下面列出了com.google.protobuf.Type#com.google.protobuf.FieldMask 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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;
}
@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());
}
@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());
}
@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());
}
@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());
}
@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());
}
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());
}
}
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());
}
}
@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());
}
}
}
}
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;
}
}
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()));
}
}
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());
}
}
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());
}
}
/**
* 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);
}
}
@Test
public void testFieldMaskAllSetFieldsOf() {
Resource resource = testCase.getModifiedResource();
FieldMask actual = FieldMasks.allSetFieldsOf(resource);
FieldMask expected = FieldMasks.compare(resource.getDefaultInstanceForType(), resource);
Truth.assertThat(expected).isEqualTo(actual);
}
@Test
public void getFieldMaskForProtoShouldReturnEmptyFieldMaskForEmptySelector() {
assertThat(
SelectorToFieldMask.getFieldMaskForProto(
DataFetchingEnvironmentImpl.newDataFetchingEnvironment().build(),
PersonOuterClass.Person.getDescriptor())
.build())
.isEqualTo(FieldMask.newBuilder().build());
}
@Test
public void getFieldMaskForChildProto() {
assertThat(
SelectorToFieldMask.getFieldMaskForProto(
DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
.mergedField(
MergedField.newMergedField()
.addField(
new Field(
"top_level_field", // QueryType
new SelectionSet(
ImmutableList.of(
new Field(
"second_level_field", // RequestType
new SelectionSet(
ImmutableList.of(
new Field(
"birthday",
new SelectionSet(
ImmutableList.of(
new Field("month")))))))))))
.build())
.build(),
PersonOuterClass.Person.getDescriptor(),
"second_level_field")
.build())
.isEqualTo(FieldMask.newBuilder().addPaths("birthday.month").build());
}
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());
}
}
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());
}
}
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());
}
}
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());
}
}
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"));
}
}
}
/**
* 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()));
}
}
}
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;
}
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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);
}
}