Search in sources :

Example 6 with Value

use of com.google.datastore.v1.Value in project java-docs-samples by GoogleCloudPlatform.

the class RiskAnalysis method calculateLDiversity.

// [END dlp_k_anonymity]
// [START dlp_l_diversity]
/**
 * Calculate l-diversity for an attribute relative to quasi-identifiers in a BigQuery table.
 *
 * @param projectId The Google Cloud Platform project ID to run the API call under.
 * @param datasetId The BigQuery dataset to analyze.
 * @param tableId The BigQuery table to analyze.
 * @param sensitiveAttribute The name of the attribute to compare the quasi-ID against
 * @param quasiIds A set of column names that form a composite key ('quasi-identifiers').
 * @param topicId The name of the Pub/Sub topic to notify once the job completes
 * @param subscriptionId The name of the Pub/Sub subscription to use when listening for job
 *     completion status.
 */
private static void calculateLDiversity(String projectId, String datasetId, String tableId, String sensitiveAttribute, List<String> quasiIds, String topicId, String subscriptionId) throws Exception {
    // Instantiates a client
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
        FieldId sensitiveAttributeField = FieldId.newBuilder().setName(sensitiveAttribute).build();
        List<FieldId> quasiIdFields = quasiIds.stream().map(columnName -> FieldId.newBuilder().setName(columnName).build()).collect(Collectors.toList());
        LDiversityConfig ldiversityConfig = LDiversityConfig.newBuilder().addAllQuasiIds(quasiIdFields).setSensitiveAttribute(sensitiveAttributeField).build();
        BigQueryTable bigQueryTable = BigQueryTable.newBuilder().setProjectId(projectId).setDatasetId(datasetId).setTableId(tableId).build();
        PrivacyMetric privacyMetric = PrivacyMetric.newBuilder().setLDiversityConfig(ldiversityConfig).build();
        String topicName = String.format("projects/%s/topics/%s", projectId, topicId);
        PublishToPubSub publishToPubSub = PublishToPubSub.newBuilder().setTopic(topicName).build();
        // Create action to publish job status notifications over Google Cloud Pub/Sub
        Action action = Action.newBuilder().setPubSub(publishToPubSub).build();
        RiskAnalysisJobConfig riskAnalysisJobConfig = RiskAnalysisJobConfig.newBuilder().setSourceTable(bigQueryTable).setPrivacyMetric(privacyMetric).addActions(action).build();
        CreateDlpJobRequest createDlpJobRequest = CreateDlpJobRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setRiskJob(riskAnalysisJobConfig).build();
        DlpJob dlpJob = dlpServiceClient.createDlpJob(createDlpJobRequest);
        String dlpJobName = 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.newBuilder().setProject(projectId).setSubscription(subscriptionId).build(), (pubsubMessage, ackReplyConsumer) -> {
            if (pubsubMessage.getAttributesCount() > 0 && pubsubMessage.getAttributesMap().get("DlpJobName").equals(dlpJobName)) {
                // 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 (TimeoutException e) {
            System.out.println("Unable to verify job completion.");
        }
        // retrieve completed job status
        DlpJob completedJob = dlpServiceClient.getDlpJob(GetDlpJobRequest.newBuilder().setName(dlpJobName).build());
        System.out.println("Job status: " + completedJob.getState());
        AnalyzeDataSourceRiskDetails riskDetails = completedJob.getRiskDetails();
        LDiversityResult ldiversityResult = riskDetails.getLDiversityResult();
        for (LDiversityHistogramBucket result : ldiversityResult.getSensitiveValueFrequencyHistogramBucketsList()) {
            for (LDiversityEquivalenceClass bucket : result.getBucketValuesList()) {
                List<String> quasiIdValues = bucket.getQuasiIdsValuesList().stream().map(Value::toString).collect(Collectors.toList());
                System.out.println("\tQuasi-ID values: " + String.join(", ", quasiIdValues));
                System.out.println("\tClass size: " + bucket.getEquivalenceClassSize());
                for (ValueFrequency valueFrequency : bucket.getTopSensitiveValuesList()) {
                    System.out.printf("\t\tSensitive value %s occurs %d time(s).\n", valueFrequency.getValue().toString(), valueFrequency.getCount());
                }
            }
        }
    } catch (Exception e) {
        System.out.println("Error in calculateLDiversity: " + e.getMessage());
    }
}
Also used : Arrays(java.util.Arrays) TimeoutException(java.util.concurrent.TimeoutException) Subscriber(com.google.cloud.pubsub.v1.Subscriber) DefaultParser(org.apache.commons.cli.DefaultParser) KMapEstimationHistogramBucket(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.KMapEstimationResult.KMapEstimationHistogramBucket) LDiversityEquivalenceClass(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.LDiversityResult.LDiversityEquivalenceClass) ValueFrequency(com.google.privacy.dlp.v2.ValueFrequency) LDiversityConfig(com.google.privacy.dlp.v2.PrivacyMetric.LDiversityConfig) NumericalStatsConfig(com.google.privacy.dlp.v2.PrivacyMetric.NumericalStatsConfig) Action(com.google.privacy.dlp.v2.Action) KMapEstimationConfig(com.google.privacy.dlp.v2.PrivacyMetric.KMapEstimationConfig) CategoricalStatsHistogramBucket(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.CategoricalStatsResult.CategoricalStatsHistogramBucket) KAnonymityEquivalenceClass(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.KAnonymityResult.KAnonymityEquivalenceClass) Value(com.google.privacy.dlp.v2.Value) TaggedField(com.google.privacy.dlp.v2.PrivacyMetric.KMapEstimationConfig.TaggedField) RiskAnalysisJobConfig(com.google.privacy.dlp.v2.RiskAnalysisJobConfig) Collectors(java.util.stream.Collectors) SettableApiFuture(com.google.api.core.SettableApiFuture) List(java.util.List) KAnonymityResult(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.KAnonymityResult) ParseException(org.apache.commons.cli.ParseException) BigQueryTable(com.google.privacy.dlp.v2.BigQueryTable) ProjectSubscriptionName(com.google.pubsub.v1.ProjectSubscriptionName) AnalyzeDataSourceRiskDetails(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails) Options(org.apache.commons.cli.Options) HelpFormatter(org.apache.commons.cli.HelpFormatter) CategoricalStatsConfig(com.google.privacy.dlp.v2.PrivacyMetric.CategoricalStatsConfig) ArrayList(java.util.ArrayList) ServiceOptions(com.google.cloud.ServiceOptions) CommandLine(org.apache.commons.cli.CommandLine) FieldId(com.google.privacy.dlp.v2.FieldId) ProjectTopicName(com.google.pubsub.v1.ProjectTopicName) Option(org.apache.commons.cli.Option) DlpServiceClient(com.google.cloud.dlp.v2.DlpServiceClient) Iterator(java.util.Iterator) CreateDlpJobRequest(com.google.privacy.dlp.v2.CreateDlpJobRequest) CommandLineParser(org.apache.commons.cli.CommandLineParser) KMapEstimationResult(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.KMapEstimationResult) KMapEstimationQuasiIdValues(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.KMapEstimationResult.KMapEstimationQuasiIdValues) InfoType(com.google.privacy.dlp.v2.InfoType) LDiversityResult(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.LDiversityResult) KAnonymityConfig(com.google.privacy.dlp.v2.PrivacyMetric.KAnonymityConfig) TimeUnit(java.util.concurrent.TimeUnit) PublishToPubSub(com.google.privacy.dlp.v2.Action.PublishToPubSub) ProjectName(com.google.privacy.dlp.v2.ProjectName) GetDlpJobRequest(com.google.privacy.dlp.v2.GetDlpJobRequest) LDiversityHistogramBucket(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.LDiversityResult.LDiversityHistogramBucket) KAnonymityHistogramBucket(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.KAnonymityResult.KAnonymityHistogramBucket) PrivacyMetric(com.google.privacy.dlp.v2.PrivacyMetric) OptionGroup(org.apache.commons.cli.OptionGroup) DlpJob(com.google.privacy.dlp.v2.DlpJob) Collections(java.util.Collections) LDiversityHistogramBucket(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.LDiversityResult.LDiversityHistogramBucket) LDiversityConfig(com.google.privacy.dlp.v2.PrivacyMetric.LDiversityConfig) Action(com.google.privacy.dlp.v2.Action) RiskAnalysisJobConfig(com.google.privacy.dlp.v2.RiskAnalysisJobConfig) PrivacyMetric(com.google.privacy.dlp.v2.PrivacyMetric) CreateDlpJobRequest(com.google.privacy.dlp.v2.CreateDlpJobRequest) TimeoutException(java.util.concurrent.TimeoutException) ParseException(org.apache.commons.cli.ParseException) PublishToPubSub(com.google.privacy.dlp.v2.Action.PublishToPubSub) Subscriber(com.google.cloud.pubsub.v1.Subscriber) DlpServiceClient(com.google.cloud.dlp.v2.DlpServiceClient) BigQueryTable(com.google.privacy.dlp.v2.BigQueryTable) ValueFrequency(com.google.privacy.dlp.v2.ValueFrequency) FieldId(com.google.privacy.dlp.v2.FieldId) LDiversityResult(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.LDiversityResult) DlpJob(com.google.privacy.dlp.v2.DlpJob) AnalyzeDataSourceRiskDetails(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails) LDiversityEquivalenceClass(com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.LDiversityResult.LDiversityEquivalenceClass) TimeoutException(java.util.concurrent.TimeoutException)

