• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java KeyFactory类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中com.google.cloud.datastore.KeyFactory的典型用法代码示例。如果您正苦于以下问题:Java KeyFactory类的具体用法?Java KeyFactory怎么用?Java KeyFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



KeyFactory类属于com.google.cloud.datastore包,在下文中一共展示了KeyFactory类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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));
	}
}
 
开发者ID:tkob,项目名称:spring-data-gclouddatastore,代码行数:17,代码来源:SimpleGcloudDatastoreRepository.java


示例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;
}
 
开发者ID:tkob,项目名称:spring-data-gclouddatastore,代码行数:17,代码来源:SimpleGcloudDatastoreRepository.java


示例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);
		}
	}
}
 
开发者ID:tkob,项目名称:spring-data-gclouddatastore,代码行数:26,代码来源:GcloudDatastoreQueryCreator.java


示例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);
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:22,代码来源:ConceptsTest.java


示例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);
}
 
开发者ID:GoogleCloudPlatform,项目名称:tomcat-runtime,代码行数:34,代码来源:DatastoreStore.java


示例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();
}
 
开发者ID:GoogleCloudPlatform,项目名称:tomcat-runtime,代码行数:23,代码来源:DatastoreSession.java


示例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")));
}
 
开发者ID:GoogleCloudPlatform,项目名称:tomcat-runtime,代码行数:17,代码来源:DatastoreSessionTest.java


示例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"));
}
 
开发者ID:GoogleCloudPlatform,项目名称:tomcat-runtime,代码行数:20,代码来源:DatastoreSessionTest.java


示例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);
}
 
开发者ID:GoogleCloudPlatform,项目名称:tomcat-runtime,代码行数:22,代码来源:DatastoreStoreTest.java


示例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"));
}
 
开发者ID:GoogleCloudPlatform,项目名称:tomcat-runtime,代码行数:24,代码来源:DatastoreStoreTest.java


示例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;
}
 
开发者ID:sai-pullabhotla,项目名称:catatumbo,代码行数:24,代码来源:DefaultDatastoreReader.java


示例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;
}
 
开发者ID:sai-pullabhotla,项目名称:catatumbo,代码行数:24,代码来源:DefaultDatastoreReader.java


示例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;
}
 
开发者ID:sai-pullabhotla,项目名称:catatumbo,代码行数:15,代码来源:DefaultEntityManager.java


示例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"));
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:38,代码来源:DatastoreServlet.java


示例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);
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:9,代码来源:ConceptsTest.java


示例16: testKeyWithMultilevelParent

import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
@Test
public void testKeyWithMultilevelParent() {
  // [START key_with_multilevel_parent]
  KeyFactory keyFactory = datastore.newKeyFactory()
      .addAncestors(PathElement.of("User", "Alice"), PathElement.of("TaskList", "default"))
      .setKind("Task");
  Key taskKey = keyFactory.newKey("sampleTask");
  // [END key_with_multilevel_parent]
  assertValidKey(taskKey);
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:11,代码来源:ConceptsTest.java


示例17: setUpTransferTests

import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
private List<Key> setUpTransferTests() {
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("People");
  Key from = keyFactory.newKey("from");
  Key to = keyFactory.newKey("to");
  datastore.put(Entity.newBuilder(from).set("balance", 100).build());
  datastore.put(Entity.newBuilder(to).set("balance", 0).build());
  return ImmutableList.of(from, to);
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:9,代码来源:ConceptsTest.java


示例18: serializeSession

import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
/**
 * Serialize a session to a list of Entities that can be stored to the Datastore.
 * @param session The session to serialize.
 * @return A list of one or more entities containing the session and its attributes.
 * @throws IOException If the session cannot be serialized.
 */
@VisibleForTesting
List<Entity> serializeSession(DatastoreSession session, Key sessionKey,
    KeyFactory attributeKeyFactory) throws IOException {
  TraceContext serializationContext = startSpan("Serialization of the session");
  List<Entity> entities = session.saveToEntities(sessionKey, attributeKeyFactory);
  endSpan(serializationContext);
  return entities;
}
 
开发者ID:GoogleCloudPlatform,项目名称:tomcat-runtime,代码行数:15,代码来源:DatastoreStore.java


示例19: saveAttributesToEntity

import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
/**
 * Serialize the session attributes into entities.
 * @param attributeKeyFactory The key builder for the entities.
 * @return A list of entities where the key correspond to the name of the attribute
           and the property `value` to the serialized attribute.
 * @throws IOException If an error occur during the serialization.
 */
@VisibleForTesting
List<Entity> saveAttributesToEntity(KeyFactory attributeKeyFactory) throws
    IOException {
  Stream<Entity> entities = Collections.list(getAttributeNames()).stream()
      .filter(name -> accessedAttributes.contains(name))
      .filter(name -> isAttributeDistributable(name, getAttribute(name)))
      .map(name -> serializeAttribute(attributeKeyFactory, name));

  try {
    return entities.collect(Collectors.toList());
  } catch (UncheckedIOException e) {
    throw e.getCause();
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:tomcat-runtime,代码行数:22,代码来源:DatastoreSession.java


示例20: testSerializationError

import com.google.cloud.datastore.KeyFactory; //导入依赖的package包/类
@Test(expected = NotSerializableException.class)
public void testSerializationError() throws Exception {
  DatastoreSession session = spy(new DatastoreSession(sessionManager));
  session.setValid(true);
  session.setAttribute("count", 5);
  when(session.isAttributeDistributable(any(), any())).thenReturn(true);
  when(session.getAttribute("count")).thenReturn(sessionManager);

  session.saveAttributesToEntity(new KeyFactory("project").setKind("kind"));
}
 
开发者ID:GoogleCloudPlatform,项目名称:tomcat-runtime,代码行数:11,代码来源:DatastoreSessionTest.java



注:本文中的com.google.cloud.datastore.KeyFactory类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java Meddle类代码示例发布时间:2022-05-22
下一篇:
Java EllipseVertexShapeTransformer类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap