Update an Akamai CDN key

Update a Video Stitcher Akamai CDN key resource.

Code sample

C#

Before trying this sample, follow the C# setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API C# API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


using Google.Cloud.Video.Stitcher.V1;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public class UpdateCdnKeyAkamaiSample
{
    public async Task<CdnKey> UpdateCdnKeyAkamaiAsync(
        string projectId, string location, string cdnKeyId, string hostname,
        string akamaiTokenKey)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CdnKey cdnKey = new CdnKey
        {
            CdnKeyName = CdnKeyName.FromProjectLocationCdnKey(projectId, location, cdnKeyId),
            Hostname = hostname,
            AkamaiCdnKey = new AkamaiCdnKey
            {
                TokenKey = ByteString.CopyFromUtf8(akamaiTokenKey)
            }
        };

        UpdateCdnKeyRequest request = new UpdateCdnKeyRequest
        {
            CdnKey = cdnKey,
            UpdateMask = new FieldMask { Paths = { "hostname", "akamai_cdn_key" } }
        };

        // Make the request.
        Operation<CdnKey, OperationMetadata> response = await client.UpdateCdnKeyAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<CdnKey, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result.
        return completedResponse.Result;
    }
}

Go

Before trying this sample, follow the Go setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Go API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateCDNKeyAkamai updates an Akamai CDN key. A CDN key is used to retrieve
// protected media.
func updateCDNKeyAkamai(w io.Writer, projectID, keyID, akamaiTokenKey string) error {
	// projectID := "my-project-id"
	// keyID := "my-cdn-key"
	// akamaiTokenKey := "my-updated-token-key"
	location := "us-central1"
	hostname := "updated.cdn.example.com"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherstreampb.UpdateCdnKeyRequest{
		CdnKey: &stitcherstreampb.CdnKey{
			CdnKeyConfig: &stitcherstreampb.CdnKey_AkamaiCdnKey{
				AkamaiCdnKey: &stitcherstreampb.AkamaiCdnKey{
					TokenKey: []byte(akamaiTokenKey),
				},
			},
			Name:     fmt.Sprintf("projects/%s/locations/%s/cdnKeys/%s", projectID, location, keyID),
			Hostname: hostname,
		},
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{
				"hostname", "akamai_cdn_key",
			},
		},
	}

	// Updates the CDN key.
	op, err := client.UpdateCdnKey(ctx, req)
	if err != nil {
		return fmt.Errorf("client.UpdateCdnKey: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Updated CDN key: %+v", response)
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Java API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.cloud.video.stitcher.v1.AkamaiCdnKey;
import com.google.cloud.video.stitcher.v1.CdnKey;
import com.google.cloud.video.stitcher.v1.CdnKeyName;
import com.google.cloud.video.stitcher.v1.UpdateCdnKeyRequest;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.protobuf.ByteString;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateCdnKeyAkamai {

  private static final int TIMEOUT_IN_MINUTES = 2;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String cdnKeyId = "my-updated-cdn-key-id";
    String hostname = "updated.example.com";
    String akamaiTokenKey = "my-updated-token-key"; // will be converted to a byte string

    updateCdnKeyAkamai(projectId, location, cdnKeyId, hostname, akamaiTokenKey);
  }

  // updateCdnKeyAkamai updates the hostname and key fields for an existing CDN key.
  public static CdnKey updateCdnKeyAkamai(
      String projectId, String location, String cdnKeyId, String hostname, String akamaiTokenKey)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      CdnKey cdnKey =
          CdnKey.newBuilder()
              .setName(CdnKeyName.of(projectId, location, cdnKeyId).toString())
              .setHostname(hostname)
              .setAkamaiCdnKey(
                  AkamaiCdnKey.newBuilder()
                      .setTokenKey(ByteString.copyFromUtf8(akamaiTokenKey))
                      .build())
              .build();

      UpdateCdnKeyRequest updateCdnKeyRequest =
          UpdateCdnKeyRequest.newBuilder()
              .setCdnKey(cdnKey)
              // Update the hostname field and token key field. You must set the mask to the fields
              // you want to update.
              .setUpdateMask(
                  FieldMask.newBuilder().addPaths("hostname").addPaths("akamai_cdn_key").build())
              .build();

      CdnKey response =
          videoStitcherServiceClient
              .updateCdnKeyAsync(updateCdnKeyRequest)
              .get(TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
      System.out.println("Updated CDN key: " + response.getName());
      return response;
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Node.js API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const location = 'us-central1';
/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// cdnKeyId = 'my-cdn-key';
// akamaiTokenKey = 'my-token-key';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function updateCdnKeyAkamai() {
  // Construct request
  const request = {
    cdnKey: {
      name: stitcherClient.cdnKeyPath(projectId, location, cdnKeyId),
      hostname: hostname,
      akamaiCdnKey: {
        tokenKey: akamaiTokenKey,
      },
    },
    updateMask: {
      paths: ['hostname', 'akamai_cdn_key'],
    },
  };

  const [operation] = await stitcherClient.updateCdnKey(request);
  const [response] = await operation.promise();
  console.log(`Updated CDN key: ${response.name}`);
  console.log(`Updated hostname: ${response.hostname}`);
}

updateCdnKeyAkamai().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

Before trying this sample, follow the PHP setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API PHP API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Video\Stitcher\V1\AkamaiCdnKey;
use Google\Cloud\Video\Stitcher\V1\CdnKey;
use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\UpdateCdnKeyRequest;
use Google\Protobuf\FieldMask;

/**
 * Updates an Akamai CDN key.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the CDN key
 * @param string  $cdnKeyId           The ID of the CDN key to be created
 * @param string  $hostname           The hostname of the CDN key
 * @param string  $tokenKey           The base64-encoded string token key for
 *                                    the Akamai CDN edge configuration
 */
function update_cdn_key_akamai(
    string $callingProjectId,
    string $location,
    string $cdnKeyId,
    string $hostname,
    string $tokenKey
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $name = $stitcherClient->cdnKeyName($callingProjectId, $location, $cdnKeyId);
    $cdnKey = new CdnKey();
    $cdnKey->setName($name);
    $cdnKey->setHostname($hostname);
    $akamaiCdn = new AkamaiCdnKey();
    $akamaiCdn->setTokenKey($tokenKey);
    $cdnKey->setAkamaiCdnKey($akamaiCdn);

    $updateMask = new FieldMask([
        'paths' => ['hostname', 'akamai_cdn_key']
    ]);

    // Run CDN key creation request
    $request = (new UpdateCdnKeyRequest())
        ->setCdnKey($cdnKey)
        ->setUpdateMask($updateMask);
    $operationResponse = $stitcherClient->updateCdnKey($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('Updated CDN key: %s' . PHP_EOL, $result->getName());
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

Before trying this sample, follow the Python setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Python API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)
from google.protobuf import field_mask_pb2 as field_mask


def update_cdn_key_akamai(
    project_id: str,
    location: str,
    cdn_key_id: str,
    hostname: str,
    akamai_token_key: str,
) -> stitcher_v1.types.CdnKey:
    """Updates an Akamai CDN key.
    Args:
        project_id: The GCP project ID.
        location: The location of the CDN key.
        cdn_key_id: The user-defined CDN key ID.
        hostname: The hostname to which this CDN key applies.
        akamai_token_key: A base64-encoded string token key.

    Returns:
        The CDN key resource.
    """

    client = VideoStitcherServiceClient()

    name = f"projects/{project_id}/locations/{location}/cdnKeys/{cdn_key_id}"

    cdn_key = stitcher_v1.types.CdnKey(
        name=name,
        hostname=hostname,
        akamai_cdn_key=stitcher_v1.types.AkamaiCdnKey(
            token_key=akamai_token_key,
        ),
    )
    update_mask = field_mask.FieldMask(paths=["hostname", "akamai_cdn_key"])

    operation = client.update_cdn_key(cdn_key=cdn_key, update_mask=update_mask)
    response = operation.result()
    print(f"Updated CDN key: {response.name}")
    return response

Ruby

Before trying this sample, follow the Ruby setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Ruby API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

require "google/cloud/video/stitcher"

##
# Update an Akamai CDN key
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param cdn_key_id [String] The user-defined CDN key ID
# @param hostname [String] The hostname to which this CDN key applies
# @param akamai_token_key [String] Applies to an Akamai CDN key. A
#   base64-encoded string token key.
#
def update_cdn_key_akamai project_id:, location:, cdn_key_id:, hostname:,
                          akamai_token_key:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the path for the CDN key resource.
  cdn_key_path = client.cdn_key_path project: project_id, location: location,
                                     cdn_key: cdn_key_id

  # Set the CDN key fields.
  update_mask = { paths: ["hostname", "akamai_cdn_key"] }
  new_cdn_key = {
    name: cdn_key_path,
    hostname: hostname,
    akamai_cdn_key: {
      token_key: akamai_token_key
    }
  }

  operation = client.update_cdn_key cdn_key: new_cdn_key,
                                    update_mask: update_mask

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print the CDN key name.
  puts "Updated CDN key: #{operation.response.name}"
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.