Cloud Storage を使ってみる

Google ディスプレイ&動画 360 はエンティティ読み込みファイルを自動的に保存 Google Cloud Storage に保存します。これらのファイルにアクセスできるのは、 付与されている場合もあります。

プロジェクトを作成する

次のようにプロジェクトを作成して構成します。

  1. Google API Console の [有効な API] ページに移動します。

    まだ Google にログインしていない場合は、ログインするよう求められます。

  2. プロジェクトのプルダウンから、既存のプロジェクトを選択するか、新しいプロジェクトを作成します。
    • 既存のプロジェクトが複数ある場合は、プロジェクトを選択します。 Cloud Storage を有効にするファイルを選択して [続行] をクリックします。
    • プロジェクトがない場合は、[新しいプロジェクトを作成] を選択し、プロジェクト名を入力して [作成] を選択します。

      注: 一部のリソース識別子は、 (プロジェクト ID など)は、プロジェクトの有効期間を過ぎた後も存続する場合があります。 そのため、リソースに機密情報を保存しないようにしてください。 あります。

  3. 有効な API のリストに、Google Cloud Storage コンポーネントが表示されていることを確認します。 表示されない場合は、[Google API] タブをクリックし、Google Cloud [API を有効にする] をクリックします。

    ほとんどのプロジェクトで、Google Cloud Storage コンポーネントはすでに有効になっていることに注意してください。計画 JSON API を使用して Google Cloud Storage にアクセスする Google Cloud Storage JSON API が有効になっていることも確認する必要があります。

  4. プロジェクトに対する課金を有効にします。

    Google Cloud Storage を使用する前に、 プロジェクトを作成します。課金を有効にしても、 料金が請求されます。詳細については、料金をご覧ください。

    1. 引き続き Cloud Storage プロジェクトの左上にあるギャラリー メニューをクリックして、[お支払い] を選択します。
    2. 請求先アカウントがまだない場合は、 新しい請求先アカウントを作成します。
    3. 既存の請求先アカウントがある場合 それを選択し、[アカウントを設定] を選択します。

Google API Console で、同じプロジェクト内で次のセクションに進みます。

Cloud Storage へのアクセスを設定する

  1. 引き続き Google API Console で、必要なプロジェクトの 左上の [API と[サービス] をクリックし、[認証情報] をクリックします。 [Credentials] ページで [Service account keys] を探します。

    サービス アカウント キーのメールアドレスを見つけます。

    1. [サービス アカウントの管理] リンク([サービス アカウント キー] セクションの右側)を選択します。
    2. メールアドレスは、表示される [権限] ページで確認できます。

    サービス アカウント キーがない場合は、新しいサービス アカウントを作成します。

    1. [認証情報を作成] プルダウンを選択し、[サービス アカウント キー] を選択します。
    2. [サービス アカウント] プルダウンで、[新しいサービス アカウント] を選択します。
    3. サービス アカウントの名前を入力します。[サービス アカウント ID] は自動的に 名前とプロジェクト名から生成されます。
    4. サービス アカウント ID gserviceaccount.com メールアドレスメモします。 [作成] を選択すると、[認証情報] ページには表示されません。
    5. [鍵のタイプ] セクションで、[JSON] を選択します。
    6. [作成] をクリックします。アカウントの公開鍵/秘密鍵のペアを含む JSON ファイルは、 ダウンロード フォルダに配置されます。このキーは、API に対するアプリケーションの認証と API に送信されるすべてのリクエストに署名する。生成された JSON ファイルを安全な場所に保存します。 アプリケーションからアクセスできるような場所に配置する必要があります。
  2. ディスプレイ&エンティティ読み取りファイルの有効化をリクエストする Video 360 サポートチーム または Google Bid Manager API を 使用します

    サポートチームがアクセスを確認したら、専用の Google グループを作成します (またはグループ)を作成し、ディスプレイ &ビデオ 360 の動画 360 パートナーの詳細( パートナー レベルのアクセス権を持つユーザーは、これらの更新を行うことができます):

    • ログ読み取り Google グループ
      読み取り専用グループには、ファイルを読み取り、ストレージ バケットの内容を一覧表示する権限のみがあります。
    • ログ管理 Google グループ
      管理グループは読み取り専用グループのすべての権限を持ちますが、 ACL を定義します。なお、管理グループにも権限がないため、 バケットの ACL を変更する権限や、ファイルを作成、変更、削除する権限は付与されません。

    Google グループを追加したら、必要に応じて Google グループへのユーザーの追加や削除を行うことができます。 ディスプレイ &ビデオ 360 の関与なしにビデオ 360 サポートチームそれらのユーザーのみに そのグループのメンバー全員がデータにアクセスできるようになります。

データへのアクセス

gsutil を使用してデータにアクセスする

gsutil ツールは、Google Cloud コンソールまたは プログラミングなしで簡単に Google Cloud Storage データ 体験できますたとえば、gsutil をスクリプトやバッチファイルの一部として使用し、 カスタム アプリケーションの作成に使用できます。

gsutil の使用を開始するには、gsutil のドキュメントをご覧ください。 以前と同様に OAuth 2 を使用して認証する必要がありますが、gsutil 自体から 認証情報を保存して、後で使用できるように保存する必要があります。

プログラムによるデータへのアクセス

Google Cloud Storage には、多くのプログラミング言語用の API があり、 プログラマティックな方法でデータにアクセスできます。以下のサンプルは、簡単な エンティティ読み取りファイルのいずれかのダウンロード Google Cloud Storage から。一般ユーザーのみが エンティティ読み込みファイルgdbm-public バケット、プライベートの エンティティ読み込みファイルは、パートナー / 広告主固有のバケットに保存されます。

Java

次の例では、Google Cloud Storage バケットを Java 用 API クライアント ライブラリを使用して、Google Cloud Storage へのデプロイも簡単です。主な一般的な Google API クライアント ライブラリに加え、 別途ダウンロードする必要があります ライブラリ (Cloud Storage API 用)をご覧ください。

まず、API と通信する際に使用する認証情報を設定して、 データへのアクセスを承認します。これを行うには、Credential を作成します。 サービス アカウントの developer.gserviceaccount.com メールアドレスを使用するオブジェクト ServiceAccountId として指定され、ダウンロードされた秘密鍵ファイルも読み込まれます。 サービス アカウントの作成時に Google API Console から使用できる。そうすれば API に対する今後のリクエストは、サービス アカウントの秘密鍵で署名されます。

NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JacksonFactory JSON_FACTORY = new JacksonFactory();

...

Credential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
   .setJsonFactory(JSON_FACTORY)
   .setServiceAccountId("...@developer.gserviceaccount.com")
   .setServiceAccountScopes(StorageScopes.DEVSTORAGE_READ_ONLY)
   .setServiceAccountPrivateKeyFromP12File(new File("...-privatekey.p12"))
   .build();

Credential オブジェクトを作成したら、そのオブジェクトを使用して、 に対する今後のすべてのリクエストに使用できる新しい Storage オブジェクトです。 Google Cloud Storage API:

Storage storage = new Storage(HTTP_TRANSPORT, JSON_FACTORY, credential);

これで新しい Storage オブジェクトが用意されたので、次にリクエストを行う準備が整いました。 できます。ここでは、特定のアイテム bucketObjectName を取得するリクエストを行っています。 バケット bucket から。このライブラリは、デバイスからのファイルの HTTP ダウンロードを Google Cloud Storage に保存し、そこからコンテンツを console:

Get bucketObject = storage.objects().get(bucketName, bucketObjectName);

ByteArrayOutputStream output = new ByteArrayOutputStream();
bucketObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
bucketObject.executeAndDownloadTo(output);

System.out.println(output.toString());

bucketbucketObjectName の値は、 API のどの部分にアクセスしているか名前について詳しくは、このモジュールの 学びました。

C#

次の例では .NET 用 Google API クライアント ライブラリ。これにより、Google Cloud Storage に保存されているデータに簡単かつ簡単にアクセスできます。

まず、API との通信で使用する認証情報を設定して、データへのアクセス承認を取得する必要があります。そのためには、サービス アカウントの developer.gserviceaccount.com メールアドレスを ServiceAccountId として使用する AssertionFlowClient オブジェクトを作成し、サービス アカウントの作成時に Google API Console からダウンロードした秘密鍵ファイルも読み込みます。

string keyPath = @"...-privatekey.p12";
X509Certificate2 certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
    ServiceAccountId = "...@developer.gserviceaccount.com",
    Scope = StorageService.Scopes.DevstorageRead_only.GetStringValue()
};

AssertionFlowClient オブジェクトを作成したら、そのオブジェクトを使用して新しい OAuth2Authenticator オブジェクトをインスタンス化し、これを使用して Google Cloud Storage API への今後のすべてのリクエスト用に新しい Storage インスタンスをインスタンス化できます。

var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
StorageService service = new StorageService(auth);

これで新しい Storage オブジェクトが用意されたので、リクエストを行う準備が整いました。 定義できます。ここでは、特定のアイテムを取得するリクエスト、 bucketObjectName(バケット bucket から)。標準の HTTP のダウンロードを処理する .NET クライアント ライブラリ クラス Google Cloud Storage を使用します。ただし、 常に正しい Authorization が表示されるようにするためのリダイレクトがあります。 ヘッダーがあります。

var results = service.Objects.Get(bucketName, bucketObjectName).Fetch();

HttpWebRequest request = createRequest(results.Media.Link, auth);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// Handle redirects manually to ensure that the Authorization header is present if
// your request is redirected.
if (response.StatusCode == HttpStatusCode.TemporaryRedirect)
{
    request = createRequest(response.Headers["Location"], auth);
    response = (HttpWebResponse)request.GetResponse();
}

