Standalone Java access CloudStorage

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 =

 "[email protected]";


 /** 欲列表的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 =

 "[email protected]";


 /** 欲列表的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);

 }

}


Comments