SlideShare a Scribd company logo
GCS - Java to store data in Cloud Storage
 
目錄
目錄 
Step1: 申請Service Account,並將相關資訊儲存起來 
Step2: Java程式開發 
 
 
Step1: 申請Service Account,並將相關資訊儲存起來
 
 
選擇Service Account,點選Create Client ID之後,系統會直接下載一個xxx­private.p12的檔案,該
檔案的密碼為”notasecret”,該密碼在需要做轉換pem檔案時候可以用到。 
 
 
 
建立好的Service Account大致如下: 
 
 
其中Email address跟剛剛下載的*.p12檔案會在Java程式中用到 
 
Step2: Java程式開發
Java程式說明如下: 
 
前置參數設定: 
  /** Service Account 的 E­mail */ 
  private static final String SERVICE_ACCOUNT_EMAIL =  
  "86083545333...tkhf@developer.gserviceaccount.com"; 
 
  /** 欲列表的Bucket名稱,名稱即可,不用gs:// */ 
  private static final String BUCKET_NAME = "yout­bucket­name"; 
   
  /** p12檔案的位置,最好給訂絕對路徑 */ 
  private static final String keypath = "path­to­your­privatekey2.p12"; 
 
 
設定credential相關參數 
// 建制service account credential. 
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport) 
            .setJsonFactory(JSON_FACTORY) 
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) 
            .setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE)) 
            .setServiceAccountPrivateKeyFromP12File(new File(keypath)) 
            .build(); 
 
 
透過HTTP Request來操作Cloud Storage 
// 設定Request相關參數 
        String URI = "https://storage.googleapis.com/" + BUCKET_NAME; 
        HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential); 
        GenericUrl url = new GenericUrl(URI); 
        HttpRequest request = requestFactory.buildGetRequest(url); 
        HttpResponse response = request.execute(); 
        String content = response.parseAsString(); 
 
// 設定要傳輸的參數 
        Source xmlInput = new StreamSource(new StringReader(content)); 
        StreamResult xmlOutput = new StreamResult(new StringWriter()); 
        Transformer transformer = TransformerFactory.newInstance().newTransformer();  
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd"); 
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent­amount", "2"); 
        transformer.transform(xmlInput, xmlOutput); 
 
// 列印XML結果 
        System.out.println("nBucket listing for " + BUCKET_NAME + ":n"); 
        System.out.println(xmlOutput.getWriter().toString()); 
 
完整程式記錄如下: 
import java.io.File; 
import java.io.IOException; 
import java.io.StringReader; 
import java.io.StringWriter; 
import java.nio.charset.Charset; 
import java.util.Collections; 
 
import javax.xml.transform.OutputKeys; 
import javax.xml.transform.Source; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.stream.StreamResult; 
import javax.xml.transform.stream.StreamSource; 
 
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 
import com.google.api.client.http.GenericUrl; 
import com.google.api.client.http.HttpRequest; 
import com.google.api.client.http.HttpRequestFactory; 
import com.google.api.client.http.HttpResponse; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.json.jackson2.JacksonFactory; 
import com.google.api.client.util.Preconditions; 
import com.google.common.io.Files; 
 
public class StorageServiceAccountSample { 
 
  /** Service Account 的 E­mail */ 
  private static final String SERVICE_ACCOUNT_EMAIL =  
  "86083545333...tkhf@developer.gserviceaccount.com"; 
 
  /** 欲列表的Bucket名稱,名稱即可,不用gs:// */ 
  private static final String BUCKET_NAME = "yout­bucket­name"; 
  private static final String keypath = "path­to­your­privatekey2.p12"; 
 
  /** Google Cloud Storage OAuth 2.0 scope,這邊給予Read+Write權限 */ 
  private static final String STORAGE_SCOPE = 
      "https://www.googleapis.com/auth/devstorage.read_write"; 
 
  /** Global instance of the HTTP transport. */ 
  private static HttpTransport httpTransport; 
 
