Mulai Menggunakan Cloud Storage

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

Membuat project

Buat dan konfigurasi project sebagai berikut:

  1. Buka halaman API yang Diaktifkan di Konsol API Google.

    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 yang ada, pastikan untuk memilih project tersebut yang ingin Anda aktifkan Google Cloud Storage, lalu pilih Lanjutkan.
    • Atau, jika Anda tidak memiliki project, pilih Create a new project, masukkan nama Project, lalu pilih Create.

      Catatan: Anda harus mengetahui bahwa beberapa ID resource (seperti ID proyek) dapat dipertahankan di luar masa proyek Anda. Karena alasan ini, hindari menyimpan informasi sensitif pada sumber daya pengenal.

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

    Perlu diperhatikan bahwa untuk sebagian besar project, komponen Google Cloud Storage sudah diaktifkan. Jika Anda berencana untuk mengakses Google Cloud Storage menggunakan JSON API, lalu Anda juga harus memastikan bahwa Google Cloud Storage JSON API sudah aktif.

  4. Aktifkan penagihan untuk project.

    Sebelum dapat menggunakan Google Cloud Storage, Anda harus mengaktifkan penagihan untuk proyek jika Anda belum melakukannya. Mengaktifkan penagihan belum tentu berarti Anda akan dikenakan biaya. Untuk mengetahui informasi selengkapnya, lihat Harga.

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

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

Menyiapkan akses ke Cloud Storage

  1. Masih di Konsol API Google dalam proyek yang diperlukan, klik menu galeri di pojok kiri atas, pilih API & Services, lalu klik Credentials. Pada Halaman kredensial, cari Kunci akun layanan.

    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 Create credentials, lalu pilih Service account key.
    2. Di menu drop-down Akun layanan, pilih Akun layanan baru.
    3. Masukkan Nama untuk akun layanan. ID akun layanan secara otomatis yang dihasilkan dari nama dan nama project.
    4. Catat alamat email ID akun layanan gserviceaccount.com. Kredensial tidak akan ditampilkan di halaman Credentials setelah Anda memilih Create.
    5. Di bagian Jenis kunci, pilih JSON.
    6. Klik Buat. File JSON dengan pasangan kunci publik/pribadi akun disimpan ke folder Download Anda. Kunci ini digunakan untuk mengotentikasi aplikasi Anda ke API dan menandatangani semua permintaan yang dikirimkan ke API. Simpan file JSON yang dihasilkan di tempat yang aman, di suatu tempat di mana aplikasi Anda akan bisa mengaksesnya.
  2. Hubungi Display & Tim Dukungan Video 360 untuk meminta pengaktifan file Pembacaan Entitas dan/atau Google Bid Manager API.

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

    • Grup Google Pembacaan Log
      Grup hanya-baca hanya memiliki izin untuk membaca file dan mencantumkan konten bucket penyimpanan.
    • Google Grup Pengelolaan Log
      Grup manajemen memiliki semua izin akses grup hanya-baca, tetapi juga dapat mengubah ACL file dalam bucket. Perhatikan bahwa bahkan grup pengelolaan pun tidak memiliki izin mengubah ACL bucket, juga tidak memiliki izin untuk membuat, mengubah, atau menghapus file.

    Setelah grup Google ditambahkan, Anda dapat menambahkan pengguna ke dan menghapus pengguna dari grup Google sesuai kebutuhan tanpa keterlibatan lebih lanjut dari kampanye Display & Tim dukungan Video 360; hanya para pengguna tersebut siapa saja yang berada dalam grup akan memiliki akses ke data Anda.

Mengakses data

Mengakses data menggunakan gsutil

Alat gsutil adalah aplikasi baris perintah yang memungkinkan Anda mengakses Google Cloud Storage data dengan mudah tanpa pemrograman apa pun pengalaman yang lancar bagi developer. Misalnya, Anda dapat menggunakan gsutil sebagai bagian dari skrip atau file batch daripada membuat aplikasi kustom.

Untuk memulai gsutil, baca dokumentasi gsutil. Anda tetap perlu melakukan autentikasi menggunakan OAuth 2 seperti sebelumnya, tetapi gsutil akan meminta Anda untuk kredensial ketika pertama kali Anda menggunakannya dan kemudian menyimpannya untuk digunakan di kemudian hari.

Mengakses data secara terprogram

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

Java

Contoh berikut menggunakan paket Google Library Klien API untuk Java, yang memungkinkan akses ke data yang disimpan di Google di Cloud Storage. Selain Library Klien Google API umum utama, Anda juga perlu mengunduh file perpustakaan untuk Cloud Storage API.

Anda harus terlebih dahulu menyiapkan kredensial yang akan digunakan saat berkomunikasi dengan API untuk mendapatkan otorisasi untuk mengakses data Anda. Hal ini dilakukan dengan membuat Credential objek 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. Hal ini akan memastikan bahwa semua permintaan selanjutnya 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 API Google Cloud Storage:

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

Setelah memiliki objek Storage baru, Anda siap untuk mulai membuat permintaan untuk 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 Anda untuk bucket dan bucketObjectName akan bervariasi bergantung pada bagian API mana yang Anda akses; lihat bagian yang sesuai tentang penamaan yang sesuai.

C#

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

Anda harus menyiapkan kredensial yang akan digunakan saat berkomunikasi dengan API terlebih dahulu untuk mendapatkan otorisasi dalam 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 kemudian 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 standar Kelas library klien .NET untuk menangani download HTTP dari Google Cloud Storage, tetapi Anda harus menangani secara manual ada pengalihan untuk memastikan bahwa selalu ada Authorization yang benar header yang ada 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 Anda untuk bucket dan bucketObjectName akan bervariasi bergantung pada bagian API yang Anda akses; lihat bagian yang sesuai tentang konvensi penamaan.

Lampiran: Sampel 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;
        }

    }
}