com.google.protobuf.FieldMask Java Examples

The following examples show how to use com.google.protobuf.FieldMask. 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: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void getFieldMaskForProtoShouldReturnMultipleNestedField() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field",
                                      new SelectionSet(
                                          ImmutableList.of(
                                              new Field(
                                                  "birthday",
                                                  new SelectionSet(
                                                      ImmutableList.of(
                                                          new Field("day"),
                                                          new Field("month"))))))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor())
              .build())
      .isEqualTo(
          FieldMask.newBuilder().addPaths("birthday.day").addPaths("birthday.month").build());
}
 
Example #2
Source File: SnippetsIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void afterAll() throws IOException {
  Assert.assertFalse("missing GOOGLE_CLOUD_PROJECT", Strings.isNullOrEmpty(PROJECT_ID));

  // Iterate over each key ring's key's crypto key versions and destroy.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    for (CryptoKey key : client.listCryptoKeys(getKeyRingName()).iterateAll()) {
      if (key.hasRotationPeriod() || key.hasNextRotationTime()) {
        CryptoKey keyWithoutRotation = CryptoKey.newBuilder().setName(key.getName()).build();
        FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");
        client.updateCryptoKey(keyWithoutRotation, fieldMask);
      }

      ListCryptoKeyVersionsRequest listVersionsRequest =
          ListCryptoKeyVersionsRequest.newBuilder()
              .setParent(key.getName())
              .setFilter("state != DESTROYED AND state != DESTROY_SCHEDULED")
              .build();
      for (CryptoKeyVersion version :
          client.listCryptoKeyVersions(listVersionsRequest).iterateAll()) {
        client.destroyCryptoKeyVersion(version.getName());
      }
    }
  }
}
 
Example #3
Source File: UptimeSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void updateUptimeCheck(
    String projectId, String displayName, String hostName, String pathName) throws IOException {
  String fullCheckName = UptimeCheckConfigName.format(projectId, displayName);

  UpdateUptimeCheckConfigRequest request =
      UpdateUptimeCheckConfigRequest.newBuilder()
          .setUpdateMask(FieldMask.newBuilder().addPaths("http_check.path"))
          .setUptimeCheckConfig(
              UptimeCheckConfig.newBuilder()
                  .setName(fullCheckName)
                  .setMonitoredResource(
                      MonitoredResource.newBuilder()
                          .setType("uptime_url")
                          .putLabels("host", hostName))
                  .setHttpCheck(HttpCheck.newBuilder().setPath(pathName).setPort(80))
                  .setTimeout(Duration.newBuilder().setSeconds(10))
                  .setPeriod(Duration.newBuilder().setSeconds(300)))
          .build();
  try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
    UptimeCheckConfig config = client.updateUptimeCheckConfig(request);
    System.out.println("Uptime check updated: \n" + config.toString());
  } catch (Exception e) {
    usage("Exception updating uptime check: " + e.toString());
    throw e;
  }
}
 
Example #4
Source File: UpdateKeyRemoveLabels.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void updateKeyRemoveLabels(
    String projectId, String locationId, String keyRingId, String keyId) throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the name from the project, location, key ring, and keyId.
    CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Build an empty key with no labels.
    CryptoKey key = CryptoKey.newBuilder().setName(cryptoKeyName.toString()).build();

    // Construct the field mask.
    FieldMask fieldMask = FieldMaskUtil.fromString("labels");

    // Create the key.
    CryptoKey createdKey = client.updateCryptoKey(key, fieldMask);
    System.out.printf("Updated key %s%n", createdKey.getName());
  }
}
 
Example #5
Source File: UpdateKeyRemoveRotation.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void updateKeyRemoveRotation(
    String projectId, String locationId, String keyRingId, String keyId) throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the name from the project, location, key ring, and keyId.
    CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Build an empty key with no labels.
    CryptoKey key =
        CryptoKey.newBuilder()
            .setName(cryptoKeyName.toString())
            .clearRotationPeriod()
            .clearNextRotationTime()
            .build();

    // Construct the field mask.
    FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");

    // Create the key.
    CryptoKey createdKey = client.updateCryptoKey(key, fieldMask);
    System.out.printf("Updated key %s%n", createdKey.getName());
  }
}
 
Example #6
Source File: AlertSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void replaceChannels(String projectId, String alertPolicyId, String[] channelIds)
    throws IOException {
  AlertPolicy.Builder policyBuilder =
      AlertPolicy.newBuilder().setName(AlertPolicyName.of(projectId, alertPolicyId).toString());
  for (String channelId : channelIds) {
    policyBuilder.addNotificationChannels(
        NotificationChannelName.of(projectId, channelId).toString());
  }
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    AlertPolicy result =
        client.updateAlertPolicy(
            FieldMask.newBuilder().addPaths("notification_channels").build(),
            policyBuilder.build());
    System.out.println(String.format("Updated %s", result.getName()));
  }
}
 
Example #7
Source File: UpdateSecret.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public void updateSecret(String projectId, String secretId) throws IOException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
    // Build the name.
    SecretName secretName = SecretName.of(projectId, secretId);

    // Build the updated secret.
    Secret secret =
        Secret.newBuilder()
            .setName(secretName.toString())
            .putLabels("secretmanager", "rocks")
            .build();

    // Build the field mask.
    FieldMask fieldMask = FieldMaskUtil.fromString("labels");

    // Create the secret.
    Secret updatedSecret = client.updateSecret(secret, fieldMask);
    System.out.printf("Updated secret %s\n", updatedSecret.getName());
  }
}
 
Example #8
Source File: UpdateFeedExample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static void updateFeed(String feedName, String topic) throws Exception {
  // String feedName = "MY_FEED_NAME"
  // String topic = "projects/[PROJECT_ID]/topics/[TOPIC_NAME]"
  Feed feed = Feed.newBuilder()
      .setName(feedName)
      .setFeedOutputConfig(
          FeedOutputConfig.newBuilder().setPubsubDestination(
              PubsubDestination.newBuilder().setTopic(topic).build()).build()).build();
  UpdateFeedRequest request = UpdateFeedRequest.newBuilder()
      .setFeed(feed)
      .setUpdateMask(
        FieldMask.newBuilder().addPaths("feed_output_config.pubsub_destination.topic").build())
      .build();
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AssetServiceClient client = AssetServiceClient.create()) {
    Feed response = client.updateFeed(request);
    System.out.println("Feed updated successfully: " + response.getName());
  } catch (Exception e) {
    System.out.println("Error during UpdateFeed: \n" + e.toString());
  }
}
 
Example #9
Source File: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void getFieldMaskForProtoShouldFallbackToStarPathIfSubSelectorNameDoesntMatchProto() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field",
                                      new SelectionSet(
                                          ImmutableList.of(
                                              new Field(
                                                  "birthday",
                                                  new SelectionSet(
                                                      ImmutableList.of(new Field("unknown"))))))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor())
              .build())
      .isEqualTo(FieldMask.newBuilder().addPaths("birthday.*").build());
}
 
Example #10
Source File: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void getFieldMaskForProtoShouldReturnNestedField() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field",
                                      new SelectionSet(
                                          ImmutableList.of(
                                              new Field(
                                                  "birthday",
                                                  new SelectionSet(
                                                      ImmutableList.of(new Field("month"))))))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor())
              .build())
      .isEqualTo(FieldMask.newBuilder().addPaths("birthday.month").build());
}
 
Example #11
Source File: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void getFieldMaskForProtoShouldIgnoreSelectorsNotInProto() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field",
                                      new SelectionSet(
                                          ImmutableList.of(
                                              new Field("username"),
                                              new Field("notInPersonProto")))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor())
              .build())
      .isEqualTo(FieldMask.newBuilder().addPaths("username").build());
}
 
Example #12
Source File: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void getFieldMaskForProtoShouldReturnSingleField() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field",
                                      new SelectionSet(ImmutableList.of(new Field("username")))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor())
              .build())
      .isEqualTo(FieldMask.newBuilder().addPaths("username").build());
}
 
