com.google.privacy.dlp.v2.Likelihood Java Examples

The following examples show how to use com.google.privacy.dlp.v2.Likelihood. 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: DLPClient.java    From android-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Example showing how to inspect a string to identify names, phone number, and
 * credit card numbers.
 *
 * @param string text to analyze
 * @return a string describing what was identified in the string
 */
@NonNull
public String inspectString(@NonNull String string) {
    // set sources of information to identify
    List<InfoType> infoTypes = ImmutableList.of(
            InfoType.newBuilder().setName("PERSON_NAME").build(),
            InfoType.newBuilder().setName("CREDIT_CARD_NUMBER").build(),
            InfoType.newBuilder().setName("PHONE_NUMBER").build());

    // configuration for the request
    InspectConfig inspectConfig =
            InspectConfig.newBuilder()
                    .addAllInfoTypes(infoTypes)
                    .setMinLikelihood(Likelihood.LIKELIHOOD_UNSPECIFIED)
                    .setLimits(InspectConfig.FindingLimits.newBuilder()
                            .setMaxFindingsPerRequest(0)
                            .build())
                    .setIncludeQuote(true)
                    .build();

    // the content to be analyzed
    ContentItem contentItem = ContentItem.newBuilder()
            .setByteItem(ByteContentItem.newBuilder()
                    .setType(ByteContentItem.BytesType.TEXT_UTF8)
                    .setData(ByteString.copyFromUtf8(string))
                    .build())
            .build();

    // create a request
    InspectContentRequest request =
            InspectContentRequest.newBuilder()
                    .setParent(ProjectName.of(mProjectId).toString())
                    .setInspectConfig(inspectConfig)
                    .setItem(contentItem)
                    .build();

    // call the API
    InspectContentResponse response = mClient.inspectContent(request);

    // format response into a string
    StringBuilder sb = new StringBuilder("Findings:");
    if (response.getResult().getFindingsCount() > 0) {
        for (Finding finding : response.getResult().getFindingsList()) {
            sb.append("\n")
                    .append("  Quote: ").append(finding.getQuote())
                    .append("  Info type: ").append(finding.getInfoType().getName())
                    .append("  Likelihood: ").append(finding.getLikelihood());
        }
    } else {
        sb.append("No findings.");
    }
    return sb.toString();
}
 
Example #2
Source File: DLPClient.java    From android-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Example showing how to inspect an image to identify names, phone number, and
 * credit card numbers.
 *
 * @param inputImage image to analyze (PNG)
 * @return a redacted image
 */
@NonNull
public ByteString redactPhoto(@NonNull ByteString inputImage) {
    // set sources of information to identify
    List<InfoType> infoTypes = ImmutableList.of(
            InfoType.newBuilder().setName("PERSON_NAME").build(),
            InfoType.newBuilder().setName("CREDIT_CARD_NUMBER").build(),
            InfoType.newBuilder().setName("PHONE_NUMBER").build());

    // set sources of information that should be redacted (to match infoTypes)
    List<RedactImageRequest.ImageRedactionConfig> imageRedactionConfigs =
            infoTypes.stream().map(infoType ->
                    RedactImageRequest.ImageRedactionConfig.newBuilder()
                            .setInfoType(infoType)
                            .build())
                    .collect(Collectors.toList());

    // configuration for the request
    InspectConfig inspectConfig =
            InspectConfig.newBuilder()
                    .addAllInfoTypes(infoTypes)
                    .setMinLikelihood(Likelihood.POSSIBLE)
                    .build();

    // content to be redacted
    ByteContentItem byteContentItem =
            ByteContentItem.newBuilder()
                    .setType(ByteContentItem.BytesType.IMAGE_PNG)
                    .setData(inputImage)
                    .build();

    // create a request
    RedactImageRequest redactImageRequest =
            RedactImageRequest.newBuilder()
                    .setParent(ProjectName.of(mProjectId).toString())
                    .addAllImageRedactionConfigs(imageRedactionConfigs)
                    .setByteItem(byteContentItem)
                    .setInspectConfig(inspectConfig)
                    .build();

    // call the API and return the redacted image
    RedactImageResponse redactImageResponse = mClient.redactImage(redactImageRequest);
    return redactImageResponse.getRedactedImage();
}
 
