凭据Java应用程序连接到Google云数据存储区

时间:2016-04-22 04:06:04

标签: java gcloud google-cloud-datastore

我正在编写一个本地java应用程序来访问我的Google数据存储区。我在这里按照教程http://googlecloudplatform.github.io/gcloud-java/0.2.0/index.html

这是我的基本代码

package myproject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.google.cloud.AuthCredentials;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.KeyFactory;

public class Main {
    private String projID = "myID";
    public static void main(String[] args) throws IOException {

        System.out.println("correct");
        Main test = new Main();
        Datastore dstore = test.getDatastore();
        KeyFactory keyFactory = dstore.newKeyFactory().kind("keyKind");
        Key key = keyFactory.newKey("keyName");
        Entity entity = Entity.builder(key)
            .set("name", "John Doe")
            .set("age", 30)
            .build();
        dstore.put(entity);

    }

    private Datastore getDatastore() throws IOException {
        File file = new File("./resource/mycredential.json");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);

            System.out.println("Total file size to read (in bytes) : "
                    + fis.available());

        } catch (IOException e) {
            e.printStackTrace();
        }
        DatastoreOptions options = DatastoreOptions.builder()
                  .projectId(projID)
                  .authCredentials(AuthCredentials.createForJson(fis)).build();
        Datastore datastore = options.service();
        return datastore;
    }
} 

我从云控制台创建了json凭据密钥。运行程序后,它会显示com.google.datastore.v1beta3.client.DatastoreFactory makeClient ??:不使用任何凭证

我真的被困在这里。如何创建正确的凭据并正确使用它? 提前致谢。

1 个答案:

答案 0 :(得分:0)

这是" INFO"消息没有任何意义。我同意这令人困惑,但每次启动本地程序时都会显示此消息,该程序正常工作 - 连接到数据存储区,检索并保存数据等。