Example #13
Source File: SelectorToFieldMask.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
public static Builder getFieldMaskForProto(
    DataFetchingEnvironment environment, Descriptor descriptor) {

  Map<String, FragmentDefinition> fragmentsByName = environment.getFragmentsByName();

  Builder maskFromSelectionBuilder = FieldMask.newBuilder();
  for (Field field :
      Optional.ofNullable(environment.getMergedField())
          .map(MergedField::getFields)
          .orElse(ImmutableList.of())) {
    for (Selection<?> selection : field.getSelectionSet().getSelections()) {
      maskFromSelectionBuilder.addAllPaths(
          getPathsForProto("", selection, descriptor, fragmentsByName));
    }
  }
  return maskFromSelectionBuilder;
}
 
Example #14
Source File: SelectorToFieldMask.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
public static Builder getFieldMaskForProto(
    DataFetchingEnvironment environment, Descriptor descriptor, String startAtFieldName) {

  Map<String, FragmentDefinition> fragmentsByName = environment.getFragmentsByName();

  Builder maskFromSelectionBuilder = FieldMask.newBuilder();

  for (Field field : environment.getFields()) {
    for (Selection<?> selection1 : field.getSelectionSet().getSelections()) {
      if (selection1 instanceof Field) {
        Field field2 = (Field) selection1;
        if (field2.getName().equals(startAtFieldName)) {
          for (Selection<?> selection : field2.getSelectionSet().getSelections()) {
            maskFromSelectionBuilder.addAllPaths(
                getPathsForProto("", selection, descriptor, fragmentsByName));
          }
        }
      }
    }
  }
  return maskFromSelectionBuilder;
}
 
Example #15
Source File: SourceSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/**
 * Update a source under an organization.
 *
 * @param sourceName The source to update.
 */