Example #3
Source File: InspectWithHotwordRules.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void inspectWithHotwordRules(
    String projectId, String textToInspect, String customRegexPattern, String hotwordRegexPattern)
    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 (DlpServiceClient dlp = DlpServiceClient.create()) {
    // Specify the type and content to be inspected.
    ByteContentItem byteItem =
        ByteContentItem.newBuilder()
            .setType(BytesType.TEXT_UTF8)
            .setData(ByteString.copyFromUtf8(textToInspect))
            .build();
    ContentItem item = ContentItem.newBuilder().setByteItem(byteItem).build();

    // Specify the regex pattern the inspection will look for.
    Regex regex = Regex.newBuilder().setPattern(customRegexPattern).build();

    // Construct the custom regex detector.
    InfoType infoType = InfoType.newBuilder().setName("C_MRN").build();
    CustomInfoType customInfoType =
        CustomInfoType.newBuilder().setInfoType(infoType).setRegex(regex).build();

    // Specify hotword likelihood adjustment.
    LikelihoodAdjustment likelihoodAdjustment =
        LikelihoodAdjustment.newBuilder().setFixedLikelihood(Likelihood.VERY_LIKELY).build();

    // Specify a window around a finding to apply a detection rule.
    Proximity proximity = Proximity.newBuilder().setWindowBefore(10).build();

    // Construct hotword rule.
    HotwordRule hotwordRule =
        HotwordRule.newBuilder()
            .setHotwordRegex(Regex.newBuilder().setPattern(hotwordRegexPattern).build())
            .setLikelihoodAdjustment(likelihoodAdjustment)
            .setProximity(proximity)
            .build();

    // Construct rule set for the inspect config.
    InspectionRuleSet inspectionRuleSet =
        InspectionRuleSet.newBuilder()
            .addInfoTypes(infoType)
            .addRules(InspectionRule.newBuilder().setHotwordRule(hotwordRule))
            .build();

    // Construct the configuration for the Inspect request.
    InspectConfig config =
        InspectConfig.newBuilder()
            .addCustomInfoTypes(customInfoType)
            .setIncludeQuote(true)
            .setMinLikelihood(Likelihood.POSSIBLE)
            .addRuleSet(inspectionRuleSet)
            .build();

    // Construct the Inspect request to be sent by the client.
    InspectContentRequest request =
        InspectContentRequest.newBuilder()
            .setParent(LocationName.of(projectId, "global").toString())
            .setItem(item)
            .setInspectConfig(config)
            .build();

    // Use the client to send the API request.
    InspectContentResponse response = dlp.inspectContent(request);

    // Parse the response and process results
    System.out.println("Findings: " + response.getResult().getFindingsCount());
    for (Finding f : response.getResult().getFindingsList()) {
      System.out.println("\tQuote: " + f.getQuote());
      System.out.println("\tInfo type: " + f.getInfoType().getName());
      System.out.println("\tLikelihood: " + f.getLikelihood());
    }
  }
}
 
Example #4
Source File: RedactImageFile.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
static void redactImageFile(String projectId, String inputPath, String outputPath)
    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 (DlpServiceClient dlp = DlpServiceClient.create()) {
    // Specify the content to be inspected.
    ByteString fileBytes = ByteString.readFrom(new FileInputStream(inputPath));
    ByteContentItem byteItem =
        ByteContentItem.newBuilder().setType(BytesType.IMAGE).setData(fileBytes).build();

    // Specify the type of info and likelihood necessary to redact.
    List<InfoType> infoTypes = new ArrayList<>();
    // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
    for (String typeName : new String[] {"PHONE_NUMBER", "EMAIL_ADDRESS", "CREDIT_CARD_NUMBER"}) {
      infoTypes.add(InfoType.newBuilder().setName(typeName).build());
    }
    InspectConfig config =
        InspectConfig.newBuilder()
            .addAllInfoTypes(infoTypes)
            .setMinLikelihood(Likelihood.LIKELY)
            .build();

    // Construct the Redact request to be sent by the client.
    RedactImageRequest request =
        RedactImageRequest.newBuilder()
            .setParent(LocationName.of(projectId, "global").toString())
            .setByteItem(byteItem)
            .setInspectConfig(config)
            .build();

    // Use the client to send the API request.
    RedactImageResponse response = dlp.redactImage(request);

    // Parse the response and process results.
    FileOutputStream redacted = new FileOutputStream(outputPath);
    redacted.write(response.getRedactedImage().toByteArray());
    redacted.close();
    System.out.println("Redacted image written to " + outputPath);

  }
}
 
