org.threeten.bp.Duration Java Examples

The following examples show how to use org.threeten.bp.Duration. 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: BigQueryOutput.java    From flo with Apache License 2.0 6 votes vote down vote up
@Override
public StagingTableId provide(EvalContext evalContext) {
  final String location = getDatasetOrThrow().getLocation();

  final TableId stagingTableId = bigQuery().createStagingTableId(tableId, location);
  final DatasetId stagingDatasetId = DatasetId.of(stagingTableId.getProject(), stagingTableId.getDataset());

  if (bigQuery().getDataset(stagingDatasetId) == null) {
    bigQuery().create(DatasetInfo
        .newBuilder(stagingDatasetId)
        .setLocation(location)
        .setDefaultTableLifetime(Duration.ofDays(1).toMillis())
        .build());
    LOG.info("created staging dataset: {}", stagingDatasetId);
  }

  return StagingTableId.of(this, stagingTableId);
}
 
Example #2
Source File: GcpPubSubAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "publisherBatchSettings")
public BatchingSettings publisherBatchSettings() {
	BatchingSettings.Builder builder = BatchingSettings.newBuilder();

	GcpPubSubProperties.Batching batching = this.gcpPubSubProperties.getPublisher()
			.getBatching();

	FlowControlSettings flowControlSettings = buildFlowControlSettings(batching.getFlowControl());
	if (flowControlSettings != null) {
		builder.setFlowControlSettings(flowControlSettings);
	}

	return ifNotNull(batching.getDelayThresholdSeconds(),
				(x) -> builder.setDelayThreshold(Duration.ofSeconds(x)))
			.apply(ifNotNull(batching.getElementCountThreshold(), builder::setElementCountThreshold)
			.apply(ifNotNull(batching.getEnabled(), builder::setIsEnabled)
			.apply(ifNotNull(batching.getRequestByteThreshold(), builder::setRequestByteThreshold)
			.apply(false)))) ? builder.build() : null;
}
 
Example #3
Source File: GcpPubSubAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private RetrySettings buildRetrySettings(GcpPubSubProperties.Retry retryProperties) {
	Builder builder = RetrySettings.newBuilder();

	return ifNotNull(retryProperties.getInitialRetryDelaySeconds(),
			(x) -> builder.setInitialRetryDelay(Duration.ofSeconds(x)))
			.apply(ifNotNull(retryProperties.getInitialRpcTimeoutSeconds(),
					(x) -> builder.setInitialRpcTimeout(Duration.ofSeconds(x)))
			.apply(ifNotNull(retryProperties.getJittered(), builder::setJittered)
			.apply(ifNotNull(retryProperties.getMaxAttempts(), builder::setMaxAttempts)
			.apply(ifNotNull(retryProperties.getMaxRetryDelaySeconds(),
					(x) -> builder.setMaxRetryDelay(Duration.ofSeconds(x)))
			.apply(ifNotNull(retryProperties.getMaxRpcTimeoutSeconds(),
					(x) -> builder.setMaxRpcTimeout(Duration.ofSeconds(x)))
			.apply(ifNotNull(retryProperties.getRetryDelayMultiplier(), builder::setRetryDelayMultiplier)
			.apply(ifNotNull(retryProperties.getTotalTimeoutSeconds(),
					(x) -> builder.setTotalTimeout(Duration.ofSeconds(x)))
			.apply(ifNotNull(retryProperties.getRpcTimeoutMultiplier(), builder::setRpcTimeoutMultiplier)
			.apply(false))))))))) ? builder.build() : null;
}
 
Example #4
Source File: TableSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example loading data from a single Google Cloud Storage file. */
// [TARGET load(FormatOptions, String, JobOption...)]
// [VARIABLE "gs://my_bucket/filename.csv"]
public Job loadSingle(String sourceUri) {
  // [START bigquery_load_table_gcs_csv]
  Job job = table.load(FormatOptions.csv(), sourceUri);
  // Wait for the job to complete
  try {
    Job completedJob =
        job.waitFor(
            RetryOption.initialRetryDelay(Duration.ofSeconds(1)),
            RetryOption.totalTimeout(Duration.ofMinutes(3)));
    if (completedJob != null && completedJob.getStatus().getError() == null) {
      // Job completed successfully
    } else {
      // Handle error case
    }
  } catch (InterruptedException e) {
    // Handle interrupted wait
  }
  // [END bigquery_load_table_gcs_csv]
  return job;
}
 
