private static Map<String, Object> getProperties(Entity entity) throws IOException, ClassNotFoundException { if (entity == null) { return null; } ImmutableMap.Builder<String, Object> builder = new ImmutableMap.Builder<>(); for (String property : entity.getNames()) { // builder.put(property, entity.getValue(property)); if (entity.getValue(property) instanceof StringValue) { builder.put(property, (String) entity.getString(property)); } else if (entity.getValue(property) instanceof LongValue) { // This conversion is safe because of integer to long conversion above builder.put(property, new Long(entity.getLong(property)).intValue()); } else if (entity.getValue(property) instanceof DoubleValue) { builder.put(property, (Double) entity.getDouble(property)); } else if (entity.getValue(property) instanceof BooleanValue) { builder.put(property, (Boolean) entity.getBoolean(property)); } else if (entity.getValue(property) instanceof TimestampValue) { builder.put(property, (Timestamp) entity.getTimestamp(property)); } else { Blob blob = entity.getBlob(property); Object obj = null; try (ObjectInputStream in = new ObjectInputStream(blob.asInputStream())) { obj = in.readObject(); } builder.put(property, obj); // BlobValue } } return builder.build(); }
"User '%s' email is '%s', phone is '%s'.%n", userKey.getName(), email, phone); System.out.printf("User '%s' has %d comment[s].%n", userKey.getName(), user.getLong("count")); int limit = 200; Map<Timestamp, String> sortedComments = new TreeMap<>();
@Override public void run(Transaction tx, Key userKey, String content) { Entity user = tx.get(userKey); if (user == null) { System.out.println("Adding a new user."); user = Entity.newBuilder(userKey).set("count", 1).build(); tx.add(user); } else { user = Entity.newBuilder(user).set("count", user.getLong("count") + 1L).build(); tx.update(user); } IncompleteKey commentKey = IncompleteKey.newBuilder(userKey, COMMENT_KIND).build(); FullEntity<IncompleteKey> comment = FullEntity.newBuilder(commentKey) .set("content", content) .set("timestamp", Timestamp.now()) .build(); tx.addWithDeferredIdAllocation(comment); System.out.printf("Adding a comment to user '%s'.%n", userKey.getName()); }
Map<Integer, Long> shardsForCounter(String counterId) throws IOException { final List<Key> shardKeys = IntStream.range(0, NUM_SHARDS).mapToObj( index -> datastore.newKeyFactory().setKind(KIND_COUNTER_SHARD).newKey( String.format("%s-%d", counterId, index))) .collect(toList()); final Map<Integer, Long> fetchedShards = new HashMap<>(); datastore.get(shardKeys, shard -> fetchedShards.put( (int) shard.getLong(PROPERTY_SHARD_INDEX), shard.getLong(PROPERTY_SHARD_VALUE))); return fetchedShards; }
long getLimitForCounter(String counterId) throws IOException { if (GLOBAL_RESOURCE_ID.equals(counterId)) { // missing global resource means free to go return config().globalConcurrency().orElse(Long.MAX_VALUE); } final Key limitKey = datastore.newKeyFactory().setKind(KIND_COUNTER_LIMIT).newKey(counterId); final Entity limitEntity = datastore.get(limitKey); if (limitEntity == null) { throw new IllegalArgumentException("No limit found in Datastore for " + counterId); } else { return limitEntity.getLong(PROPERTY_LIMIT); } }
private Resource entityToResource(Entity entity) { return Resource.create(entity.getKey().getName(), entity.getLong(PROPERTY_LIMIT)); }
@Override public Optional<Shard> shard(String counterId, int shardIndex) throws IOException { // TODO there's no need for this to be transactional final Key shardKey = tx.getDatastore().newKeyFactory().setKind(KIND_COUNTER_SHARD) .newKey(counterId + "-" + shardIndex); Entity shardEntity = tx.get(shardKey); if (shardEntity == null) { return Optional.empty(); } return Optional.of(Shard.create(counterId, shardIndex, (int) tx.get(shardKey).getLong(PROPERTY_SHARD_VALUE))); }
/** * Increments the version property of the given entity by one. * * @param nativeEntity * the target entity * @param versionMetadata * the metadata of the version property * @return a new entity (copy of the given), but with the incremented version. */ static Entity incrementVersion(Entity nativeEntity, PropertyMetadata versionMetadata) { String versionPropertyName = versionMetadata.getMappedName(); long version = nativeEntity.getLong(versionPropertyName); return Entity.newBuilder(nativeEntity).set(versionPropertyName, ++version).build(); }
long version = nativeEntities[i].getLong(versionPropertyName) - 1; Entity storedNativeEntity = storedNativeEntities.get(i); if (storedNativeEntity == null) { String.format("Entity does not exist: %s", nativeKeys[i])); long storedVersion = storedNativeEntities.get(i).getLong(versionPropertyName); if (version != storedVersion) { throw new OptimisticLockException(
@Override @SuppressWarnings("unchecked") protected <E> E updateWithOptimisticLockingInternal(E entity, PropertyMetadata versionMetadata) { try { entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity); Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, Intent.UPDATE); Entity storedNativeEntity = nativeTransaction.get(nativeEntity.getKey()); if (storedNativeEntity == null) { throw new OptimisticLockException( String.format("Entity does not exist: %s", nativeEntity.getKey())); } String versionPropertyName = versionMetadata.getMappedName(); long version = nativeEntity.getLong(versionPropertyName) - 1; long storedVersion = storedNativeEntity.getLong(versionPropertyName); if (version != storedVersion) { throw new OptimisticLockException( String.format("Expecting version %d, but found %d", version, storedVersion)); } nativeTransaction.update(nativeEntity); E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass()); entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity); return updatedEntity; } catch (DatastoreException exp) { throw DatastoreUtils.wrap(exp); } }
long version = nativeEntities[i].getLong(versionPropertyName) - 1; Entity storedNativeEntity = storedNativeEntities.get(i); if (storedNativeEntity == null) { String.format("Entity does not exist: %s", nativeKeys[i])); long storedVersion = storedNativeEntities.get(i).getLong(versionPropertyName); if (version != storedVersion) { throw new OptimisticLockException(
static RunState entityToRunState(Entity entity, WorkflowInstance instance) throws IOException { final long counter = entity.getLong(PROPERTY_COUNTER); final State state = State.valueOf(entity.getString(PROPERTY_STATE)); final long timestamp = entity.getLong(PROPERTY_STATE_TIMESTAMP); final StateData data = StateData.newBuilder() .tries((int) entity.getLong(PROPERTY_STATE_TRIES)) .consecutiveFailures((int) entity.getLong(PROPERTY_STATE_CONSECUTIVE_FAILURES)) .retryCost(entity.getDouble(PROPERTY_STATE_RETRY_COST)) .trigger(DatastoreStorage.<String>readOpt(entity, PROPERTY_STATE_TRIGGER_TYPE).map(type -> TriggerUtil.trigger(type, entity.getString(PROPERTY_STATE_TRIGGER_ID)))) .messages(OBJECT_MAPPER.<List<Message>>readValue(entity.getString(PROPERTY_STATE_MESSAGES), new TypeReference<List<Message>>() { })) .retryDelayMillis(readOpt(entity, PROPERTY_STATE_RETRY_DELAY_MILLIS)) .lastExit(DatastoreStorage.<Long>readOpt(entity, PROPERTY_STATE_LAST_EXIT).map(Long::intValue)) .executionId(readOpt(entity, PROPERTY_STATE_EXECUTION_ID)) .executionDescription(readOptJson(entity, PROPERTY_STATE_EXECUTION_DESCRIPTION, ExecutionDescription.class)) .resourceIds(readOptJson(entity, PROPERTY_STATE_RESOURCE_IDS, new TypeReference<Set<String>>() { })) .triggerParameters(readOptJson(entity, PROPERTY_STATE_TRIGGER_PARAMETERS, TriggerParameters.class)) .build(); return RunState.create(instance, state, data, Instant.ofEpochMilli(timestamp), counter); }
String contextPath = entity.getString(_model.getContextPath()); String vhost = entity.getString(_model.getVhost()); long accessed = entity.getLong(_model.getAccessed()); long lastAccessed = entity.getLong(_model.getLastAccessed()); long createTime = entity.getLong(_model.getCreateTime()); long cookieSet = entity.getLong(_model.getCookieSetTime()); String lastNode = entity.getString(_model.getLastNode()); lastSaved = entity.getLong(_model.getLastSaved()); long expiry = entity.getLong(_model.getExpiry()); long maxInactive = entity.getLong(_model.getMaxInactive()); Blob blob = (Blob) entity.getBlob(_model.getAttributes());
info.add(new ExpiryInfo(entity.getString(_model.getId()),entity.getString(_model.getLastNode()), entity.getLong(_model.getExpiry())));
return !isExpired(entity.getLong(_model.getExpiry()));
static Backfill entityToBackfill(Entity entity) throws IOException { final WorkflowId workflowId = WorkflowId.create(entity.getString(PROPERTY_COMPONENT), entity.getString(PROPERTY_WORKFLOW)); final BackfillBuilder builder = Backfill.newBuilder() .id(entity.getKey().getName()) .start(timestampToInstant(entity.getTimestamp(PROPERTY_START))) .end(timestampToInstant(entity.getTimestamp(PROPERTY_END))) .workflowId(workflowId) .concurrency((int) entity.getLong(PROPERTY_CONCURRENCY)) .nextTrigger(timestampToInstant(entity.getTimestamp(PROPERTY_NEXT_TRIGGER))) .schedule(Schedule.parse(entity.getString(PROPERTY_SCHEDULE))) .allTriggered(entity.getBoolean(PROPERTY_ALL_TRIGGERED)) .halted(entity.getBoolean(PROPERTY_HALTED)) .reverse(read(entity, PROPERTY_REVERSE, Boolean.FALSE)); if (entity.contains(PROPERTY_DESCRIPTION)) { builder.description(entity.getString(PROPERTY_DESCRIPTION)); } if (entity.contains(PROPERTY_TRIGGER_PARAMETERS)) { builder.triggerParameters(OBJECT_MAPPER.readValue( entity.getString(PROPERTY_TRIGGER_PARAMETERS), TriggerParameters.class)); } return builder.build(); }