Example 7 with Value

use of com.google.datastore.v1.Value in project structr by structr.

the class SessionTransaction method getStrings.

public QueryResult<String> getStrings(final String statement, final Map<String, Object> map) {
    final long t0 = System.currentTimeMillis();
    try {
        final StatementResult result = tx.run(statement, map);
        final Record record = result.next();
        final Value value = record.get(0);
        return new QueryResult<String>() {

            @Override
            public void close() {
                result.consume();
            }

            @Override
            public Iterator<String> iterator() {
                return value.asList(Values.ofString()).iterator();
            }
        };
    } catch (TransientException tex) {
        closed = true;
        throw new RetryException(tex);
    } catch (NoSuchRecordException nex) {
        throw new NotFoundException(nex);
    } catch (ServiceUnavailableException ex) {
        throw new NetworkException(ex.getMessage(), ex);
    } finally {
        logQuery(statement, map, t0);
    }
}
Also used : StatementResult(org.neo4j.driver.v1.StatementResult) QueryResult(org.structr.api.QueryResult) TransientException(org.neo4j.driver.v1.exceptions.TransientException) Value(org.neo4j.driver.v1.Value) NotFoundException(org.structr.api.NotFoundException) Record(org.neo4j.driver.v1.Record) ServiceUnavailableException(org.neo4j.driver.v1.exceptions.ServiceUnavailableException) RetryException(org.structr.api.RetryException) NetworkException(org.structr.api.NetworkException) NoSuchRecordException(org.neo4j.driver.v1.exceptions.NoSuchRecordException)