これにより、レスポンスの内容は HttpWebResponse オブジェクトから読み取ることができます。 通常どおり GetResponseStream 経由で取得します。bucketbucketObjectName は、アクセスする API の部分によって異なります。命名規則に関する該当するセクションをご覧ください。

付録: サンプル全体

Java

/*
 * Copyright (c) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.bidmanager.api.samples;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.Storage.Objects.Get;
import com.google.api.services.storage.StorageScopes;

/**
 * A simple class that demonstrates how to download a specific object from a bucket using a
 * service account
 */
public class ServiceDownload {

  /**
   * This is the HTTP Transport object used for automatically refreshing access tokens.
   */
  static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  /**
   * This is the JSON factory used for parsing refresh token responses.Your first requirement
   */
  static final JacksonFactory JSON_FACTORY = new JacksonFactory();

  /**
   * The main method will attempt to download a specific named object from the gdbm-public bucket
   * using a service account.
   *
   * @param args Not used.
   */
  public static void main(String[] args) {

    try {
      // Prompt the user for the details of the object to download.
      System.out.print("Name of object to download, e.g. entity/20130430.0.Browser.json:");
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String bucketObjectName = in.readLine();
      in.close();
      String bucketName = "gdbm-public";

      Credential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
           .setJsonFactory(JSON_FACTORY)
           .setServiceAccountId("...@developer.gserviceaccount.com")
           .setServiceAccountScopes(StorageScopes.DEVSTORAGE_READ_ONLY)
           .setServiceAccountPrivateKeyFromP12File(
               new File("...-privatekey.p12"))
           .build();

      Storage storage = new Storage(HTTP_TRANSPORT, JSON_FACTORY, credential);

      Get bucketObject = storage.objects().get(bucketName, bucketObjectName);

      ByteArrayOutputStream output = new ByteArrayOutputStream();
      bucketObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
      bucketObject.executeAndDownloadTo(output);
      System.out.println(output.toString());

    } catch (Exception e) {
      System.err.println("Unexpected exception caught: " + e.getMessage());
      e.printStackTrace();
    }

  }


}

C#

/*
 * Copyright (c) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;

using DotNetOpenAuth.OAuth2;

using Google.Apis;
using Google.Apis.Requests;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Storage.v1beta1;
using Google.Apis.Storage.v1beta1.Data;
using Google.Apis.Util;

namespace ApiSamples
{
    /// <summary>
    /// A simple class that demonstrates how to download a specific object from a bucket using a
    /// service account
    /// </summary>
    class ServiceDownload
    {
        /// <summary>
        /// The main method will attempt to download a specific named object from the
        /// gdbm-public bucket using a service account.
        /// </summary>
        /// <param name="args">Not used.</param>
        public static void Main(string[] args)
        {

            // Prompt the user for the details of the object to download
            Console.WriteLine("Name of object to download, e.g. entity/20130430.0.Browser.json:");
            string bucketObjectName = Console.ReadLine();
            string bucketName = "gdbm-public";

            try
            {
                string keyPath = @"...-privatekey.p12";
                X509Certificate2 certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);
                var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
                {
                    ServiceAccountId = "...@developer.gserviceaccount.com",
                    Scope = StorageService.Scopes.DevstorageRead_only.GetStringValue()
                };
                var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);

                StorageService service = new StorageService(auth);
                var results = service.Objects.Get(bucketName, bucketObjectName).Fetch();

                HttpWebRequest request = createRequest(results.Media.Link, auth);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                // Handle redirects manully to ensure that the Authorization header is present if
                // our request is redirected.
                if (response.StatusCode == HttpStatusCode.TemporaryRedirect)
                {
                    request = createRequest(response.Headers["Location"], auth);
                    response = (HttpWebResponse)request.GetResponse();
                }

                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                String data = reader.ReadToEnd();
                Console.Write(data);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception caught: " + e.Message);
                Console.Write(e.StackTrace);
            }
            Console.ReadKey();
        }

        /// <summary>
        /// Generate a HttpWebRequest for the given URL with the appropriate OAuth2 authorization
        /// header applied.  The HttpWebRequest object returned has its AllowAutoRedirect option
        /// disabled to allow us to manually handle redirects.
        /// </summary>
        /// <param name="url">URL that is to be requested with this object</param>
        /// <param name="auth">The OAuth2Authenticator instance that contains the appropriate keys.</param>
        /// <returns>HttpWebRequest object ready to be used to make requests to the API</returns>
        private static HttpWebRequest createRequest(string url, OAuth2Authenticator<AssertionFlowClient> auth)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Bearer " + auth.State.AccessToken);
            request.AllowAutoRedirect = false;
            return request;
        }

    }
}