  /** Global instance of the JSON factory. */ 
  private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); 
 
  public static void main(String[] args) { 
    try { 
      try { 
        httpTransport = GoogleNetHttpTransport.newTrustedTransport(); 
   
        // 建制service account credential. 
        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY) 
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) 
            .setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE)) 
            .setServiceAccountPrivateKeyFromP12File(new File(keypath)) 
            .build(); 
 
        // Set up and execute Google Cloud Storage request. 
        String URI = "https://storage.googleapis.com/" + BUCKET_NAME; 
        HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential); 
        GenericUrl url = new GenericUrl(URI); 
        HttpRequest request = requestFactory.buildGetRequest(url); 
        HttpResponse response = request.execute(); 
        String content = response.parseAsString(); 
 
        // Instantiate transformer input 
        Source xmlInput = new StreamSource(new StringReader(content)); 
        StreamResult xmlOutput = new StreamResult(new StringWriter()); 
 
        // Configure transformer 
        Transformer transformer = TransformerFactory.newInstance().newTransformer(); // An 
identity transformer 
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd"); 
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent­amount", "2"); 
        transformer.transform(xmlInput, xmlOutput); 
 
        // Pretty print the output XML. 
        System.out.println("nBucket listing for " + BUCKET_NAME + ":n"); 
        System.out.println(xmlOutput.getWriter().toString()); 
        System.exit(0); 
 
      } catch (IOException e) { 
        System.err.println(e.getMessage()); 
      } 
    } catch (Throwable t) { 
      t.printStackTrace(); 
    } 
    System.exit(1); 
  } 
} 
 

More Related Content

PPTX
Microservice Protection With WSO2 Identity Server
PDF
Kerberos survival guide
PDF
MongoDB World 2019: MongoDB Implementation at T-Mobile
PPTX
Kerberos Survival Guide: SharePoint Saturday Nashville 2015
PPTX
SharePoint Saturday Kansas City - Kerberos Survival Guide
PPTX
Kerberos survival guide - SPS Ozarks 2010
PPTX
PDF
Bt0083 server side programing
Microservice Protection With WSO2 Identity Server
Kerberos survival guide
MongoDB World 2019: MongoDB Implementation at T-Mobile
Kerberos Survival Guide: SharePoint Saturday Nashville 2015
SharePoint Saturday Kansas City - Kerberos Survival Guide
Kerberos survival guide - SPS Ozarks 2010
Bt0083 server side programing

Viewers also liked (10)

PDF
JCConf2016 - Dataflow Workshop Setup
PDF
GAE - Using CloudStorage through FileReadChannel
PDF
GAE Java IDE installation
PDF
JCConf 2016 - Dataflow Workshop Labs
PDF
GCE Windows Serial Console Usage Guide
PDF
EmbulkのGCS/BigQuery周りのプラグインについて
PDF
Google Cloud Monitoring
PDF
Google Cloud Platform專案建立說明
PDF
Try Cloud Spanner
PPTX
均一Gae甘苦談
JCConf2016 - Dataflow Workshop Setup
GAE - Using CloudStorage through FileReadChannel
GAE Java IDE installation
JCConf 2016 - Dataflow Workshop Labs
GCE Windows Serial Console Usage Guide
EmbulkのGCS/BigQuery周りのプラグインについて
Google Cloud Monitoring
Google Cloud Platform專案建立說明
Try Cloud Spanner
均一Gae甘苦談
Ad

Similar to GCS - Java to store data in Cloud Storage (20)