Example #5
Source File: GcpPubSubEmulatorAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscriberRetrySettings() {
	this.contextRunner.run((context) -> {
		RetrySettings settings = context.getBean("subscriberRetrySettings",
				RetrySettings.class);
		assertThat(settings.getTotalTimeout()).isEqualTo(Duration.ofSeconds(1));
		assertThat(settings.getInitialRetryDelay()).isEqualTo(Duration.ofSeconds(2));
		assertThat(settings.getRetryDelayMultiplier()).isEqualTo(3, DELTA);
		assertThat(settings.getMaxRetryDelay()).isEqualTo(Duration.ofSeconds(4));
		assertThat(settings.getMaxAttempts()).isEqualTo(5);
		assertThat(settings.isJittered()).isTrue();
		assertThat(settings.getInitialRpcTimeout()).isEqualTo(Duration.ofSeconds(6));
		assertThat(settings.getRpcTimeoutMultiplier()).isEqualTo(7, DELTA);
		assertThat(settings.getMaxRpcTimeout()).isEqualTo(Duration.ofSeconds(8));
	});
}
 
Example #6
Source File: GcpPubSubEmulatorAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublisherRetrySettings() {
	this.contextRunner.run((context) -> {
		RetrySettings settings = context.getBean("publisherRetrySettings",
				RetrySettings.class);
		assertThat(settings.getTotalTimeout()).isEqualTo(Duration.ofSeconds(9));
		assertThat(settings.getInitialRetryDelay()).isEqualTo(Duration.ofSeconds(10));
		assertThat(settings.getRetryDelayMultiplier()).isEqualTo(11, DELTA);
		assertThat(settings.getMaxRetryDelay()).isEqualTo(Duration.ofSeconds(12));
		assertThat(settings.getMaxAttempts()).isEqualTo(13);
		assertThat(settings.isJittered()).isTrue();
		assertThat(settings.getInitialRpcTimeout()).isEqualTo(Duration.ofSeconds(14));
		assertThat(settings.getRpcTimeoutMultiplier()).isEqualTo(15, DELTA);
		assertThat(settings.getMaxRpcTimeout()).isEqualTo(Duration.ofSeconds(16));
	});
}
 
Example #7
Source File: TableSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example extracting data to single Google Cloud Storage file. */
// [TARGET extract(String, String, JobOption...)]
// [VARIABLE "CSV"]
// [VARIABLE "gs://my_bucket/filename.csv"]
public Job extractSingle(String format, String gcsUrl) {
  // [START bigquery_extract_table]
  Job job = table.extract(format, gcsUrl);
  // Wait for the job to complete
  try {
    Job completedJob =
        job.waitFor(
            RetryOption.initialRetryDelay(Duration.ofSeconds(1)),
            RetryOption.totalTimeout(Duration.ofMinutes(3)));
    if (completedJob != null && completedJob.getStatus().getError() == null) {
      // Job completed successfully
    } else {
      // Handle error case
    }
  } catch (InterruptedException e) {
    // Handle interrupted wait
  }
  // [END bigquery_extract_table]
  return job;
}
 
