本文整理汇总了Java中com.google.cloud.datastore.KeyFactory类的典型用法代码示例。如果您正苦于以下问题:Java KeyFactory类的具体用法?Java KeyFactory怎么用?Java KeyFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
KeyFactory类属于com.google.cloud.datastore包,在下文中一共展示了KeyFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: setAncestorFilter
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
private <U> void setAncestorFilter(StructuredQuery.Builder<U> queryBuilder) {
Datastore datastore = datastoreOptions.getService();
Deque<PathElement> ancestors = Context.getAncestors();
Deque<PathElement> init = new LinkedList<>();
init.addAll(ancestors);
PathElement last = init.pollLast();
if (last != null) {
KeyFactory keyFactory = datastore.newKeyFactory();
keyFactory.addAncestors(init).setKind(last.getKind());
Key key = last.hasId() ? keyFactory.newKey(last.getId())
: keyFactory.newKey(last.getName());
queryBuilder.setFilter(StructuredQuery.PropertyFilter.hasAncestor(key));
}
}
示例2: getKey
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
private Key getKey(ID id) {
Datastore datastore = this.datastoreOptions.getService();
KeyFactory keyFactory = datastore.newKeyFactory().setKind(this.kind);
Iterable<PathElement> ancestors = Context.getAncestors();
keyFactory.addAncestors(ancestors);
Key key;
if (id instanceof Number) {
key = keyFactory.newKey(((Number) id).longValue());
}
else {
key = keyFactory.newKey(id.toString());
}
return key;
}
示例3: setAncestorFilter
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
protected StructuredQuery.Filter setAncestorFilter(StructuredQuery.Filter filter) {
Datastore datastore = datastoreOptions.getService();
Deque<PathElement> ancestors = Context.getAncestors();
Deque<PathElement> init = new LinkedList<>();
init.addAll(ancestors);
PathElement last = init.pollLast();
if (last == null) {
return filter;
}
else {
KeyFactory keyFactory = datastore.newKeyFactory();
keyFactory.addAncestors(init).setKind(last.getKind());
Key key = last.hasId()
? keyFactory.newKey(last.getId()) : keyFactory.newKey(last.getName());
StructuredQuery.Filter ancestorFilter = StructuredQuery.PropertyFilter.hasAncestor(key);
if (filter == null) {
return ancestorFilter;
}
else {
return StructuredQuery.CompositeFilter.and(filter, ancestorFilter);
}
}
}
示例4: testNamespaceRunQuery
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
@Test
public void testNamespaceRunQuery() {
setUpQueryTests();
// [START namespace_run_query]
KeyFactory keyFactory = datastore.newKeyFactory().setKind("__namespace__");
Key startNamespace = keyFactory.newKey("g");
Key endNamespace = keyFactory.newKey("h");
Query<Key> query = Query.newKeyQueryBuilder()
.setKind("__namespace__")
.setFilter(CompositeFilter.and(
PropertyFilter.gt("__key__", startNamespace),
PropertyFilter.lt("__key__", endNamespace)))
.build();
List<String> namespaces = new ArrayList<>();
QueryResults<Key> results = datastore.run(query);
while (results.hasNext()) {
namespaces.add(results.next().getName());
}
// [END namespace_run_query]
assertEquals(ImmutableList.of("ghijklmnop"), namespaces);
}
示例5: save
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
/**
* Save the specified Session into this Store. Any previously saved information for
* the associated session identifier is replaced.
*
* <p>Attempt to serialize the session and send it to the datastore.</p>
*
* @throws IOException If an error occurs during the serialization of the session.
*
* @param session Session to be saved
*/
@Override
public void save(Session session) throws IOException {
log.debug("Persisting session: " + session.getId());
if (!(session instanceof DatastoreSession)) {
throw new IOException(
"The session must be an instance of DatastoreSession to be serialized");
}
DatastoreSession datastoreSession = (DatastoreSession) session;
Key sessionKey = newKey(session.getId());
KeyFactory attributeKeyFactory = datastore.newKeyFactory()
.setKind(sessionKind)
.addAncestor(PathElement.of(sessionKind, sessionKey.getName()));
List<Entity> entities = serializeSession(datastoreSession, sessionKey, attributeKeyFactory);
TraceContext datastoreSaveContext = startSpan("Storing the session in the Datastore");
datastore.put(entities.toArray(new FullEntity[0]));
datastore.delete(datastoreSession.getSuppressedAttributes().stream()
.map(attributeKeyFactory::newKey)
.toArray(Key[]::new));
endSpan(datastoreSaveContext);
}
示例6: serializeAttribute
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
/**
* Serialize an attribute an embed it into an entity whose key is generated by the provided
* KeyFactory.
* @param attributeKeyFactory The KeyFactory to use to create the key for the entity.
* @param name The name of the attribute to serialize.
* @return An Entity containing the serialized attribute.
*/
private Entity serializeAttribute(KeyFactory attributeKeyFactory, String name) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(getAttribute(name));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return Entity.newBuilder(attributeKeyFactory.newKey(name))
.set(SessionMetadata.ATTRIBUTE_VALUE_NAME,
BlobValue.newBuilder(Blob.copyFrom(bos.toByteArray()))
.setExcludeFromIndexes(true)
.build())
.build();
}
示例7: testAttributesSerializationKey
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
@Test
public void testAttributesSerializationKey() throws Exception {
DatastoreSession session = new DatastoreSession(sessionManager);
session.setValid(true);
session.setAttribute("count", 2);
session.setAttribute("map", new HashMap<>());
KeyFactory factory = new KeyFactory("project").setKind("kind");
List<Entity> entities = session.saveAttributesToEntity(factory);
assertTrue(entities.stream()
.map(BaseEntity::getKey)
.map(Key::getName)
.collect(Collectors.toSet())
.containsAll(Arrays.asList("count", "map")));
}
示例8: testSerializationCycle
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
@Test
public void testSerializationCycle() throws Exception {
DatastoreSession initialSession = new DatastoreSession(sessionManager);
initialSession.setValid(true);
initialSession.setAttribute("count", 5);
initialSession.setAttribute("map", Collections.singletonMap("key", "value"));
KeyFactory keyFactory = new KeyFactory("project").setKind("kind");
List<Entity> attributes = initialSession.saveToEntities(sessionKey, keyFactory);
DatastoreSession restoredSession = new DatastoreSession(sessionManager);
restoredSession.restoreFromEntities(sessionKey, attributes);
assertTrue(restoredSession.getAttribute("count") != null);
assertTrue(restoredSession.getAttribute("map") != null);
assertEquals(5, restoredSession.getAttribute("count"));
assertEquals("value", ((Map)restoredSession.getAttribute("map")).get("key"));
}
示例9: setUp
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
store = new DatastoreStore();
KeyFactory keyFactory = new KeyFactory("project").setKind("kind");
key = keyFactory.newKey(keyId);
attributeKey = keyFactory.newKey("attribute");
QueryResults<Key> keyQueryResults = new IteratorQueryResults<>(ImmutableList.of(key).iterator());
when(datastore.newKeyFactory()).thenAnswer((invocation) -> new KeyFactory("project"));
when(datastore.run(any(KeyQuery.class))).thenReturn(keyQueryResults);
when(manager.getContext()).thenReturn(new StandardContext());
when(manager.willAttributeDistribute(anyString(), any())).thenReturn(true);
when(manager.createEmptySession()).thenReturn(new DatastoreSession(manager));
store.setDatastore(datastore);
store.setClock(clock);
store.setSessionKind("kind");
store.setManager(manager);
}
示例10: testDecomposedSessionLoad
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
@Test
public void testDecomposedSessionLoad() throws Exception {
DatastoreSession session = new DatastoreSession(manager);
session.setValid(true);
session.setId(keyId);
session.setAttribute("count", 2);
session.setAttribute("map", Collections.singletonMap("key", "value"));
KeyFactory attributeKeyFactory = datastore.newKeyFactory()
.setKind("kind")
.addAncestor(PathElement.of("kind", key.getName()));
List<Entity> entities = session.saveToEntities(key, attributeKeyFactory);
QueryResults<Entity> queryResults = new IteratorQueryResults<>(entities.iterator());
when(datastore.<Entity>run(any())).thenReturn(queryResults);
Session restored = store.load(keyId);
assertEquals(keyId, restored.getId());
assertEquals(2, restored.getSession().getAttribute("count"));
assertEquals("value",
((Map<String, String>)session.getSession().getAttribute("map")).get("key"));
}
示例11: longListToNativeKeys
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
/**
* Converts the given list of identifiers into an array of native Key objects.
*
* @param entityClass
* the entity class to which these identifiers belong to.
* @param identifiers
* the list of identifiers to convert.
* @return an array of Key objects
*/
private Key[] longListToNativeKeys(Class<?> entityClass, List<Long> identifiers) {
if (identifiers == null || identifiers.isEmpty()) {
return new Key[0];
}
EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass);
Key[] nativeKeys = new Key[identifiers.size()];
KeyFactory keyFactory = entityManager.newNativeKeyFactory();
keyFactory.setKind(entityMetadata.getKind());
for (int i = 0; i < identifiers.size(); i++) {
long id = identifiers.get(i);
nativeKeys[i] = keyFactory.newKey(id);
}
return nativeKeys;
}
示例12: stringListToNativeKeys
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
/**
* Converts the given list of identifiers into an array of native Key objects.
*
* @param entityClass
* the entity class to which these identifiers belong to.
* @param identifiers
* the list of identifiers to convert.
* @return an array of Key objects
*/
private Key[] stringListToNativeKeys(Class<?> entityClass, List<String> identifiers) {
if (identifiers == null || identifiers.isEmpty()) {
return new Key[0];
}
EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass);
Key[] nativeKeys = new Key[identifiers.size()];
KeyFactory keyFactory = entityManager.newNativeKeyFactory();
keyFactory.setKind(entityMetadata.getKind());
for (int i = 0; i < identifiers.size(); i++) {
String id = identifiers.get(i);
nativeKeys[i] = keyFactory.newKey(id);
}
return nativeKeys;
}
示例13: newNativeKeyFactory
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
/**
* Creates and returns a new native KeyFactory. If a namespace was specified using {@link Tenant},
* the returned KeyFactory will have the specified namespace.
*
* @return a {@link KeyFactory}
*/
KeyFactory newNativeKeyFactory() {
KeyFactory keyFactory = datastore.newKeyFactory();
String namespace = Tenant.getNamespace();
if (namespace != null) {
keyFactory.setNamespace(namespace);
}
return keyFactory;
}
示例14: doGet
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
@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"));
}
}
示例15: testIncompleteKey
import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
@Test
public void testIncompleteKey() {
// [START incomplete_key]
KeyFactory keyFactory = datastore.newKeyFactory().setKind("Task");
Key taskKey = datastore.allocateId(keyFactory.newKey());
// [END incomplete_key]
assertValidKey(taskKey);
}