Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify server to access datastore from Java app?

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.

" rel="nofollow noreferrer">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?

like image 693
zeke14 Avatar asked Jan 01 '26 03:01

zeke14


1 Answers

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);
like image 56
Alex Martelli Avatar answered Jan 05 '26 05:01

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!