// [START update_source]
static Source updateSource(SourceName sourceName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to update a source.
    // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/
    // "423432321");
    Source source =
        Source.newBuilder()
            .setDisplayName("Updated Display Name")
            .setName(sourceName.toString())
            .build();
    FieldMask updateMask = FieldMask.newBuilder().addPaths("display_name").build();

    UpdateSourceRequest.Builder request =
        UpdateSourceRequest.newBuilder().setSource(source).setUpdateMask(updateMask);

    // Call the API.
    Source response = client.updateSource(request.build());

    System.out.println("Updated Source: " + response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #16
Source File: SecurityMarkSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Add security mark to an asset.
 *
 * @param assetName The asset resource to add the security mark for.
 */
// [START add_to_asset]
static SecurityMarks addToAsset(String assetName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // String assetName = "organizations/123123342/assets/12312321";
    // Start setting up a request to add security marks for an asset.
    ImmutableMap markMap = ImmutableMap.of("key_a", "value_a", "key_b", "value_b");

    // Add security marks and field mask for security marks.
    SecurityMarks securityMarks =
        SecurityMarks.newBuilder()
            .setName(assetName + "/securityMarks")
            .putAllMarks(markMap)
            .build();
    FieldMask updateMask =
        FieldMask.newBuilder().addPaths("marks.key_a").addPaths("marks.key_b").build();

    UpdateSecurityMarksRequest request =
        UpdateSecurityMarksRequest.newBuilder()
            .setSecurityMarks(securityMarks)
            .setUpdateMask(updateMask)
            .build();

    // Call the API.
    SecurityMarks response = client.updateSecurityMarks(request);

    System.out.println("Security Marks:");
    System.out.println(response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #17
Source File: FieldMaskTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void itSetsFieldMaskWhenEmptyInJson() throws IOException {
  String json = "{\"fieldMask\":\"\"}";
  HasFieldMask message = camelCase().readValue(json, HasFieldMask.class);
  assertThat(message.hasFieldMask()).isTrue();
  assertThat(message.getFieldMask()).isEqualTo(FieldMask.getDefaultInstance());
}
 
Example #18
Source File: OrganizationSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Update Asset Discovery OrganizationSettings for an organization
 *
 * @param organizationName The organization to update settings for.
 */
// [START update_organization_settings]
static OrganizationSettings updateOrganizationSettings(OrganizationName organizationName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to update OrganizationSettings for.
    // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324");
    OrganizationSettings organizationSettings =
        OrganizationSettings.newBuilder()
            .setName(organizationName.toString() + "/organizationSettings")
            .setEnableAssetDiscovery(true)
            .build();
    FieldMask updateMask = FieldMask.newBuilder().addPaths("enable_asset_discovery").build();

    UpdateOrganizationSettingsRequest.Builder request =
        UpdateOrganizationSettingsRequest.newBuilder()
            .setOrganizationSettings(organizationSettings)
            .setUpdateMask(updateMask);

    // Call the API.
    OrganizationSettings response = client.updateOrganizationSettings(request.build());

    System.out.println("Organization Settings have been updated:");
    System.out.println(response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #19
Source File: UpdateNotificationConfigSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static NotificationConfig updateNotificationConfig(
    String organizationId, String notificationConfigId, String projectId, String topicName)
    throws IOException {
  // String organizationId = "{your-org-id}";
  // String notificationConfigId = "{your-config-id}";
  // String projectId = "{your-project}";
  // String topicName = "{your-topic}";

  String notificationConfigName =
      String.format(
          "organizations/%s/notificationConfigs/%s", organizationId, notificationConfigId);

  // Ensure this ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the topic.
  String pubsubTopic = String.format("projects/%s/topics/%s", projectId, topicName);

  NotificationConfig configToUpdate =
      NotificationConfig.newBuilder()
          .setName(notificationConfigName)
          .setDescription("updated description")
          .setPubsubTopic(pubsubTopic)
          .setStreamingConfig(StreamingConfig.newBuilder().setFilter("state = \"ACTIVE\""))
          .build();
  FieldMask fieldMask =
      FieldMask.newBuilder()
        .addPaths("description")
        .addPaths("pubsub_topic")
        .addPaths("streaming_config.filter").build();

  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    NotificationConfig updatedConfig = client.updateNotificationConfig(configToUpdate, fieldMask);

    System.out.println(String.format("Notification config: %s", updatedConfig));
    return updatedConfig;
  }
}
 
Example #20
Source File: ProductManagement.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Update the product labels.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId -Id of the product.
 * @param productLabels - Labels of the product.
 * @throws IOException - on I/O errors.
 */
public static void updateProductLabels(
    String projectId, String computeRegion, String productId, String productLabels)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product.
    String formattedName =
        ProductSearchClient.formatProductName(projectId, computeRegion, productId);

    // Set product name, product labels and product display name.
    // Multiple labels are also supported.
    Product product =
        Product.newBuilder()
            .setName(formattedName)
            .addProductLabels(
                KeyValue.newBuilder()
                    .setKey(productLabels.split(",")[0].split("=")[0])
                    .setValue(productLabels.split(",")[0].split("=")[1])
                    .build())
            .build();

    // Set product update field name.
    FieldMask updateMask = FieldMask.newBuilder().addPaths("product_labels").build();

    // Update the product.
    Product updatedProduct = client.updateProduct(product, updateMask);
    // Display the product information
    System.out.println(String.format("Product name: %s", updatedProduct.getName()));
    System.out.println(String.format("Updated product labels: "));
    for (Product.KeyValue element : updatedProduct.getProductLabelsList()) {
      System.out.println(String.format("%s: %s", element.getKey(), element.getValue()));
    }
  }
}
 
Example #21
Source File: SecurityMarkSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Clear security marks for an asset.
 *
 * @param assetName The asset resource to clear the security marks for.
 */
// [START clear_from_asset]
static SecurityMarks clearFromAsset(String assetName) {
  // String assetName = "organizations/123123342/assets/12312321";
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to clear security marks for an asset.
    // Create security mark and field mask for clearing security marks.
    SecurityMarks securityMarks =
        SecurityMarks.newBuilder().setName(assetName + "/securityMarks").build();
    FieldMask updateMask =
        FieldMask.newBuilder().addPaths("marks.key_a").addPaths("marks.key_b").build();

    UpdateSecurityMarksRequest request =
        UpdateSecurityMarksRequest.newBuilder()
            .setSecurityMarks(securityMarks)
            .setUpdateMask(updateMask)
            .build();

    // Call the API.
    SecurityMarks response = client.updateSecurityMarks(request);

    System.out.println("Security Marks cleared:");
    System.out.println(response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #22
Source File: AlertSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static void enablePolicies(String projectId, String filter, boolean enable)
    throws IOException {
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    ListAlertPoliciesPagedResponse response =
        client.listAlertPolicies(
            ListAlertPoliciesRequest.newBuilder()
                .setName(ProjectName.of(projectId).toString())
                .setFilter(filter)
                .build());

    for (AlertPolicy policy : response.iterateAll()) {
      if (policy.getEnabled().getValue() == enable) {
        System.out.println(
            String.format(
                "Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled"));
        continue;
      }
      AlertPolicy updatedPolicy =
          AlertPolicy.newBuilder()
              .setName(policy.getName())
              .setEnabled(BoolValue.newBuilder().setValue(enable))
              .build();
      AlertPolicy result =
          client.updateAlertPolicy(
              FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy);
      System.out.println(
          String.format(
              "%s %s",
              result.getDisplayName(), result.getEnabled().getValue() ? "enabled" : "disabled"));
    }
  }
}
 
Example #23
Source File: SecurityMarkSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes and updates a security mark for an asset.
 *
 * @param assetName The asset resource path to update and remove the security marks for.
 */
// [START delete_and_update_marks]
static SecurityMarks deleteAndUpdateMarks(String assetName) {
  // String assetName = "organizations/123123342/assets/12312321";
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to clear and update security marks for an asset.
    // Create security mark and field mask for clearing security marks.
    SecurityMarks securityMarks =
        SecurityMarks.newBuilder()
            .setName(assetName + "/securityMarks")
            .putMarks("key_a", "new_value_for_a")
            .build();
    FieldMask updateMask =
        FieldMask.newBuilder().addPaths("marks.key_a").addPaths("marks.key_b").build();

    UpdateSecurityMarksRequest request =
        UpdateSecurityMarksRequest.newBuilder()
            .setSecurityMarks(securityMarks)
            .setUpdateMask(updateMask)
            .build();

    // Call the API.
    SecurityMarks response = client.updateSecurityMarks(request);

    System.out.println("Security Marks updated and cleared:");
    System.out.println(response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #24
Source File: SecurityMarkSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Add security mark to a finding.
 *
 * @param findingName The finding resource path to add the security mark for.
 */
// [START add_to_finding]
static SecurityMarks addToFinding(FindingName findingName) {
  // FindingName findingName = FindingName.of(/*organization=*/"123234324",
  // /*source=*/"423432321", /*findingId=*/"samplefindingid2");
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to add security marks for a finding.
    ImmutableMap markMap = ImmutableMap.of("key_a", "value_a", "key_b", "value_b");

    // Add security marks and field mask for security marks.
    SecurityMarks securityMarks =
        SecurityMarks.newBuilder()
            .setName(findingName + "/securityMarks")
            .putAllMarks(markMap)
            .build();
    FieldMask updateMask =
        FieldMask.newBuilder().addPaths("marks.key_a").addPaths("marks.key_b").build();

    UpdateSecurityMarksRequest request =
        UpdateSecurityMarksRequest.newBuilder()
            .setSecurityMarks(securityMarks)
            .setUpdateMask(updateMask)
            .build();

    // Call the API.
    SecurityMarks response = client.updateSecurityMarks(request);

    System.out.println("Security Marks:");
    System.out.println(response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #25
Source File: FieldMaskDeserializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Override
public FieldMask deserialize(JsonParser parser, DeserializationContext context) throws IOException {
  switch (parser.getCurrentToken()) {
    case VALUE_STRING:
      return FieldMaskUtil.fromJsonString(parser.getText());
    default:
      context.reportWrongTokenException(FieldMask.class, JsonToken.VALUE_STRING, wrongTokenMessage(context));
      // the previous method should have thrown
      throw new AssertionError();
  }
}
 
Example #26
Source File: FieldMaskSerializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(
        FieldMask fieldMask,
        JsonGenerator generator,
        SerializerProvider serializerProvider
) throws IOException {
  generator.writeString(FieldMaskUtil.toJsonString(fieldMask));
}
 
Example #27
Source File: EnableKeyVersion.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void enableKeyVersion(
    String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
    throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the key version name from the project, location, key ring, key,
    // and key version.
    CryptoKeyVersionName keyVersionName =
        CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

    // Build the updated key version, setting it to enabled.
    CryptoKeyVersion keyVersion =
        CryptoKeyVersion.newBuilder()
            .setName(keyVersionName.toString())
            .setState(CryptoKeyVersionState.ENABLED)
            .build();

    // Create a field mask of updated values.
    FieldMask fieldMask = FieldMaskUtil.fromString("state");

    // Destroy the key version.
    CryptoKeyVersion response = client.updateCryptoKeyVersion(keyVersion, fieldMask);
    System.out.printf("Enabled key version: %s%n", response.getName());
  }
}
 
Example #28
Source File: UpdateKeyUpdateLabels.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void updateKeyUpdateLabels(
    String projectId, String locationId, String keyRingId, String keyId) throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the parent name from the project, location, and key ring.
    CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    //
    // Step 1 - get the current set of labels on the key
    //

    // Get the current key.
    CryptoKey key = client.getCryptoKey(cryptoKeyName);

    //
    // Step 2 - add a label to the list of labels
    //

    // Add a new label.
    key = key.toBuilder().putLabels("new_label", "new_value").build();

    // Construct the field mask.
    FieldMask fieldMask = FieldMaskUtil.fromString("labels");

    // Update the key.
    CryptoKey updatedKey = client.updateCryptoKey(key, fieldMask);
    System.out.printf("Updated key %s%n", updatedKey.getName());
  }
}
 
Example #29
Source File: DisableKeyVersion.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void disableKeyVersion(
    String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
    throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the key version name from the project, location, key ring, key,
    // and key version.
    CryptoKeyVersionName keyVersionName =
        CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId);

    // Build the updated key version, setting it to disbaled.
    CryptoKeyVersion keyVersion =
        CryptoKeyVersion.newBuilder()
            .setName(keyVersionName.toString())
            .setState(CryptoKeyVersionState.DISABLED)
            .build();

    // Create a field mask of updated values.
    FieldMask fieldMask = FieldMaskUtil.fromString("state");

    // Destroy the key version.
    CryptoKeyVersion response = client.updateCryptoKeyVersion(keyVersion, fieldMask);
    System.out.printf("Disabled key version: %s%n", response.getName());
  }
}
 
Example #30
Source File: UpdateKeyAddRotation.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void updateKeyAddRotation(
    String projectId, String locationId, String keyRingId, String keyId) throws IOException {
  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests. After
  // completing all of your requests, call the "close" method on the client to
  // safely clean up any remaining background resources.
  try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
    // Build the name from the project, location, and key ring.
    CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

    // Calculate the date 24 hours from now (this is used below).
    long tomorrow = java.time.Instant.now().plus(24, ChronoUnit.HOURS).getEpochSecond();

    // Build the key to update with a rotation schedule.
    CryptoKey key =
        CryptoKey.newBuilder()
            .setName(cryptoKeyName.toString())
            .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
            .setVersionTemplate(
                CryptoKeyVersionTemplate.newBuilder()
                    .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))

            // Rotate every 30 days.
            .setRotationPeriod(
                Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))

            // Start the first rotation in 24 hours.
            .setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow))
            .build();

    // Construct the field mask.
    FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");

    // Update the key.
    CryptoKey updatedKey = client.updateCryptoKey(key, fieldMask);
    System.out.printf("Updated key %s%n", updatedKey.getName());
  }
}