Mulai Menggunakan Cloud Storage

Google Display & Video 360 menyimpan File Pembacaan Entity secara otomatis di Google Cloud Storage. File-file ini hanya dapat diakses oleh akun yang telah diberi akses.

Membuat project

Buat dan konfigurasi project sebagai berikut:

  1. Buka halaman Google API Console Enabled APIs.

    Jika Anda belum login ke Google, Anda akan diminta untuk login.

  2. Dari drop-down project, pilih project yang sudah ada atau buat yang baru.
    • Jika Anda memiliki beberapa project, pastikan untuk memilih project yang Google Cloud Storage-nya ingin Anda aktifkan, lalu pilih Continue.
    • Atau, jika Anda tidak memiliki project, pilih Buat project baru, masukkan nama Project, lalu pilih Buat.

      Catatan: Perlu diketahui bahwa beberapa ID resource (seperti project ID) mungkin dipertahankan setelah project Anda aktif. Karena alasan ini, hindari menyimpan informasi sensitif di ID resource.

  3. Dalam daftar Enabled APIs, pastikan komponen Google Cloud Storage tercantum. Jika tidak tercantum, klik tab Google APIs, telusuri dan pilih komponen Google Cloud Storage, lalu klik Enable API.

    Perhatikan bahwa untuk sebagian besar project, komponen Google Cloud Storage sudah diaktifkan. Jika ingin mengakses Google Cloud Storage menggunakan JSON API, Anda juga harus memverifikasi bahwa Google Cloud Storage JSON API diaktifkan.

  4. Aktifkan penagihan untuk project.

    Sebelum dapat menggunakan Google Cloud Storage, Anda harus mengaktifkan penagihan untuk project jika belum melakukannya. Mengaktifkan penagihan tidak selalu berarti Anda akan dikenai biaya. Untuk mengetahui informasi selengkapnya, lihat Harga.

    1. Masih dalam proyek penyimpanan cloud, klik menu galeri di sudut kiri atas, lalu pilih Penagihan.
    2. Jika Anda belum memiliki akun penagihan, ikuti petunjuk untuk membuat akun penagihan baru.
    3. Jika Anda memiliki akun penagihan yang sudah ada, pilih akun tersebut, lalu pilih Set account.

Di Konsol API Google, tetap berada dalam project yang sama dan buka bagian berikutnya.

Menyiapkan akses ke Cloud Storage

  1. Masih di Konsol API Google dalam project yang diperlukan, klik menu galeri di pojok kiri atas, pilih APIs & Services, lalu klik Credentials. Pada halaman Credentials, cari Service account keys.

    Temukan alamat email kunci akun Layanan:

    1. Pilih link Kelola Akun Layanan (di sebelah kanan bagian Kunci akun layanan).
    2. Alamat email dapat dilihat di halaman Izin yang dihasilkan.

    Jika tidak ada Kunci akun layanan, buat Akun layanan baru:

    1. Pilih drop-down Buat kredensial, lalu pilih Kunci akun layanan.
    2. Di drop-down Akun layanan, pilih Akun layanan baru.
    3. Masukkan Nama untuk akun layanan. ID akun layanan otomatis dibuat dari nama dan nama project.
    4. Catat ID akun layanan gserviceaccount.com alamat email. Otorisasi ini tidak ditampilkan di halaman Credentials setelah Anda memilih Create.
    5. Di bagian Key type, pilih JSON.
    6. Klik Create. File JSON dengan pasangan kunci publik/pribadi akun disimpan ke folder Download Anda. Kunci ini digunakan untuk mengautentikasi aplikasi Anda ke API dan menandatangani semua permintaan yang dikirimkannya ke API. Simpan file JSON yang dihasilkan di tempat yang aman, di suatu tempat yang dapat diakses oleh aplikasi Anda.
  2. Hubungi Tim Dukungan Display & Video 360 untuk meminta pengaktifan file Pembacaan Entitas dan/atau Google Bid Manager API.

    Setelah Tim Dukungan mengonfirmasi akses, buat Google Grup khusus (atau grup) dan perbarui kolom berikut di detail partner Display & Video 360 (perhatikan bahwa hanya pengguna dengan akses tingkat partner yang dapat melakukan pembaruan ini):

    • Grup Google Baca Log
      Grup hanya baca hanya memiliki izin untuk membaca file dan membuat daftar konten bucket penyimpanan.
    • Grup Google Pengelolaan Log
      Grup pengelolaan memiliki semua izin grup hanya baca, tetapi juga dapat mengubah ACL file dalam bucket. Perlu diperhatikan bahwa grup pengelolaan bahkan tidak memiliki izin untuk mengubah ACL bucket, dan juga tidak memiliki izin untuk membuat, mengubah, atau menghapus file.

    Setelah Google Grup ditambahkan, Anda dapat menambahkan pengguna ke dan menghapus pengguna dari Google Grup sesuai kebutuhan tanpa melibatkan tim dukungan Display & Video 360 lebih lanjut. Hanya pengguna yang ada dalam grup Anda yang akan memiliki akses ke data.