Example #5
Source File: InspectGcsFileWithSampling.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void inspectGcsFileWithSampling(
    String projectId, String gcsUri, String topicId, String subscriptionId)
    throws ExecutionException, InterruptedException, 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 (DlpServiceClient dlp = DlpServiceClient.create()) {
    // Specify the GCS file to be inspected and sampling configuration
    CloudStorageOptions cloudStorageOptions =
        CloudStorageOptions.newBuilder()
            .setFileSet(FileSet.newBuilder().setUrl(gcsUri))
            .setBytesLimitPerFile(200)
            .addFileTypes(FileType.TEXT_FILE)
            .setFilesLimitPercent(90)
            .setSampleMethod(SampleMethod.RANDOM_START)
            .build();

    StorageConfig storageConfig =
        StorageConfig.newBuilder().setCloudStorageOptions(cloudStorageOptions).build();

    // Specify the type of info the inspection will look for.
    // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
    InfoType infoType = InfoType.newBuilder().setName("PERSON_NAME").build();

    // Specify how the content should be inspected.
    InspectConfig inspectConfig =
        InspectConfig.newBuilder()
            .addInfoTypes(infoType)
            .setExcludeInfoTypes(true)
            .setIncludeQuote(true)
            .setMinLikelihood(Likelihood.POSSIBLE)
            .build();

    // Specify the action that is triggered when the job completes.
    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();

    // Configure the long running job we want the service to perform.
    InspectJobConfig inspectJobConfig =
        InspectJobConfig.newBuilder()
            .setStorageConfig(storageConfig)
            .setInspectConfig(inspectConfig)
            .addActions(action)
            .build();

    // Create the request for the job configured above.
    CreateDlpJobRequest createDlpJobRequest =
        CreateDlpJobRequest.newBuilder()
            .setParent(LocationName.of(projectId, "global").toString())
            .setInspectJob(inspectJobConfig)
            .build();

    // Use the client to send the request.
    final DlpJob dlpJob = dlp.createDlpJob(createDlpJobRequest);
    System.out.println("Job created: " + dlpJob.getName());

    // Set up a Pub/Sub subscriber to listen on the job completion status
    final SettableApiFuture<Boolean> done = SettableApiFuture.create();

    ProjectSubscriptionName subscriptionName =
        ProjectSubscriptionName.of(projectId, subscriptionId);

    MessageReceiver messageHandler =
        (PubsubMessage pubsubMessage, AckReplyConsumer ackReplyConsumer) -> {
          handleMessage(dlpJob, done, pubsubMessage, ackReplyConsumer);
        };
    Subscriber subscriber = Subscriber.newBuilder(subscriptionName, messageHandler).build();
    subscriber.startAsync();

    // Wait for job completion semi-synchronously
    // For long jobs, consider using a truly asynchronous execution model such as Cloud Functions
    try {
      done.get(15, TimeUnit.MINUTES);
    } catch (TimeoutException e) {
      System.out.println("Job was not completed after 15 minutes.");
      return;
    } finally {
      subscriber.stopAsync();
      subscriber.awaitTerminated();
    }

    // Get the latest state of the job from the service
    GetDlpJobRequest request = GetDlpJobRequest.newBuilder().setName(dlpJob.getName()).build();
    DlpJob completedJob = dlp.getDlpJob(request);

    // Parse the response and process results.
    System.out.println("Job status: " + completedJob.getState());
    InspectDataSourceDetails.Result result = completedJob.getInspectDetails().getResult();
    System.out.println("Findings: ");
    for (InfoTypeStats infoTypeStat : result.getInfoTypeStatsList()) {
      System.out.print("\tInfo type: " + infoTypeStat.getInfoType().getName());
      System.out.println("\tCount: " + infoTypeStat.getCount());
    }
  }
}
 