Example #8
Source File: CPSPublisherTask.java    From pubsub with Apache License 2.0 6 votes vote down vote up
CPSPublisherTask(StartRequest request, MetricsHandler metricsHandler, int workerCount) {
  super(request, metricsHandler, workerCount);
  log.warn("constructing CPS publisher");
  this.payload = getPayload();
  try {
    this.publisher =
        Publisher.newBuilder(ProjectTopicName.of(request.getProject(), request.getTopic()))
            .setBatchingSettings(
                BatchingSettings.newBuilder()
                    .setElementCountThreshold((long) request.getPublisherOptions().getBatchSize())
                    .setRequestByteThreshold(9500000L)
                    .setDelayThreshold(
                        Duration.ofMillis(
                            Durations.toMillis(request.getPublisherOptions().getBatchDuration())))
                    .setIsEnabled(true)
                    .build())
            .build();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #9
Source File: TableSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of copying the table to a destination table. */
// [TARGET copy(String, String, JobOption...)]
// [VARIABLE "my_dataset"]
// [VARIABLE "my_destination_table"]
public Job copy(String datasetName, String tableName) {
  // [START ]
  Job job = table.copy(datasetName, tableName);
  // Wait for the job to complete.
  try {
    Job completedJob =
        job.waitFor(
            RetryOption.initialRetryDelay(Duration.ofSeconds(1)),
            RetryOption.totalTimeout(Duration.ofMinutes(3)));
    if (completedJob != null && completedJob.getStatus().getError() == null) {
      // Job completed successfully
    } else {
      // Handle error case
    }
  } catch (InterruptedException e) {
    // Handle interrupted wait
  }
  // [END ]
  return job;
}
 
Example #10
Source File: JobSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example usage of {@code waitFor()} with checking period and timeout. */
// [TARGET waitFor(RetryOption...)]
public boolean waitForWithOptions() throws InterruptedException {
  try {
    // [START ]
    Job completedJob =
        job.waitFor(
            RetryOption.initialRetryDelay(Duration.ofSeconds(1)),
            RetryOption.totalTimeout(Duration.ofMinutes(1)));
    if (completedJob == null) {
      // job no longer exists
    } else if (completedJob.getStatus().getError() != null) {
      // job failed, handle error
    } else {
      // job completed successfully
    }
    // [END ]
  } catch (BigQueryException e) {
    if (e.getCause() instanceof PollException) {
      return false;
    }
    throw e;
  }
  return true;
}
 
Example #11
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void test_Dublin_dst() {
    ZoneRules test = europeDublin();
    assertEquals(test.isDaylightSavings(createZDT(1960, 1, 1, ZoneOffset.UTC).toInstant()), false);
    assertEquals(test.getDaylightSavings(createZDT(1960, 1, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(0));
    assertEquals(test.isDaylightSavings(createZDT(1960, 7, 1, ZoneOffset.UTC).toInstant()), true);
    assertEquals(test.getDaylightSavings(createZDT(1960, 7, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(1));
    // check negative DST is correctly handled
    assertEquals(test.isDaylightSavings(createZDT(2016, 1, 1, ZoneOffset.UTC).toInstant()), false);
    assertEquals(test.getDaylightSavings(createZDT(2016, 1, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(0));
    assertEquals(test.isDaylightSavings(createZDT(2016, 7, 1, ZoneOffset.UTC).toInstant()), true);
    assertEquals(test.getDaylightSavings(createZDT(2016, 7, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(1));

    // TZDB data is messed up, comment out tests until better fix available
    DateTimeFormatter formatter1 = new DateTimeFormatterBuilder().appendZoneText(TextStyle.FULL).toFormatter();
    assertEquals(formatter1.format(createZDT(2016, 1, 1, ZoneId.of("Europe/Dublin"))), "Greenwich Mean Time");
    assertEquals(formatter1.format(createZDT(2016, 7, 1, ZoneId.of("Europe/Dublin"))).startsWith("Irish S"), true);

    DateTimeFormatter formatter2 = new DateTimeFormatterBuilder().appendZoneText(TextStyle.SHORT).toFormatter();
    assertEquals(formatter2.format(createZDT(2016, 1, 1, ZoneId.of("Europe/Dublin"))), "GMT");
    assertEquals(formatter2.format(createZDT(2016, 7, 1, ZoneId.of("Europe/Dublin"))), "IST");
}
 
Example #12
Source File: FormatUtils.java    From JReadHub with GNU General Public License v3.0 6 votes vote down vote up
public static String getRelativeTimeSpanString(@NonNull OffsetDateTime offsetDateTime) {
    long offset = 0;
    try {
        offset = Duration.between(offsetDateTime, OffsetDateTime.now()).toMillis();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (offset > YEAR) {
        return (offset / YEAR) + " 年前";
    } else if (offset > MONTH) {
        return (offset / MONTH) + " 个月前";
    } else if (offset > WEEK) {
        return (offset / WEEK) + " 周前";
    } else if (offset > DAY) {
        return (offset / DAY) + " 天前";
    } else if (offset > HOUR) {
        return (offset / HOUR) + " 小时前";
    } else if (offset > MINUTE) {
        return (offset / MINUTE) + " 分钟前";
    } else {
        return "刚刚";
    }
}
 
Example #13
Source File: TableSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example copying the table to a destination table. */
// [TARGET copy(TableId, JobOption...)]
// [VARIABLE "my_dataset"]
// [VARIABLE "my_destination_table"]
public Job copyTableId(String dataset, String tableName) throws BigQueryException {
  // [START bigquery_copy_table]
  TableId destinationId = TableId.of(dataset, tableName);
  JobOption options = JobOption.fields(JobField.STATUS, JobField.USER_EMAIL);
  Job job = table.copy(destinationId, options);
  // Wait for the job to complete.
  try {
    Job completedJob =
        job.waitFor(
            RetryOption.initialRetryDelay(Duration.ofSeconds(1)),
            RetryOption.totalTimeout(Duration.ofMinutes(3)));
    if (completedJob != null && completedJob.getStatus().getError() == null) {
      // Job completed successfully.
    } else {
      // Handle error case.
    }
  } catch (InterruptedException e) {
    // Handle interrupted wait
  }
  // [END bigquery_copy_table]
  return job;
}
 
Example #14
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void test_Paris_preTimeZones() {
    ZoneRules test = europeParis();
    ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC);
    Instant instant = old.toInstant();
    ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, 9, 21);
    assertEquals(test.getOffset(instant), offset);
    checkOffset(test, old.toLocalDateTime(), offset, 1);
    assertEquals(test.getStandardOffset(instant), offset);
    assertEquals(test.getDaylightSavings(instant), Duration.ZERO);
    assertEquals(test.isDaylightSavings(instant), false);
}
 
Example #15
Source File: ITFindingSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupActiveFindingsWithSourceAndCompareDuration() throws IOException {
  assertTrue(
      FindingSnippets.groupActiveFindingsWithSourceAndCompareDuration(
                  SOURCE_NAME, Duration.ofDays(1))
              .size()
          > 0);
}
 
Example #16
Source File: AssetSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Lists all project assets for an organization at a given point in time.
 *
 * @param organizationName The organization to list assets for.
 * @param asOf The snapshot time to query for assets. If null defaults to one day ago.
 */
// [START list_assets_as_of_time]
static ImmutableList<ListAssetsResult> listAssetsAsOfYesterday(
    OrganizationName organizationName, Instant asOf) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request for to search for all assets in an organization.
    // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324");

    // Initialize the builder with the organization and filter
    ListAssetsRequest.Builder request =
        ListAssetsRequest.newBuilder()
            .setParent(organizationName.toString())
            .setFilter(
                "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"");

    // Set read time to either the instant passed in or one day ago.
    asOf = MoreObjects.firstNonNull(asOf, Instant.now().minus(Duration.ofDays(1)));
    request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano());

    // Call the API.
    ListAssetsPagedResponse response = client.listAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them incrementally by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Projects:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #17
Source File: FindingSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * List findings at a specific time under a source.
 *
 * @param sourceName The source to list findings at a specific time for.
 */
// [START list_findings_at_time]
static ImmutableList<ListFindingsResult> listFindingsAtTime(SourceName sourceName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // SourceName sourceName = SourceName.of(/*organizationId=*/"123234324",
    // /*sourceId=*/"423432321");

    // 5 days ago
    Instant fiveDaysAgo = Instant.now().minus(Duration.ofDays(5));

    ListFindingsRequest.Builder request =
        ListFindingsRequest.newBuilder()
            .setParent(sourceName.toString())
            .setReadTime(
                Timestamp.newBuilder()
                    .setSeconds(fiveDaysAgo.getEpochSecond())
                    .setNanos(fiveDaysAgo.getNano()));

    // Call the API.
    ListFindingsPagedResponse response = client.listFindings(request.build());

    // This creates one list for all findings.  If your organization has a large number of
    // findings this can cause out of memory issues.  You can process them in incrementally
    // by returning the Iterable returned response.iterateAll() directly.
    ImmutableList<ListFindingsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Findings:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #18
Source File: AssetSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Groups all assets by their state_changes (ADDED/DELETED/ACTIVE) during a period of time for an
 * organization.
 *
 * @param organizationName The organization to group assets for.
 */
// [START group_all_assets_with_compare_duration]
static ImmutableList<GroupResult> groupAssetsWithCompareDuration(
    OrganizationName organizationName, Duration duration) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request for to group all assets during a period of time in an
    // organization.
    // OrganizationName organizationName = OrganizationName.of("123234324");
    GroupAssetsRequest.Builder request =
        GroupAssetsRequest.newBuilder()
            .setGroupBy("state_change")
            .setParent(organizationName.toString());
    request
        .getCompareDurationBuilder()
        .setSeconds(duration.getSeconds())
        .setNanos(duration.getNano());

    // Call the API.
    GroupAssetsPagedResponse response = client.groupAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them batches by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<GroupResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("All assets:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #19
Source File: GooglePubsubPublisher.java    From echo with Apache License 2.0 5 votes vote down vote up
public static GooglePubsubPublisher buildPublisher(
    GooglePubsubPublisherConfig config, ObjectMapper mapper) {
  GooglePubsubPublisher publisher = new GooglePubsubPublisher();
  publisher.setName(config.getName());
  ProjectTopicName fullName = ProjectTopicName.of(config.getProject(), config.getTopicName());
  publisher.setTopicName(config.getTopicName());
  publisher.setFullTopicName(fullName.toString());
  publisher.setContent(config.getContent());
  publisher.setMapper(mapper);

  BatchingSettings batchingSettings =
      BatchingSettings.newBuilder()
          .setElementCountThreshold(config.getBatchCountThreshold())
          .setDelayThreshold(Duration.ofMillis(config.getDelayMillisecondsThreshold()))
          .build();

  try {
    Publisher p =
        Publisher.newBuilder(fullName)
            .setCredentialsProvider(new GooglePubsubCredentialsProvider(config.getJsonPath()))
            .setBatchingSettings(batchingSettings)
            .build();
    publisher.setPublisher(p);
  } catch (IOException ioe) {
    log.error("Could not create Google Pubsub Publishers", ioe);
  }

  return publisher;
}
 
Example #20
Source File: FindingSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Group active findings under an organization and a source by their state_changes
 * (ADDED/CHANGED/UNCHANGED) during a period.
 *
 * @param sourceName The source to limit the findings to.
 */
// [START group_active_findings_with_source_and_compare_duration]
static ImmutableList<GroupResult> groupActiveFindingsWithSourceAndCompareDuration(
    SourceName sourceName, Duration duration) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/
    // "423432321");

    GroupFindingsRequest.Builder request =
        GroupFindingsRequest.newBuilder()
            .setParent(sourceName.toString())
            .setGroupBy("state_change")
            .setFilter("state=\"ACTIVE\"");
    request
        .getCompareDurationBuilder()
        .setSeconds(duration.getSeconds())
        .setNanos(duration.getNano());

    // Call the API.
    GroupFindingsPagedResponse response = client.groupFindings(request.build());

    // This creates one list for all findings.  If your organization has a large number of
    // findings
    // this can cause out of memory issues.  You can process them batches by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<GroupResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Findings:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #21
Source File: TestFixedZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_data_nullInput() {
    ZoneRules test = make(OFFSET_PONE);
    assertEquals(test.getOffset((Instant) null), OFFSET_PONE);
    assertEquals(test.getOffset((LocalDateTime) null), OFFSET_PONE);
    assertEquals(test.getValidOffsets(null).size(), 1);
    assertEquals(test.getValidOffsets(null).get(0), OFFSET_PONE);
    assertEquals(test.getTransition(null), null);
    assertEquals(test.getStandardOffset(null), OFFSET_PONE);
    assertEquals(test.getDaylightSavings(null), Duration.ZERO);
    assertEquals(test.isDaylightSavings(null), false);
    assertEquals(test.nextTransition(null), null);
    assertEquals(test.previousTransition(null), null);
}
 
Example #22
Source File: TestZoneOffsetTransition.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_getters_gap() throws Exception {
    LocalDateTime before = LocalDateTime.of(2010, 3, 31, 1, 0);
    LocalDateTime after = LocalDateTime.of(2010, 3, 31, 2, 0);
    ZoneOffsetTransition test = ZoneOffsetTransition.of(before, OFFSET_0200, OFFSET_0300);
    assertEquals(test.isGap(), true);
    assertEquals(test.isOverlap(), false);
    assertEquals(test.getDateTimeBefore(), before);
    assertEquals(test.getDateTimeAfter(), after);
    assertEquals(test.getInstant(), before.toInstant(OFFSET_0200));
    assertEquals(test.getOffsetBefore(), OFFSET_0200);
    assertEquals(test.getOffsetAfter(), OFFSET_0300);
    assertEquals(test.getDuration(), Duration.of(1, HOURS));
    assertSerializable(test);
}
 
Example #23
Source File: TestZoneOffsetTransition.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_getters_overlap() throws Exception {
    LocalDateTime before = LocalDateTime.of(2010, 10, 31, 1, 0);
    LocalDateTime after = LocalDateTime.of(2010, 10, 31, 0, 0);
    ZoneOffsetTransition test = ZoneOffsetTransition.of(before, OFFSET_0300, OFFSET_0200);
    assertEquals(test.isGap(), false);
    assertEquals(test.isOverlap(), true);
    assertEquals(test.getDateTimeBefore(), before);
    assertEquals(test.getDateTimeAfter(), after);
    assertEquals(test.getInstant(), before.toInstant(OFFSET_0300));
    assertEquals(test.getOffsetBefore(), OFFSET_0300);
    assertEquals(test.getOffsetAfter(), OFFSET_0200);
    assertEquals(test.getDuration(), Duration.of(-1, HOURS));
    assertSerializable(test);
}
 
Example #24
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void test_London_preTimeZones() {
    ZoneRules test = europeLondon();
    ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC);
    Instant instant = old.toInstant();
    ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, -1, -15);
    assertEquals(test.getOffset(instant), offset);
    checkOffset(test, old.toLocalDateTime(), offset, 1);
    assertEquals(test.getStandardOffset(instant), offset);
    assertEquals(test.getDaylightSavings(instant), Duration.ZERO);
    assertEquals(test.isDaylightSavings(instant), false);
}
 
Example #25
Source File: TestStandardZoneRules.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void test_NewYork_preTimeZones() {
    ZoneRules test = americaNewYork();
    ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC);
    Instant instant = old.toInstant();
    ZoneOffset offset = ZoneOffset.of("-04:56:02");
    assertEquals(test.getOffset(instant), offset);
    checkOffset(test, old.toLocalDateTime(), offset, 1);
    assertEquals(test.getStandardOffset(instant), offset);
    assertEquals(test.getDaylightSavings(instant), Duration.ZERO);
    assertEquals(test.isDaylightSavings(instant), false);
}
 
Example #26
Source File: ITAssetSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupAssetsWithCompareDuration() {
  ImmutableList<GroupResult> results =
      AssetSnippets.groupAssetsWithCompareDuration(
          getOrganizationId(), Duration.ofSeconds(86400));
  assertTrue(results.size() > 0);
}
 
Example #27
Source File: AssetSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns Assets and metadata about assets activity (e.g. added, removed, no change) between
 * between <code>asOf.minus(timespan)</code> and <code>asOf</code>.
 *
 * @param timeSpan The time-range to compare assets over.
 * @param asOf The instant in time to query for. If null, current time is assumed.
 */
// [START list_asset_changes_status_changes]
static ImmutableList<ListAssetsResult> listAssetAndStatusChanges(
    OrganizationName organizationName, Duration timeSpan, Instant asOf) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {

    // Start setting up a request for to search for all assets in an organization.
    // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324");
    ListAssetsRequest.Builder request =
        ListAssetsRequest.newBuilder()
            .setParent(organizationName.toString())
            .setFilter(
                "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"");
    request
        .getCompareDurationBuilder()
        .setSeconds(timeSpan.getSeconds())
        .setNanos(timeSpan.getNano());

    // Set read time to either the instant passed in or now.
    asOf = MoreObjects.firstNonNull(asOf, Instant.now());
    request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano());

    // Call the API.
    ListAssetsPagedResponse response = client.listAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them incrementally by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Projects:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #28
Source File: PerformanceBenchmark.java    From kafka-pubsub-emulator with Apache License 2.0 5 votes vote down vote up
private Publisher getPublisher() throws IOException {
  return Publisher.newBuilder(topic)
      .setCredentialsProvider(credentialsProvider)
      .setChannelProvider(getChannelProvider())
      // Batching settings borrowed from PubSub Load Test Framework
      .setBatchingSettings(
          BatchingSettings.newBuilder()
              .setElementCountThreshold(950L)
              .setRequestByteThreshold(9500000L)
              .setDelayThreshold(Duration.ofMillis(10))
              .build())
      .build();
}
 
Example #29
Source File: TableSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example loading data from a list of Google Cloud Storage files. */
// [TARGET load(FormatOptions, List, JobOption...)]
// [VARIABLE "gs://my_bucket/filename1.csv"]
// [VARIABLE "gs://my_bucket/filename2.csv"]
public Job loadList(String gcsUrl1, String gcsUrl2) {
  // [START ]
  List<String> sourceUris = new ArrayList<>();
  sourceUris.add(gcsUrl1);
  sourceUris.add(gcsUrl2);
  Job job = table.load(FormatOptions.csv(), sourceUris);
  // Wait for the job to complete
  try {
    Job completedJob =
        job.waitFor(
            RetryOption.initialRetryDelay(Duration.ofSeconds(1)),
            RetryOption.totalTimeout(Duration.ofMinutes(3)));
    if (completedJob != null && completedJob.getStatus().getError() == null) {
      // Job completed successfully
    } else {
      // Handle error case
    }
  } catch (InterruptedException e) {
    // Handle interrupted wait
  }
  // [END ]
  return job;
}
 
Example #30
Source File: TableSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example of partitioning data to a list of Google Cloud Storage files. */
// [TARGET extract(String, List, JobOption...)]
// [VARIABLE "CSV"]
// [VARIABLE "gs://my_bucket/PartitionA_*.csv"]
// [VARIABLE "gs://my_bucket/PartitionB_*.csv"]
public Job extractList(String format, String gcsUrl1, String gcsUrl2) {
  // [START ]
  List<String> destinationUris = new ArrayList<>();
  destinationUris.add(gcsUrl1);
  destinationUris.add(gcsUrl2);
  Job job = table.extract(format, destinationUris);
  // Wait for the job to complete
  try {
    Job completedJob =
        job.waitFor(
            RetryOption.initialRetryDelay(Duration.ofSeconds(1)),
            RetryOption.totalTimeout(Duration.ofMinutes(3)));
    if (completedJob != null && completedJob.getStatus().getError() == null) {
      // Job completed successfully
    } else {
      // Handle error case
    }
  } catch (InterruptedException e) {
    // Handle interrupted wait
  }
  // [END ]
  return job;
}