Java Code Examples for com.google.cloud.datastore.Datastore#run()

The following examples show how to use com.google.cloud.datastore.Datastore#run() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MessageRepositoryImpl.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> retrieveClaims(int limit) {
  // Get claim saved in Datastore
  Datastore datastore = getDatastoreInstance();
  Query<Entity> query = Query.newEntityQueryBuilder().setKind(claimsKind).setLimit(limit).build();
  QueryResults<Entity> results = datastore.run(query);

  List<String> claims = new ArrayList<>();
  while (results.hasNext()) {
    Entity entity = results.next();
    String claim = entity.getString("claim");
    if (claim != null) {
      claims.add(claim);
    }
  }
  return claims;
}
 
Example 2
Source File: MessageRepositoryImpl.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> retrieveTokens(int limit) {
  // Get token saved in Datastore
  Datastore datastore = getDatastoreInstance();
  Query<Entity> query = Query.newEntityQueryBuilder().setKind(tokensKind).setLimit(limit).build();
  QueryResults<Entity> results = datastore.run(query);

  List<String> tokens = new ArrayList<>();
  while (results.hasNext()) {
    Entity entity = results.next();
    String token = entity.getString("token");
    if (token != null) {
      tokens.add(token);
    }
  }
  return tokens;
}
 
Example 3
Source File: TestUtils.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static void wipeDatastore() {
  Datastore datastore = getDatastore();
  QueryResults<Key> guestbooks =
      datastore.run(Query.newKeyQueryBuilder().setKind("Greeting").build());
  ArrayList<Key> keys = Lists.newArrayList(guestbooks);

  if (!keys.isEmpty()) {
    datastore.delete(keys.toArray(new Key[keys.size()]));
  }
}
 
Example 4
Source File: DefaultDatastoreMetadata.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public QueryResponse<String> getNamespaces(DatastoreCursor fromCursor, int limit) {
  try {
    String query = "SELECT __key__ FROM " + ENTITY_NAMESPACES + " ORDER BY __key__";
    if (limit > 0) {
      query += " LIMIT @Limit";
    }
    query += " OFFSET @Offset";
    GqlQuery.Builder<Key> gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query);
    if (limit > 0) {
      gqlQueryBuilder.setBinding("Limit", limit);
    }
    gqlQueryBuilder.setBinding("Offset", Cursor.fromUrlSafe(fromCursor.getEncoded()));
    GqlQuery<Key> gqlQuery = gqlQueryBuilder.build();
    Datastore datastore = entityManager.getDatastore();
    QueryResults<Key> results = datastore.run(gqlQuery);
    DefaultQueryResponse<String> response = new DefaultQueryResponse<>();
    List<String> namespaces = new ArrayList<>(Math.max(limit, 50));
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      Key key = results.next();
      String name = key.getName();
      namespaces.add(name == null ? "" : name);
    }
    response.setResults(namespaces);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 5
Source File: DatastoreUtil.java    From styx with Apache License 2.0 5 votes vote down vote up
static void deleteDatastoreNamespace(Datastore datastore, String namespace) {
  var keys = new ArrayList<Key>();
  var query = datastore.run(KeyQuery.newKeyQueryBuilder().setNamespace(namespace).build());
  query.forEachRemaining(key -> {
    if (!RESERVED_KIND_PATTERN.matcher(key.getKind()).matches()) {
      keys.add(key);
    }
  });
  if (keys.isEmpty()) {
    return;
  }
  log.info("Deleting datastore entities in namespace {}: {}", namespace, keys.size());
  Lists.partition(keys, 500).forEach(keyBatch ->
      datastore.delete(keyBatch.toArray(Key[]::new)));
}
 
Example 6
Source File: MessageRepositoryImpl.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public List<Message> retrieve(int limit) {
  // Get Message saved in Datastore
  Datastore datastore = getDatastoreInstance();
  Query<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind(messagesKind)
          .setLimit(limit)
          .addOrderBy(StructuredQuery.OrderBy.desc("publishTime"))
          .build();
  QueryResults<Entity> results = datastore.run(query);

  List<Message> messages = new ArrayList<>();
  while (results.hasNext()) {
    Entity entity = results.next();
    Message message = new Message(entity.getString("messageId"));
    String data = entity.getString("data");
    if (data != null) {
      message.setData(data);
    }
    String publishTime = entity.getString("publishTime");
    if (publishTime != null) {
      message.setPublishTime(publishTime);
    }
    messages.add(message);
  }
  return messages;
}
 
