Group assets by state

Demonstrates how to group assets by state change

Code sample

Java

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);
  }
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.