Example #6
Source File: QuickStart.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void quickstart(String projectId) 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 (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
    // Configure that content that will be inspected
    String text = "His name was Robert Frost";
    ByteContentItem byteContentItem =
        ByteContentItem.newBuilder()
            .setType(ByteContentItem.BytesType.TEXT_UTF8)
            .setData(ByteString.copyFromUtf8(text))
            .build();
    ContentItem contentItem = ContentItem.newBuilder().setByteItem(byteContentItem).build();

    // The types of information to match:
    // See: https://cloud.google.com/dlp/docs/infotypes-reference
    List<InfoType> infoTypes =
        Stream.of("PERSON_NAME", "US_STATE")
            .map(it -> InfoType.newBuilder().setName(it).build())
            .collect(Collectors.toList());

    // The minimum likelihood required before returning a match:
    // See: https://cloud.google.com/dlp/docs/likelihood
    Likelihood minLikelihood = Likelihood.POSSIBLE;

    // The maximum number of findings to report (0 = server maximum)
    InspectConfig.FindingLimits findingLimits =
        InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(0).build();

    // Specify the inspection configuration
    InspectConfig inspectConfig =
        InspectConfig.newBuilder()
            .addAllInfoTypes(infoTypes)
            .setMinLikelihood(minLikelihood)
            .setLimits(findingLimits)
            .setIncludeQuote(true)
            .build();

    // Create the request from previous configs
    InspectContentRequest request =
        InspectContentRequest.newBuilder()
            .setParent(LocationName.of(projectId, "global").toString())
            .setInspectConfig(inspectConfig)
            .setItem(contentItem)
            .build();

    // Send the request to the service and receive the results
    InspectContentResponse response = dlpServiceClient.inspectContent(request);

    // Process the results
    System.out.println("Inspect of text complete: ");
    InspectResult result = response.getResult();
    if (result.getFindingsCount() < 0) {
      System.out.println("No findings.");
      return;
    }
    System.out.println("Findings: ");
    for (Finding finding : result.getFindingsList()) {
      System.out.println("\tQuote: " + finding.getQuote());
      System.out.println("\tInfo type: " + finding.getInfoType().getName());
      System.out.println("\tLikelihood: " + finding.getLikelihood());
    }
  }
}
 
Example #7
Source File: InspectWithCustomRegex.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void inspectWithCustomRegex(
    String projectId, String textToInspect, String customRegexPattern) 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 (DlpServiceClient dlp = DlpServiceClient.create()) {
    // Specify the type and content to be inspected.
    ByteContentItem byteItem =
        ByteContentItem.newBuilder()
            .setType(BytesType.TEXT_UTF8)
            .setData(ByteString.copyFromUtf8(textToInspect))
            .build();
    ContentItem item = ContentItem.newBuilder().setByteItem(byteItem).build();

    // Specify the regex pattern the inspection will look for.
    Regex regex = Regex.newBuilder().setPattern(customRegexPattern).build();

    // Construct the custom regex detector.
    InfoType infoType = InfoType.newBuilder().setName("C_MRN").build();
    CustomInfoType customInfoType =
        CustomInfoType.newBuilder()
            .setInfoType(infoType)
            .setRegex(regex)
            .build();

    // Construct the configuration for the Inspect request.
    InspectConfig config =
        InspectConfig.newBuilder()
            .addCustomInfoTypes(customInfoType)
            .setIncludeQuote(true)
            .setMinLikelihood(Likelihood.POSSIBLE)
            .build();

    // Construct the Inspect request to be sent by the client.
    InspectContentRequest request =
        InspectContentRequest.newBuilder()
            .setParent(LocationName.of(projectId, "global").toString()).setItem(item)
            .setInspectConfig(config)
            .build();

    // Use the client to send the API request.
    InspectContentResponse response = dlp.inspectContent(request);

    // Parse the response and process results
    System.out.println("Findings: " + response.getResult().getFindingsCount());
    for (Finding f : response.getResult().getFindingsList()) {
      System.out.println("\tQuote: " + f.getQuote());
      System.out.println("\tInfo type: " + f.getInfoType().getName());
      System.out.println("\tLikelihood: " + f.getLikelihood());
    }
  }
}
 
