3

I'm trying to access Google Datastore from a standalone Java app (not a web application or servlet), using the low-level Java API, running on my local system.

remoteapi appears the simplest way do this. However, I need to specify a server per

RemoteApiOptions options = new RemoteApiOptions()
   .server("your_app_id.appspot.com", 443)    
   .useApplicationDefaultCredential();

How do I specify the server(...) invocation to access Datastore? I have run

gcloud auth login

and I have a project configured for Datastore (with a project ID, etc.) but no 'app_id' since there's no app involved.

Is there a standard server for accessing Datastore? Or is there a better way to access Datastore from a standalone java app?

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
zeke14
  • 99
  • 2

1 Answers1

9

To access Cloud Datastore outside of App Engine, follow the docs, which do not involve the Remote API. The complete example given on that page uses Maven (for the Java version), but, if that's not how you prefer to develop, you can look at the sources just as a usage example, and separately install the Google Cloud Client Library for Java; for running standalone (not in App Engine or Compute Engine), you'll explicitly authorize, as per the example on that page...:

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

DatastoreOptions options = DatastoreOptions.builder()
  .projectId(PROJECT_ID)
  .authCredentials(AuthCredentials.createForJson(
    new FileInputStream(PATH_TO_JSON_KEY))).build();
Datastore datastore = options.service();
KeyFactory keyFactory = datastore.newKeyFactory().kind(KIND);
Key key = keyFactory.newKey(keyName);
Entity entity = datastore.get(key);
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • Thanks. I saw that page but didn't wasn't sure where the relevant code was. Out of curiosity, what is a json key? I see [how to create one](https://developers.google.com/identity/protocols/application-default-credentials#whentouse) but I have no idea what it might be (googling didn't turn up much). – zeke14 Mar 09 '16 at 02:48
  • @zeke14, a json key is simply a secret bit of data for authentication, which is saved in json format for easy access from just about any language. – Alex Martelli Mar 09 '16 at 17:23