Mengakses data Anda

Mengakses data menggunakan gsutil

Alat gsutil adalah aplikasi command line yang memungkinkan Anda mengakses data Google Cloud Storage dengan mudah tanpa pengalaman pemrograman apa pun. Misalnya, Anda dapat menggunakan gsutil sebagai bagian dari file skrip atau batch, bukan membuat aplikasi kustom.

Untuk mulai menggunakan gsutil, baca dokumentasi gsutil. Anda masih harus melakukan autentikasi menggunakan OAuth 2 seperti sebelumnya, tetapi gsutil akan meminta kredensial tersebut saat pertama kali Anda menggunakannya, lalu menyimpannya untuk digunakan di lain waktu.

Mengakses data secara terprogram

Google Cloud Storage memiliki API untuk banyak bahasa pemrograman yang memungkinkan Anda mengakses data dengan cara terprogram. Contoh di bawah menunjukkan cara melakukan download sederhana untuk salah satu File Pembacaan Entity dari Google Cloud Storage. Ingat bahwa hanya Entity Read Files publik yang disimpan di bucket gdbm-public; Entity Read Files pribadi Anda akan disimpan dalam bucket khusus Partner dan Pengiklan.

Java

Contoh berikut menggunakan Library Klien Google API untuk Java, yang memudahkan akses ke data yang disimpan di Google Cloud Storage. Selain Library Klien Google API umum yang utama, Anda juga harus mendownload library terpisah untuk Cloud Storage API.

Anda harus menyiapkan kredensial yang akan digunakan saat berkomunikasi dengan API terlebih dahulu guna mendapatkan otorisasi untuk mengakses data Anda. Hal ini dilakukan dengan membuat objek Credential yang menggunakan alamat email developer.gserviceaccount.com Akun Layanan sebagai ServiceAccountId dan juga memuat file kunci pribadi yang didownload dari Konsol API Google saat membuat Akun Layanan. Cara ini akan memastikan bahwa semua permintaan berikutnya ke API ditandatangani dengan kunci pribadi Akun Layanan:

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();

Setelah membuat objek Credential, Anda dapat menggunakannya untuk membuat instance objek Storage baru yang dapat Anda gunakan untuk semua permintaan mendatang ke Google Cloud Storage API:

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

Setelah memiliki objek Storage baru, Anda siap untuk mulai membuat permintaan ke API. Di sini Anda membuat permintaan untuk mengambil item tertentu bucketObjectName dari bucket bucket. Library ini menangani download HTTP file dari Google Cloud Storage, lalu Anda cukup mencetak kontennya ke konsol:

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

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

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

Nilai untuk bucket dan bucketObjectName akan bervariasi, bergantung pada bagian API yang Anda akses. Lihat bagian yang sesuai tentang konvensi penamaan.

C#

Contoh berikut menggunakan Library Klien Google API untuk .NET, yang mempermudah dan mempermudah akses ke data yang disimpan di Google Cloud Storage.

Anda harus menyiapkan kredensial yang akan digunakan saat berkomunikasi dengan API terlebih dahulu guna mendapatkan otorisasi untuk mengakses data Anda. Hal ini dilakukan dengan membuat objek AssertionFlowClient yang menggunakan alamat email developer.gserviceaccount.com Akun Layanan sebagai ServiceAccountId dan juga memuat file kunci pribadi yang didownload dari Konsol API Google saat membuat Akun Layanan.

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()
};

Setelah membuat objek AssertionFlowClient, Anda dapat menggunakannya untuk membuat instance objek OAuth2Authenticator baru yang dapat digunakan untuk membuat instance Storage baru untuk semua permintaan mendatang ke Google Cloud Storage API:

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

Setelah memiliki objek Storage baru, Anda siap untuk mulai membuat permintaan ke API. Di sini Anda membuat permintaan untuk mengambil item tertentu, bucketObjectName, dari bucket bucket. Kami menggunakan class library klien .NET standar untuk menangani download HTTP dari Google Cloud Storage, tetapi Anda harus menangani kasus secara manual apabila terdapat pengalihan untuk memastikan selalu ada header Authorization yang benar dalam permintaan:

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();
}

Konten respons kemudian dapat dibaca dari objek HttpWebResponse melalui GetResponseStream seperti biasa. Nilai untuk bucket dan bucketObjectName akan bervariasi bergantung pada bagian API yang Anda akses. Lihat bagian yang sesuai tentang konvensi penamaan.

Lampiran: Contoh Lengkap

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;
        }

    }
}