Example #8
Source File: JobsCreate.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void createJobs(String projectId, String gcsPath) 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 (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

    // Set autoPopulateTimespan to true to scan only new content
    boolean autoPopulateTimespan = true;
    TimespanConfig timespanConfig =
        TimespanConfig.newBuilder()
            .setEnableAutoPopulationOfTimespanConfig(autoPopulateTimespan)
            .build();

    // Specify the GCS file to be inspected.
    CloudStorageOptions cloudStorageOptions =
        CloudStorageOptions.newBuilder()
            .setFileSet(CloudStorageOptions.FileSet.newBuilder().setUrl(gcsPath))
            .build();
    StorageConfig storageConfig =
        StorageConfig.newBuilder()
            .setCloudStorageOptions(cloudStorageOptions)
            .setTimespanConfig(timespanConfig)
            .build();

    // Specify the type of info the inspection will look for.
    // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
    List<InfoType> infoTypes =
        Stream.of("EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER")
            .map(it -> InfoType.newBuilder().setName(it).build())
            .collect(Collectors.toList());
    // The minimum likelihood required before returning a match:
    // See: https://cloud.google.com/dlp/docs/likelihood
    Likelihood minLikelihood = Likelihood.UNLIKELY;

    // The maximum number of findings to report (0 = server maximum)
    InspectConfig.FindingLimits findingLimits =
        InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(100).build();

    InspectConfig inspectConfig =
        InspectConfig.newBuilder()
            .addAllInfoTypes(infoTypes)
            .setIncludeQuote(true)
            .setMinLikelihood(minLikelihood)
            .setLimits(findingLimits)
            .build();

    // Specify the action that is triggered when the job completes.
    Action.PublishSummaryToCscc publishSummaryToCscc =
        Action.PublishSummaryToCscc.getDefaultInstance();
    Action action = Action.newBuilder().setPublishSummaryToCscc(publishSummaryToCscc).build();

    // Configure the inspection job we want the service to perform.
    InspectJobConfig inspectJobConfig =
        InspectJobConfig.newBuilder()
            .setInspectConfig(inspectConfig)
            .setStorageConfig(storageConfig)
            .addActions(action)
            .build();

    // Construct the job creation request to be sent by the client.
    CreateDlpJobRequest createDlpJobRequest =
        CreateDlpJobRequest.newBuilder()
            .setParent(LocationName.of(projectId, "global").toString())
            .setInspectJob(inspectJobConfig)
            .build();

    // Send the job creation request and process the response.
    DlpJob createdDlpJob = dlpServiceClient.createDlpJob(createDlpJobRequest);
    System.out.println("Job created successfully: " + createdDlpJob.getName());
  }
}
 
Example #9
Source File: InspectStringCustomHotword.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void inspectStringCustomHotword(String projectId, String textToInspect,
    String customHotword) 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 (DlpServiceClient dlp = DlpServiceClient.create()) {
    // Specify the type and content to be inspected.
    ByteContentItem byteItem =
        ByteContentItem.newBuilder()
            .setType(BytesType.TEXT_UTF8)
            .setData(ByteString.copyFromUtf8(textToInspect))
            .build();
    ContentItem item = ContentItem.newBuilder().setByteItem(byteItem).build();

    // Increase likelihood of matches that have customHotword nearby
    HotwordRule hotwordRule =
        HotwordRule.newBuilder()
            .setHotwordRegex(Regex.newBuilder().setPattern(customHotword))
            .setProximity(Proximity.newBuilder().setWindowBefore(50))
            .setLikelihoodAdjustment(
                LikelihoodAdjustment.newBuilder().setFixedLikelihood(Likelihood.VERY_LIKELY))
            .build();

    // Construct a ruleset that applies the hotword rule to the PERSON_NAME infotype.
    InspectionRuleSet ruleSet =
        InspectionRuleSet.newBuilder()
            .addInfoTypes(InfoType.newBuilder().setName("PERSON_NAME").build())
            .addRules(InspectionRule.newBuilder().setHotwordRule(hotwordRule))
            .build();

    // Construct the configuration for the Inspect request.
    InspectConfig config =
        InspectConfig.newBuilder()
            .addInfoTypes(InfoType.newBuilder().setName("PERSON_NAME").build())
            .setIncludeQuote(true)
            .addRuleSet(ruleSet)
            .setMinLikelihood(Likelihood.VERY_LIKELY)
            .build();

    // Construct the Inspect request to be sent by the client.
    InspectContentRequest request =
        InspectContentRequest.newBuilder()
            .setParent(LocationName.of(projectId, "global").toString())
            .setItem(item)
            .setInspectConfig(config)
            .build();

    // Use the client to send the API request.
    InspectContentResponse response = dlp.inspectContent(request);

    // Parse the response and process results
    System.out.println("Findings: " + response.getResult().getFindingsCount());
    for (Finding f : response.getResult().getFindingsList()) {
      System.out.println("\tQuote: " + f.getQuote());
      System.out.println("\tInfo type: " + f.getInfoType().getName());
      System.out.println("\tLikelihood: " + f.getLikelihood());
    }
  }
}
 