Example 8 with Value

use of com.google.datastore.v1.Value in project YCSB by brianfrankcooper.

the class GoogleDatastoreClient method read.

@Override
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
    LookupRequest.Builder lookupRequest = LookupRequest.newBuilder();
    lookupRequest.addKeys(buildPrimaryKey(table, key));
    lookupRequest.getReadOptionsBuilder().setReadConsistency(this.readConsistency);
    // Note above, datastore lookupRequest always reads the entire entity, it
    // does not support reading a subset of "fields" (properties) of an entity.
    logger.debug("Built lookup request as: " + lookupRequest.toString());
    LookupResponse response = null;
    try {
        response = datastore.lookup(lookupRequest.build());
    } catch (DatastoreException exception) {
        logger.error(String.format("Datastore Exception when reading (%s): %s %s", exception.getMessage(), exception.getMethodName(), exception.getCode()));
        // will bubble up to the user as part of the YCSB Status "name".
        return new Status("ERROR-" + exception.getCode(), exception.getMessage());
    }
    if (response.getFoundCount() == 0) {
        return new Status("ERROR-404", "Not Found, key is: " + key);
    } else if (response.getFoundCount() > 1) {
        // entity back. Unexpected State.
        return Status.UNEXPECTED_STATE;
    }
    Entity entity = response.getFound(0).getEntity();
    logger.debug("Read entity: " + entity.toString());
    Map<String, Value> properties = entity.getProperties();
    Set<String> propertiesToReturn = (fields == null ? properties.keySet() : fields);
    for (String name : propertiesToReturn) {
        if (properties.containsKey(name)) {
            result.put(name, new StringByteIterator(properties.get(name).getStringValue()));
        }
    }
    return Status.OK;
}
Also used : Status(site.ycsb.Status) StringByteIterator(site.ycsb.StringByteIterator) DatastoreException(com.google.datastore.v1.client.DatastoreException)

Example 9 with Value

use of com.google.datastore.v1.Value in project googleads-java-lib by googleads.

the class PqlTest method testCreateValue_numberSet.

