use of com.google.privacy.dlp.v2.InspectConfig in project java-docs-samples by GoogleCloudPlatform.
the class Templates method listInspectTemplates.
// [END dlp_create_inspect_template]
// [START dlp_list_inspect_templates]
/**
* List DLP inspection templates created in a given project
*
* @param projectId Google Cloud Project ID
*/
private static void listInspectTemplates(String projectId) {
try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
ListInspectTemplatesRequest request = ListInspectTemplatesRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setPageSize(1).build();
ListInspectTemplatesPagedResponse response = dlpServiceClient.listInspectTemplates(request);
ListInspectTemplatesPage page = response.getPage();
ListInspectTemplatesResponse templatesResponse = page.getResponse();
for (InspectTemplate template : templatesResponse.getInspectTemplatesList()) {
System.out.printf("Template name: %s\n", template.getName());
if (template.getDisplayName() != null) {
System.out.printf("\tDisplay name: %s \n", template.getDisplayName());
System.out.printf("\tCreate time: %s \n", template.getCreateTime());
System.out.printf("\tUpdate time: %s \n", template.getUpdateTime());
// print inspection config
InspectConfig inspectConfig = template.getInspectConfig();
for (InfoType infoType : inspectConfig.getInfoTypesList()) {
System.out.printf("\tInfoType: %s\n", infoType.getName());
}
System.out.printf("\tMin likelihood: %s\n", inspectConfig.getMinLikelihood());
System.out.printf("\tLimits: %s\n", inspectConfig.getLimits().getMaxFindingsPerRequest());
}
}
} catch (Exception e) {
System.out.printf("Error creating template: %s", e.getMessage());
}
}
use of com.google.privacy.dlp.v2.InspectConfig in project java-docs-samples by GoogleCloudPlatform.
the class Templates method createInspectTemplate.
// [START dlp_create_inspect_template]
/**
* Create a new DLP inspection configuration template.
*
* @param displayName (Optional) The human-readable name to give the template
* @param projectId Google Cloud Project ID to call the API under
* @param templateId (Optional) The name of the template to be created
* @param infoTypeList The infoTypes of information to match
* @param minLikelihood The minimum likelihood required before returning a match
* @param maxFindings The maximum number of findings to report per request (0 = server maximum)
*/
private static void createInspectTemplate(String displayName, String templateId, String description, String projectId, List<InfoType> infoTypeList, Likelihood minLikelihood, int maxFindings) {
try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
FindingLimits findingLimits = FindingLimits.newBuilder().setMaxFindingsPerRequest(maxFindings).build();
// Construct the inspection configuration for the template
InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypeList).setMinLikelihood(minLikelihood).setLimits(findingLimits).build();
InspectTemplate inspectTemplate = InspectTemplate.newBuilder().setInspectConfig(inspectConfig).setDisplayName(displayName).setDescription(description).build();
CreateInspectTemplateRequest createInspectTemplateRequest = CreateInspectTemplateRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setInspectTemplate(inspectTemplate).setTemplateId(templateId).build();
InspectTemplate response = dlpServiceClient.createInspectTemplate(createInspectTemplateRequest);
System.out.printf("Template created: %s", response.getName());
} catch (Exception e) {
System.out.printf("Error creating template: %s", e.getMessage());
}
}
use of com.google.privacy.dlp.v2.InspectConfig in project java-docs-samples by GoogleCloudPlatform.
the class DeIdentification method reIdentifyWithFpe.
// [END dlp_deidentify_fpe]
// [START dlp_reidentify_fpe]
/**
* Reidentify a string by encrypting sensitive information while preserving format.
*
* @param string The string to reidentify.
* @param alphabet The set of characters used when encrypting the input. For more information, see
* cloud.google.com/dlp/docs/reference/rest/v2/content/deidentify
* @param keyName The name of the Cloud KMS key to use when decrypting the wrapped key.
* @param wrappedKey The encrypted (or "wrapped") AES-256 encryption key.
* @param projectId ID of Google Cloud project to run the API under.
* @param surrogateType The name of the surrogate custom info type to used during the encryption
* process.
*/
private static void reIdentifyWithFpe(String string, FfxCommonNativeAlphabet alphabet, String keyName, String wrappedKey, String projectId, String surrogateType) {
// instantiate a client
try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
ContentItem contentItem = ContentItem.newBuilder().setValue(string).build();
InfoType surrogateTypeObject = InfoType.newBuilder().setName(surrogateType).build();
// Create the format-preserving encryption (FPE) configuration
KmsWrappedCryptoKey kmsWrappedCryptoKey = KmsWrappedCryptoKey.newBuilder().setWrappedKey(ByteString.copyFrom(BaseEncoding.base64().decode(wrappedKey))).setCryptoKeyName(keyName).build();
CryptoKey cryptoKey = CryptoKey.newBuilder().setKmsWrapped(kmsWrappedCryptoKey).build();
CryptoReplaceFfxFpeConfig cryptoReplaceFfxFpeConfig = CryptoReplaceFfxFpeConfig.newBuilder().setCryptoKey(cryptoKey).setCommonAlphabet(alphabet).setSurrogateInfoType(surrogateTypeObject).build();
// Create the deidentification transformation configuration
PrimitiveTransformation primitiveTransformation = PrimitiveTransformation.newBuilder().setCryptoReplaceFfxFpeConfig(cryptoReplaceFfxFpeConfig).build();
InfoTypeTransformation infoTypeTransformationObject = InfoTypeTransformation.newBuilder().setPrimitiveTransformation(primitiveTransformation).addInfoTypes(surrogateTypeObject).build();
InfoTypeTransformations infoTypeTransformationArray = InfoTypeTransformations.newBuilder().addTransformations(infoTypeTransformationObject).build();
// Create the inspection config
CustomInfoType customInfoType = CustomInfoType.newBuilder().setInfoType(surrogateTypeObject).setSurrogateType(SurrogateType.newBuilder().build()).build();
InspectConfig inspectConfig = InspectConfig.newBuilder().addCustomInfoTypes(customInfoType).build();
// Create the reidentification request object
DeidentifyConfig reidentifyConfig = DeidentifyConfig.newBuilder().setInfoTypeTransformations(infoTypeTransformationArray).build();
ReidentifyContentRequest request = ReidentifyContentRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setReidentifyConfig(reidentifyConfig).setInspectConfig(inspectConfig).setItem(contentItem).build();
// Execute the deidentification request
ReidentifyContentResponse response = dlpServiceClient.reidentifyContent(request);
// Print the reidentified input value
// e.g. "My SSN is 7261298621" --> "My SSN is 123456789"
String result = response.getItem().getValue();
System.out.println(result);
} catch (Exception e) {
System.out.println("Error in reidentifyWithFpe: " + e.getMessage());
}
}
use of com.google.privacy.dlp.v2.InspectConfig in project java-docs-samples by GoogleCloudPlatform.
the class Inspect method inspectGcsFile.
// [END dlp_inspect_file]
// [START dlp_inspect_gcs]
/**
* Inspect GCS file for Info types and wait on job completion using Google Cloud Pub/Sub
* notification
*
* @param bucketName The name of the bucket where the file resides.
* @param fileName The path to the file within the bucket to inspect (can include wildcards, eg.
* my-image.*)
* @param minLikelihood The minimum likelihood required before returning a match
* @param infoTypes The infoTypes of information to match
* @param maxFindings The maximum number of findings to report (0 = server maximum)
* @param topicId Google Cloud Pub/Sub topic Id to notify of job status
* @param subscriptionId Google Cloud Subscription to above topic to listen for job status updates
* @param projectId Google Cloud project ID
*/
private static void inspectGcsFile(String bucketName, String fileName, Likelihood minLikelihood, List<InfoType> infoTypes, int maxFindings, String topicId, String subscriptionId, String projectId) throws Exception {
// Instantiates a client
try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
CloudStorageOptions cloudStorageOptions = CloudStorageOptions.newBuilder().setFileSet(CloudStorageOptions.FileSet.newBuilder().setUrl("gs://" + bucketName + "/" + fileName)).build();
StorageConfig storageConfig = StorageConfig.newBuilder().setCloudStorageOptions(cloudStorageOptions).build();
FindingLimits findingLimits = FindingLimits.newBuilder().setMaxFindingsPerRequest(maxFindings).build();
InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes).setMinLikelihood(minLikelihood).setLimits(findingLimits).build();
String pubSubTopic = String.format("projects/%s/topics/%s", projectId, topicId);
Action.PublishToPubSub publishToPubSub = Action.PublishToPubSub.newBuilder().setTopic(pubSubTopic).build();
Action action = Action.newBuilder().setPubSub(publishToPubSub).build();
InspectJobConfig inspectJobConfig = InspectJobConfig.newBuilder().setStorageConfig(storageConfig).setInspectConfig(inspectConfig).addActions(action).build();
// Semi-synchronously submit an inspect job, and wait on results
CreateDlpJobRequest createDlpJobRequest = CreateDlpJobRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setInspectJob(inspectJobConfig).build();
DlpJob dlpJob = dlpServiceClient.createDlpJob(createDlpJobRequest);
System.out.println("Job created with ID:" + dlpJob.getName());
final SettableApiFuture<Boolean> done = SettableApiFuture.create();
// Set up a Pub/Sub subscriber to listen on the job completion status
Subscriber subscriber = Subscriber.newBuilder(ProjectSubscriptionName.of(projectId, subscriptionId), (pubsubMessage, ackReplyConsumer) -> {
if (pubsubMessage.getAttributesCount() > 0 && pubsubMessage.getAttributesMap().get("DlpJobName").equals(dlpJob.getName())) {
// notify job completion
done.set(true);
ackReplyConsumer.ack();
}
}).build();
subscriber.startAsync();
// For long jobs, consider using a truly asynchronous execution model such as Cloud Functions
try {
done.get(1, TimeUnit.MINUTES);
// Wait for the job to become available
Thread.sleep(500);
} catch (Exception e) {
System.out.println("Unable to verify job completion.");
}
DlpJob completedJob = dlpServiceClient.getDlpJob(GetDlpJobRequest.newBuilder().setName(dlpJob.getName()).build());
System.out.println("Job status: " + completedJob.getState());
InspectDataSourceDetails inspectDataSourceDetails = completedJob.getInspectDetails();
InspectDataSourceDetails.Result result = inspectDataSourceDetails.getResult();
if (result.getInfoTypeStatsCount() > 0) {
System.out.println("Findings: ");
for (InfoTypeStats infoTypeStat : result.getInfoTypeStatsList()) {
System.out.print("\tInfo type: " + infoTypeStat.getInfoType().getName());
System.out.println("\tCount: " + infoTypeStat.getCount());
}
} else {
System.out.println("No findings.");
}
}
}
use of com.google.privacy.dlp.v2.InspectConfig in project java-docs-samples by GoogleCloudPlatform.
the class Inspect method inspectFile.
// [END dlp_inspect_string]
// [START dlp_inspect_file]
/**
* Inspect a local file
*
* @param filePath The path to a local file to inspect. Can be a text, JPG, or PNG file.
* @param minLikelihood The minimum likelihood required before returning a match
* @param maxFindings The maximum number of findings to report (0 = server maximum)
* @param infoTypes The infoTypes of information to match
* @param includeQuote Whether to include the matching string
* @param projectId Google Cloud project ID
*/
private static void inspectFile(String filePath, Likelihood minLikelihood, int maxFindings, List<InfoType> infoTypes, boolean includeQuote, String projectId) {
// Instantiates a client
try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
// detect file mime type, default to application/octet-stream
String mimeType = URLConnection.guessContentTypeFromName(filePath);
if (mimeType == null) {
mimeType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filePath);
}
ByteContentItem.BytesType bytesType;
switch(mimeType) {
case "image/jpeg":
bytesType = ByteContentItem.BytesType.IMAGE_JPEG;
break;
case "image/bmp":
bytesType = ByteContentItem.BytesType.IMAGE_BMP;
break;
case "image/png":
bytesType = ByteContentItem.BytesType.IMAGE_PNG;
break;
case "image/svg":
bytesType = ByteContentItem.BytesType.IMAGE_SVG;
break;
default:
bytesType = ByteContentItem.BytesType.BYTES_TYPE_UNSPECIFIED;
break;
}
byte[] data = Files.readAllBytes(Paths.get(filePath));
ByteContentItem byteContentItem = ByteContentItem.newBuilder().setType(bytesType).setData(ByteString.copyFrom(data)).build();
ContentItem contentItem = ContentItem.newBuilder().setByteItem(byteContentItem).build();
FindingLimits findingLimits = FindingLimits.newBuilder().setMaxFindingsPerRequest(maxFindings).build();
InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes).setMinLikelihood(minLikelihood).setLimits(findingLimits).setIncludeQuote(includeQuote).build();
InspectContentRequest request = InspectContentRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setInspectConfig(inspectConfig).setItem(contentItem).build();
InspectContentResponse response = dlpServiceClient.inspectContent(request);
InspectResult result = response.getResult();
if (result.getFindingsCount() > 0) {
System.out.println("Findings: ");
for (Finding finding : result.getFindingsList()) {
if (includeQuote) {
System.out.print("\tQuote: " + finding.getQuote());
}
System.out.print("\tInfo type: " + finding.getInfoType().getName());
System.out.println("\tLikelihood: " + finding.getLikelihood());
}
} else {
System.out.println("No findings.");
}
} catch (Exception e) {
System.out.println("Error in inspectFile: " + e.getMessage());
}
}
Aggregations