Example 7
Source File: MessageRepositoryImpl.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public List<Message> retrieve(int limit) {
  // Get Message saved in Datastore
  Datastore datastore = getDatastoreInstance();
  Query<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind(messagesKind)
          .setLimit(limit)
          .addOrderBy(StructuredQuery.OrderBy.desc("publishTime"))
          .build();
  QueryResults<Entity> results = datastore.run(query);

  List<Message> messages = new ArrayList<>();
  while (results.hasNext()) {
    Entity entity = results.next();
    Message message = new Message(entity.getString("messageId"));
    String data = entity.getString("data");
    if (data != null) {
      message.setData(data);
    }
    String publishTime = entity.getString("publishTime");
    if (publishTime != null) {
      message.setPublishTime(publishTime);
    }
    messages.add(message);
  }
  return messages;
}
 
Example 8
Source File: MessageRepositoryImpl.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public List<Message> retrieve(int limit) {
  // Get Message saved in Datastore
  Datastore datastore = getDatastoreInstance();
  Query<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind(messagesKind)
          .setLimit(limit)
          .addOrderBy(StructuredQuery.OrderBy.desc("publishTime"))
          .build();
  QueryResults<Entity> results = datastore.run(query);

  List<Message> messages = new ArrayList<>();
  while (results.hasNext()) {
    Entity entity = results.next();
    Message message = new Message(entity.getString("messageId"));
    String data = entity.getString("data");
    if (data != null) {
      message.setData(data);
    }
    String publishTime = entity.getString("publishTime");
    if (publishTime != null) {
      message.setPublishTime(publishTime);
    }
    if (entity.contains("sourceLang")) {
      String sourceLang = entity.getString("sourceLang");
      if (sourceLang != null) {
        message.setSourceLang(sourceLang);
      }
    }
    if (entity.contains("targetLang")) {
      String targetLang = entity.getString("targetLang");
      if (targetLang != null) {
        message.setTargetLang(targetLang);
      }
    }
    messages.add(message);
  }
  return messages;
}
 
Example 9
Source File: DatastoreServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  // store only the first two octets of a users ip address
  String userIp = req.getRemoteAddr();
  InetAddress address = InetAddress.getByName(userIp);
  if (address instanceof Inet6Address) {
    // nest indexOf calls to find the second occurrence of a character in a string
    // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
    userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
  } else if (address instanceof Inet4Address) {
    userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
  }

  Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("visit");
  IncompleteKey key = keyFactory.setKind("visit").newKey();

  // Record a visit to the datastore, storing the IP and timestamp.
  FullEntity<IncompleteKey> curVisit =
      FullEntity.newBuilder(key).set("user_ip", userIp).set("timestamp", Timestamp.now()).build();
  datastore.add(curVisit);

  // Retrieve the last 10 visits from the datastore, ordered by timestamp.
  Query<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind("visit")
          .setOrderBy(StructuredQuery.OrderBy.desc("timestamp"))
          .setLimit(10)
          .build();
  QueryResults<Entity> results = datastore.run(query);

  resp.setContentType("text/plain");
  PrintWriter out = resp.getWriter();
  out.print("Last 10 visits:\n");
  while (results.hasNext()) {
    Entity entity = results.next();
    out.format(
        "Time: %s Addr: %s\n", entity.getTimestamp("timestamp"), entity.getString("user_ip"));
  }
}
 
Example 10
Source File: AddEntitiesAndRunQuery.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
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("[email protected]");
  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("[email protected]");
  Entity janeEntity =
      Entity.newBuilder(janeKey)
          .set("name", "Jane Doe")
          .set("age", 44)
          .set("favorite_food", "pizza")
          .build();
  Key joeKey = keyFactory.newKey("[email protected]");
  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!");
  }
}