@Test
public void testCreateValue_numberSet() {
    Set<Long> numberSet = new LinkedHashSet<Long>();
    numberSet.add(1L);
    Value value1 = ((SetValue) Pql.createValue(numberSet)).getValues(0);
    assertEquals("1", ((NumberValue) value1).getValue());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BooleanValue(com.google.api.ads.admanager.axis.v202202.BooleanValue) NumberValue(com.google.api.ads.admanager.axis.v202202.NumberValue) TargetingValue(com.google.api.ads.admanager.axis.v202202.TargetingValue) Value(com.google.api.ads.admanager.axis.v202202.Value) DateValue(com.google.api.ads.admanager.axis.v202202.DateValue) SetValue(com.google.api.ads.admanager.axis.v202202.SetValue) DateTimeValue(com.google.api.ads.admanager.axis.v202202.DateTimeValue) TextValue(com.google.api.ads.admanager.axis.v202202.TextValue) SetValue(com.google.api.ads.admanager.axis.v202202.SetValue) Test(org.junit.Test)

Example 10 with Value

use of com.google.datastore.v1.Value in project googleads-java-lib by googleads.

the class Pql method getApiValue.

/**
 * Gets the underlying value of the {@code Value} object that's comparable to what would be
 * returned in any other API object (i.e. DateTimeValue will return an API DateTime, not a Joda
 * DateTime).
 *
 * @param value the value to convert
 * @return the native value of {@code Value} or {@code null} if the underlying value is null
 * @throws IllegalArgumentException if value cannot be converted
 */
public static Object getApiValue(Value value) {
    if (value instanceof BooleanValue) {
        return ((BooleanValue) value).isValue();
    } else if (value instanceof NumberValue) {
        if (((NumberValue) value).getValue() == null) {
            return null;
        } else {
            try {
                return NumberFormat.getInstance().parse(((NumberValue) value).getValue());
            } catch (ParseException e) {
                throw new IllegalStateException("Received invalid number format from API: " + ((NumberValue) value).getValue());
            }
        }
    } else if (value instanceof TextValue) {
        return ((TextValue) value).getValue();
    } else if (value instanceof DateTimeValue) {
        return ((DateTimeValue) value).getValue();
    } else if (value instanceof DateValue) {
        return ((DateValue) value).getValue();
    } else if (value instanceof TargetingValue) {
        return ((TargetingValue) value).getValue();
    } else if (value instanceof SetValue) {
        List<Value> setValues = ((SetValue) value).getValues();
        Set<Object> apiValue = new LinkedHashSet<Object>();
        if (setValues != null) {
            for (Value setValue : setValues) {
                validateSetValueEntryForSet(getApiValue(setValue), apiValue);
                apiValue.add(getApiValue(setValue));
            }
        }
        return apiValue;
    } else {
        throw new IllegalArgumentException("Unsupported Value type [" + value.getClass() + "]");
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) DateTimeValue(com.google.api.ads.admanager.jaxws.v202105.DateTimeValue) NumberValue(com.google.api.ads.admanager.jaxws.v202105.NumberValue) TextValue(com.google.api.ads.admanager.jaxws.v202105.TextValue) DateValue(com.google.api.ads.admanager.jaxws.v202105.DateValue) BooleanValue(com.google.api.ads.admanager.jaxws.v202105.BooleanValue) NumberValue(com.google.api.ads.admanager.jaxws.v202105.NumberValue) BooleanValue(com.google.api.ads.admanager.jaxws.v202105.BooleanValue) Value(com.google.api.ads.admanager.jaxws.v202105.Value) SetValue(com.google.api.ads.admanager.jaxws.v202105.SetValue) DateTimeValue(com.google.api.ads.admanager.jaxws.v202105.DateTimeValue) TargetingValue(com.google.api.ads.admanager.jaxws.v202105.TargetingValue) DateValue(com.google.api.ads.admanager.jaxws.v202105.DateValue) TextValue(com.google.api.ads.admanager.jaxws.v202105.TextValue) ParseException(java.text.ParseException) TargetingValue(com.google.api.ads.admanager.jaxws.v202105.TargetingValue) SetValue(com.google.api.ads.admanager.jaxws.v202105.SetValue)

Aggregations

LinkedHashSet (java.util.LinkedHashSet)56 Test (org.junit.Test)43 BooleanValue (com.google.api.ads.admanager.axis.v202105.BooleanValue)7 DateTimeValue (com.google.api.ads.admanager.axis.v202105.DateTimeValue)7 DateValue (com.google.api.ads.admanager.axis.v202105.DateValue)7 NumberValue (com.google.api.ads.admanager.axis.v202105.NumberValue)7 SetValue (com.google.api.ads.admanager.axis.v202105.SetValue)7 TargetingValue (com.google.api.ads.admanager.axis.v202105.TargetingValue)7 BooleanValue (com.google.api.ads.admanager.jaxws.v202202.BooleanValue)6 DateTimeValue (com.google.api.ads.admanager.jaxws.v202202.DateTimeValue)6 DateValue (com.google.api.ads.admanager.jaxws.v202202.DateValue)6 NumberValue (com.google.api.ads.admanager.jaxws.v202202.NumberValue)6 SetValue (com.google.api.ads.admanager.jaxws.v202202.SetValue)6 TargetingValue (com.google.api.ads.admanager.jaxws.v202202.TargetingValue)6 TextValue (com.google.api.ads.admanager.jaxws.v202202.TextValue)6 Value (com.google.api.ads.admanager.jaxws.v202202.Value)6 BooleanValue (com.google.api.ads.admanager.axis.v202108.BooleanValue)5 DateTimeValue (com.google.api.ads.admanager.axis.v202108.DateTimeValue)5 DateValue (com.google.api.ads.admanager.axis.v202108.DateValue)5 NumberValue (com.google.api.ads.admanager.axis.v202108.NumberValue)5