Search in sources :

Example 31 with Entity

use of com.google.cloud.datastore.Entity in project jetty.project by eclipse.

the class GCloudSessionDataStore method entityFromSession.

/**
     * Generate a gcloud datastore Entity from SessionData
     * @param session the session data
     * @param key the key
     * @return the entity
     * @throws Exception if there is a deserialization error
     */
protected Entity entityFromSession(SessionData session, Key key) throws Exception {
    if (session == null)
        return null;
    Entity entity = null;
    //serialize the attribute map
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(session.getAllAttributes());
    oos.flush();
    //turn a session into an entity         
    entity = Entity.newBuilder(key).set(_model.getId(), session.getId()).set(_model.getContextPath(), session.getContextPath()).set(_model.getVhost(), session.getVhost()).set(_model.getAccessed(), session.getAccessed()).set(_model.getLastAccessed(), session.getLastAccessed()).set(_model.getCreateTime(), session.getCreated()).set(_model.getCookieSetTime(), session.getCookieSet()).set(_model.getLastNode(), session.getLastNode()).set(_model.getExpiry(), session.getExpiry()).set(_model.getMaxInactive(), session.getMaxInactiveMs()).set(_model.getLastSaved(), session.getLastSaved()).set(_model.getAttributes(), BlobValue.newBuilder(Blob.copyFrom(baos.toByteArray())).setExcludeFromIndexes(true).build()).build();
    return entity;
}
Also used : Entity(com.google.cloud.datastore.Entity) ProjectionEntity(com.google.cloud.datastore.ProjectionEntity) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream)

Example 32 with Entity

use of com.google.cloud.datastore.Entity in project jetty.project by eclipse.

the class GCloudSessionDataStore method doStore.

/** 
     * @see org.eclipse.jetty.server.session.AbstractSessionDataStore#doStore(java.lang.String, org.eclipse.jetty.server.session.SessionData, long)
     */
@Override
public void doStore(String id, SessionData data, long lastSaveTime) throws Exception {
    if (LOG.isDebugEnabled())
        LOG.debug("Writing session {} to DataStore", data.getId());
    Entity entity = entityFromSession(data, makeKey(id, _context));
    //attempt the update with exponential back-off
    int backoff = getBackoffMs();
    int attempts;
    for (attempts = 0; attempts < getMaxRetries(); attempts++) {
        try {
            _datastore.put(entity);
            return;
        } catch (DatastoreException e) {
            if (e.isRetryable()) {
                if (LOG.isDebugEnabled())
                    LOG.debug("Datastore put retry {} waiting {}ms", attempts, backoff);
                try {
                    Thread.currentThread().sleep(backoff);
                } catch (InterruptedException x) {
                }
                backoff *= 2;
            } else {
                throw e;
            }
        }
    }
    //retries have been exceeded
    throw new UnwriteableSessionDataException(id, _context, null);
}
Also used : Entity(com.google.cloud.datastore.Entity) ProjectionEntity(com.google.cloud.datastore.ProjectionEntity) DatastoreException(com.google.cloud.datastore.DatastoreException) UnwriteableSessionDataException(org.eclipse.jetty.server.session.UnwriteableSessionDataException)

Example 33 with Entity

use of com.google.cloud.datastore.Entity in project jetty.project by eclipse.

the class GCloudSessionDataStore method queryExpiryByEntity.

/**
     * A less efficient query to find sessions whose expiry time has passed:
     * retrieves the whole Entity.
     * @return set of ExpiryInfo representing the id, lastNode and expiry time of 
     * sessions that are expired
     * @throws Exception if datastore experiences a problem
     */
protected Set<ExpiryInfo> queryExpiryByEntity() throws Exception {
    Set<ExpiryInfo> info = new HashSet<>();
    //get up to maxResult number of sessions that have expired
    Query<Entity> query = Query.newEntityQueryBuilder().setKind(_model.getKind()).setFilter(CompositeFilter.and(PropertyFilter.gt(_model.getExpiry(), 0), PropertyFilter.le(_model.getExpiry(), System.currentTimeMillis()))).setLimit(_maxResults).build();
    QueryResults<Entity> results;
    if (LOG.isDebugEnabled()) {
        long start = System.currentTimeMillis();
        results = _datastore.run(query);
        LOG.debug("Expiry query no index in {}ms", System.currentTimeMillis() - start);
    } else
        results = _datastore.run(query);
    while (results.hasNext()) {
        Entity entity = results.next();
        info.add(new ExpiryInfo(entity.getString(_model.getId()), entity.getString(_model.getLastNode()), entity.getLong(_model.getExpiry())));
    }
    return info;
}
Also used : Entity(com.google.cloud.datastore.Entity) ProjectionEntity(com.google.cloud.datastore.ProjectionEntity) HashSet(java.util.HashSet)

Example 34 with Entity