Example #10
Source File: InspectPhoneNumber.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void inspectString(String projectId, String textToInspect) 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 (DlpServiceClient dlp = DlpServiceClient.create()) {
    // Specify the type and content to be inspected.
    ContentItem item = ContentItem.newBuilder()
        .setValue(textToInspect)
        .build();

    // Specify the type of info the inspection will look for.
    // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
    InfoType infoType = InfoType.newBuilder().setName("PHONE_NUMBER").build();

    // Construct the configuration for the Inspect request.
    InspectConfig config =
        InspectConfig.newBuilder()
            .setIncludeQuote(true)
            .setMinLikelihood(Likelihood.POSSIBLE)
            .addInfoTypes(infoType)
            .build();

    // Construct the Inspect request to be sent by the client.
    InspectContentRequest request =
        InspectContentRequest.newBuilder()
            .setParent(LocationName.of(projectId, "global").toString())
            .setItem(item)
            .setInspectConfig(config)
            .build();

    // Use the client to send the API request.
    InspectContentResponse response = dlp.inspectContent(request);

    // Parse the response and process results
    System.out.println("Findings: " + response.getResult().getFindingsCount());
    for (Finding f : response.getResult().getFindingsList()) {
      System.out.println("\tQuote: " + f.getQuote());
      System.out.println("\tInfo type: " + f.getInfoType().getName());
      System.out.println("\tLikelihood: " + f.getLikelihood());
    }
  }
}
 
Example #11
Source File: InspectStringMultipleRules.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void inspectStringMultipleRules(String projectId, String textToInspect)
    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 (DlpServiceClient dlp = DlpServiceClient.create()) {
    // Specify the type and content to be inspected.
    ByteContentItem byteItem =
        ByteContentItem.newBuilder()
            .setType(BytesType.TEXT_UTF8)
            .setData(ByteString.copyFromUtf8(textToInspect))
            .build();
    ContentItem item = ContentItem.newBuilder().setByteItem(byteItem).build();

    // Construct hotword rules
    HotwordRule patientRule =
        HotwordRule.newBuilder()
            .setHotwordRegex(Regex.newBuilder().setPattern("patient"))
            .setProximity(Proximity.newBuilder().setWindowBefore(10))
            .setLikelihoodAdjustment(
                LikelihoodAdjustment.newBuilder().setFixedLikelihood(Likelihood.VERY_LIKELY))
            .build();

    HotwordRule doctorRule =
        HotwordRule.newBuilder()
            .setHotwordRegex(Regex.newBuilder().setPattern("doctor"))
            .setProximity(Proximity.newBuilder().setWindowBefore(10))
            .setLikelihoodAdjustment(
                LikelihoodAdjustment.newBuilder().setFixedLikelihood(Likelihood.UNLIKELY))
            .build();

    // Construct exclusion rules
    ExclusionRule quasimodoRule =
        ExclusionRule.newBuilder()
            .setDictionary(
                Dictionary.newBuilder().setWordList(WordList.newBuilder().addWords("Quasimodo")))
            .setMatchingType(MatchingType.MATCHING_TYPE_PARTIAL_MATCH)
            .build();

    ExclusionRule redactedRule =
        ExclusionRule.newBuilder()
            .setRegex(Regex.newBuilder().setPattern("REDACTED"))
            .setMatchingType(MatchingType.MATCHING_TYPE_PARTIAL_MATCH)
            .build();

    // Construct a ruleset that applies the rules to the PERSON_NAME infotype.
    InspectionRuleSet ruleSet =
        InspectionRuleSet.newBuilder()
            .addInfoTypes(InfoType.newBuilder().setName("PERSON_NAME"))
            .addRules(InspectionRule.newBuilder().setHotwordRule(patientRule))
            .addRules(InspectionRule.newBuilder().setHotwordRule(doctorRule))
            .addRules(InspectionRule.newBuilder().setExclusionRule(quasimodoRule))
            .addRules(InspectionRule.newBuilder().setExclusionRule(redactedRule))
            .build();

    // Construct the configuration for the Inspect request, including the ruleset.
    InspectConfig config =
        InspectConfig.newBuilder()
            .addInfoTypes(InfoType.newBuilder().setName("PERSON_NAME"))
            .setIncludeQuote(true)
            .addRuleSet(ruleSet)
            .build();

    // Construct the Inspect request to be sent by the client.
    InspectContentRequest request =
        InspectContentRequest.newBuilder()
            .setParent(LocationName.of(projectId, "global").toString())
            .setItem(item)
            .setInspectConfig(config)
            .build();

    // Use the client to send the API request.
    InspectContentResponse response = dlp.inspectContent(request);

    // Parse the response and process results
    System.out.println("Findings: " + response.getResult().getFindingsCount());
    for (Finding f : response.getResult().getFindingsList()) {
      System.out.println("\tQuote: " + f.getQuote());
      System.out.println("\tInfo type: " + f.getInfoType().getName());
      System.out.println("\tLikelihood: " + f.getLikelihood());
    }
  }
}