DOC
( 16 ) Office 2007 Create An Extranet Site With Forms Authentication
PDF
Administrators manual
PDF
Administrators manual
PDF
Data load utility
PPTX
ASP.NET Lecture 5
PDF
[AD/CS] Windows Server 2016 - CA Enterprise - Parte02
DOCX
To integrate Active Directory with keyclock
PPTX
SharePoint Security in an Insecure World - AUSPC 2012
PDF
Apache Web Services
PDF
Open-VPN Server
PDF
User id installation and configuration
PDF
MATERIAL.pdf
PDF
Single Sign-On for APEX applications based on Kerberos (Important: latest ver...
PPTX
Azure AD B2C Webinar Series: Custom Policies Part 2 Policy Walkthrough
PPTX
Lamdba micro service using Amazon Api Gateway
PPTX
Security for SharePoint in an Insecure World - SharePoint Connections Amsterd...
PDF
Azure hands on lab
PPTX
SPTechCon SFO 2012 - Understanding the Five Layers of SharePoint Security
PPTX
MS Cloud Day - Deploying and monitoring windows azure applications
PDF
DCHQ Cloud Application Platform | Linux Containers | Docker PaaS
( 16 ) Office 2007 Create An Extranet Site With Forms Authentication
Administrators manual
Administrators manual
Data load utility
ASP.NET Lecture 5
[AD/CS] Windows Server 2016 - CA Enterprise - Parte02
To integrate Active Directory with keyclock
SharePoint Security in an Insecure World - AUSPC 2012
Apache Web Services
Open-VPN Server
User id installation and configuration
MATERIAL.pdf
Single Sign-On for APEX applications based on Kerberos (Important: latest ver...
Azure AD B2C Webinar Series: Custom Policies Part 2 Policy Walkthrough
Lamdba micro service using Amazon Api Gateway
Security for SharePoint in an Insecure World - SharePoint Connections Amsterd...
Azure hands on lab
SPTechCon SFO 2012 - Understanding the Five Layers of SharePoint Security
MS Cloud Day - Deploying and monitoring windows azure applications
DCHQ Cloud Application Platform | Linux Containers | Docker PaaS
Ad

More from Simon Su (20)

PDF
Kubernetes Basic Operation
PDF
Google IoT Core 初體驗
PDF
JSDC 2017 - 使用google cloud 從雲到端,動手刻個IoT
PDF
GCPUG.TW meetup #28 - GKE上運作您的k8s服務
PDF
Google Cloud Platform Special Training
PDF
GCPNext17' Extend 開始GCP了嗎?
PDF
Google Cloud Computing compares GCE, GAE and GKE
PDF
JCConf 2016 - Google Dataflow 小試
PDF
GCPUG meetup 201610 - Dataflow Introduction
PDF
Brocade - Stingray Application Firewall
PDF
使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析
PDF
Docker in Action
PDF
Google I/O 2016 Recap - Google Cloud Platform News Update
PDF
IThome DevOps Summit - IoT、docker與DevOps
PDF
Google Cloud Platform Introduction - 2016Q3
PDF
Google I/O Extended 2016 - 台北場活動回顧
PPTX
GCS - Access Control Lists (中文)
PDF
Google Cloud Platform - for Mobile Solutions
PDF
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(下)
PDF
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
Kubernetes Basic Operation
Google IoT Core 初體驗
JSDC 2017 - 使用google cloud 從雲到端,動手刻個IoT
GCPUG.TW meetup #28 - GKE上運作您的k8s服務
Google Cloud Platform Special Training
GCPNext17' Extend 開始GCP了嗎?
Google Cloud Computing compares GCE, GAE and GKE
JCConf 2016 - Google Dataflow 小試
GCPUG meetup 201610 - Dataflow Introduction
Brocade - Stingray Application Firewall
使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析
Docker in Action
Google I/O 2016 Recap - Google Cloud Platform News Update
IThome DevOps Summit - IoT、docker與DevOps
Google Cloud Platform Introduction - 2016Q3
Google I/O Extended 2016 - 台北場活動回顧
GCS - Access Control Lists (中文)
Google Cloud Platform - for Mobile Solutions
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(下)
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)

Recently uploaded (20)

PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
cuic standard and advanced reporting.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Machine learning based COVID-19 study performance prediction
PDF
Encapsulation theory and applications.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Electronic commerce courselecture one. Pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
“AI and Expert System Decision Support & Business Intelligence Systems”
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Spectroscopy.pptx food analysis technology
Review of recent advances in non-invasive hemoglobin estimation
Diabetes mellitus diagnosis method based random forest with bat algorithm
Understanding_Digital_Forensics_Presentation.pptx
Spectral efficient network and resource selection model in 5G networks
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation_ Review paper, used for researhc scholars
cuic standard and advanced reporting.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Programs and apps: productivity, graphics, security and other tools
Machine learning based COVID-19 study performance prediction
Encapsulation theory and applications.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Electronic commerce courselecture one. Pdf

GCS - Java to store data in Cloud Storage