use of com.google.cloud.datastore.Entity in project jetty.project by eclipse.

the class GCloudSessionDataStore method exists.

/** 
     * @see org.eclipse.jetty.server.session.SessionDataStore#exists(java.lang.String)
     */
@Override
public boolean exists(String id) throws Exception {
    if (_indexesPresent) {
        Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder().setKind(_model.getKind()).setProjection(_model.getExpiry()).setFilter(PropertyFilter.eq(_model.getId(), id)).build();
        QueryResults<ProjectionEntity> presults;
        if (LOG.isDebugEnabled()) {
            long start = System.currentTimeMillis();
            presults = _datastore.run(query);
            LOG.debug("Exists query by index in {}ms", System.currentTimeMillis() - start);
        } else
            presults = _datastore.run(query);
        if (presults.hasNext()) {
            ProjectionEntity pe = presults.next();
            return !isExpired(pe.getLong(_model.getExpiry()));
        } else
            return false;
    } else {
        Query<Entity> query = Query.newEntityQueryBuilder().setKind(_model.getKind()).setFilter(PropertyFilter.eq(_model.getId(), id)).build();
        QueryResults<Entity> results;
        if (LOG.isDebugEnabled()) {
            long start = System.currentTimeMillis();
            results = _datastore.run(query);
            LOG.debug("Exists query no index in {}ms", System.currentTimeMillis() - start);
        } else
            results = _datastore.run(query);
        if (results.hasNext()) {
            Entity entity = results.next();
            return !isExpired(entity.getLong(_model.getExpiry()));
        } else
            return false;
    }
}
Also used : Entity(com.google.cloud.datastore.Entity) ProjectionEntity(com.google.cloud.datastore.ProjectionEntity) ProjectionEntity(com.google.cloud.datastore.ProjectionEntity)

Example 35 with Entity

use of com.google.cloud.datastore.Entity in project google-cloud-java by GoogleCloudPlatform.

the class AddEntitiesAndRunQuery method main.

public static void main(String... args) {
    // Create datastore service object.
    // By default, credentials are inferred from the runtime environment.
    Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
    // Add an entity to Datastore
    KeyFactory keyFactory = datastore.newKeyFactory().setKind("Person");
    Key key = keyFactory.newKey("john.doe@gmail.com");
    Entity entity = Entity.newBuilder(key).set("name", "John Doe").set("age", 51).set("favorite_food", "pizza").build();
    datastore.put(entity);
    // Get an entity from Datastore
    Entity johnEntity = datastore.get(key);
    // Add a couple more entities to make the query results more interesting
    Key janeKey = keyFactory.newKey("jane.doe@gmail.com");
    Entity janeEntity = Entity.newBuilder(janeKey).set("name", "Jane Doe").set("age", 44).set("favorite_food", "pizza").build();
    Key joeKey = keyFactory.newKey("joe.shmoe@gmail.com");
    Entity joeEntity = Entity.newBuilder(joeKey).set("name", "Joe Shmoe").set("age", 27).set("favorite_food", "sushi").build();
    datastore.put(janeEntity, joeEntity);
    // Run a query
    Query<Entity> query = Query.newEntityQueryBuilder().setKind("Person").setFilter(PropertyFilter.eq("favorite_food", "pizza")).build();
    QueryResults<Entity> results = datastore.run(query);
    while (results.hasNext()) {
        Entity currentEntity = results.next();
        System.out.println(currentEntity.getString("name") + ", you're invited to a pizza party!");
    }
}
Also used : Entity(com.google.cloud.datastore.Entity) Datastore(com.google.cloud.datastore.Datastore) KeyFactory(com.google.cloud.datastore.KeyFactory) Key(com.google.cloud.datastore.Key)

Aggregations

Entity (com.google.cloud.datastore.Entity)59 Key (com.google.cloud.datastore.Key)37 IncompleteKey (com.google.cloud.datastore.IncompleteKey)27 Test (org.junit.Test)25 FullEntity (com.google.cloud.datastore.FullEntity)24 Datastore (com.google.cloud.datastore.Datastore)16 ProjectionEntity (com.google.cloud.datastore.ProjectionEntity)15 Transaction (com.google.cloud.datastore.Transaction)15 KeyFactory (com.google.cloud.datastore.KeyFactory)12 DatastoreException (com.google.cloud.datastore.DatastoreException)11 Batch (com.google.cloud.datastore.Batch)2 GqlQuery (com.google.cloud.datastore.GqlQuery)2 NullValue (com.google.cloud.datastore.NullValue)2 HashSet (java.util.HashSet)2 BooleanValue (com.google.cloud.datastore.BooleanValue)1 LatLngValue (com.google.cloud.datastore.LatLngValue)1 ListValue (com.google.cloud.datastore.ListValue)1 StringValue (com.google.cloud.datastore.StringValue)1 TimestampValue (com.google.cloud.datastore.TimestampValue)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1