Skip to content

Instantly share code, notes, and snippets.

@dblevins
Created July 18, 2023 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dblevins/6f31afde55ce5b40820eba168a163eda to your computer and use it in GitHub Desktop.
Save dblevins/6f31afde55ce5b40820eba168a163eda to your computer and use it in GitHub Desktop.

Create Measurement Protocol Secrets in Java

Maven dependency

<dependency>
  <groupId>com.google.analytics</groupId>
  <artifactId>google-analytics-admin</artifactId>
  <version>0.30.0</version>
</dependency>

Construct the client

    /*
     * Create a service account and save the credentials json file
     * https://console.cloud.google.com/projectselector2/apis/enableflow?authuser=1
     */
    final File credentialsJsonFile = null; // TODO specify a credentials json file

    /*
     * Use ServiceAccountCredentials as the Credentials implementation
     */
    final Credentials credentials;
    try (final InputStream in = new FileInputStream(credentialsJsonFile)) {
        credentials = ServiceAccountCredentials.fromStream(in);
    }

    /*
     * Create the AnalyticsAdminServiceSettings
     */
    final AnalyticsAdminServiceSettings analyticsAdminServiceSettings = AnalyticsAdminServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
            .build();

    /*
     * Finally, create the AnalyticsAdminServiceClient
     */
    final AnalyticsAdminServiceClient client = AnalyticsAdminServiceClient.create(analyticsAdminServiceSettings);

Create the API Secret

final DataStreamName dataStreamName = DataStreamName.newBuilder()
        .setDataStream("123456")  // replace with your datastream id
        .setProperty("7654321")   // replace with your property id
        .build();

final MeasurementProtocolSecret secretName = MeasurementProtocolSecret.newBuilder()
        .setDisplayName("orange")  // replace with a name you want
        .build();

final MeasurementProtocolSecret secret = client.createMeasurementProtocolSecret(dataStreamName, secretName);

final String apiSecret = secret.getSecretValue();

System.out.println("Here is your new api_secret: "+ apiSecret);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment