com.googlecode.objectify.annotation.Entity Java Examples

The following examples show how to use com.googlecode.objectify.annotation.Entity. 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: ChildEntityReader.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Expands non-entity polymorphic classes into their child types. */
@SuppressWarnings("unchecked")
private ImmutableList<Class<? extends I>> expandPolymorphicClasses(
    ImmutableSet<Class<? extends I>> resourceClasses) {
  ImmutableList.Builder<Class<? extends I>> builder = new ImmutableList.Builder<>();
  for (Class<? extends I> clazz : resourceClasses) {
    if (clazz.isAnnotationPresent(Entity.class)) {
      builder.add(clazz);
    } else {
      for (Class<? extends ImmutableObject> entityClass : ALL_CLASSES) {
        if (clazz.isAssignableFrom(entityClass)) {
          builder.add((Class<? extends I>) entityClass);
        }
      }
    }
  }
  return builder.build();
}
 
Example #2
Source File: EntityClassesTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntityClasses_entitySubclassesHaveKindsMatchingBaseEntities() {
  Set<String> baseEntityKinds =
      ALL_CLASSES
          .stream()
          .filter(hasAnnotation(Entity.class))
          .map(Key::getKind)
          .collect(toImmutableSet());
  Set<String> entitySubclassKinds =
      ALL_CLASSES
          .stream()
          .filter(hasAnnotation(EntitySubclass.class))
          .map(Key::getKind)
          .collect(toImmutableSet());
  assertWithMessage("base entity kinds")
      .that(baseEntityKinds)
      .containsAtLeastElementsIn(entitySubclassKinds);
}
 
Example #3
Source File: CommitLogMutation.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new mutation entity created from a raw Datastore Entity instance.
 *
 * <p>The mutation key is generated deterministically from the {@code entity} key. The Entity
 * itself is serialized to bytes and stored within the returned mutation.
 */
@VisibleForTesting
public static CommitLogMutation createFromRaw(
    Key<CommitLogManifest> parent,
    com.google.appengine.api.datastore.Entity rawEntity) {
  CommitLogMutation instance = new CommitLogMutation();
  instance.parent = checkNotNull(parent);
  // Creates a web-safe key string.
  instance.entityKey = KeyFactory.keyToString(rawEntity.getKey());
  instance.entityProtoBytes = convertToPb(rawEntity).toByteArray();
  return instance;
}
 
Example #4
Source File: CommitLogRevisionsTranslatorFactoryTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testRawEntityLayout() {
  save(new TestObject());
  clock.advanceBy(standardDays(1));
  com.google.appengine.api.datastore.Entity entity =
      tm().transactNewReadOnly(() -> ofy().save().toEntity(reload()));
  assertThat(entity.getProperties().keySet()).containsExactly("revisions.key", "revisions.value");
  assertThat(entity.getProperties()).containsEntry(
      "revisions.key", ImmutableList.of(START_TIME.toDate(), START_TIME.plusDays(1).toDate()));
  assertThat(entity.getProperty("revisions.value")).isInstanceOf(List.class);
  assertThat(((List<Object>) entity.getProperty("revisions.value")).get(0))
      .isInstanceOf(com.google.appengine.api.datastore.Key.class);
}
 
Example #5
Source File: CommitLogRevisionsTranslatorFactoryTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoad_missingRevisionRawProperties_createsEmptyObject() {
  com.google.appengine.api.datastore.Entity entity =
      tm().transactNewReadOnly(() -> ofy().save().toEntity(new TestObject()));
  entity.removeProperty("revisions.key");
  entity.removeProperty("revisions.value");
  TestObject object = ofy().load().fromEntity(entity);
  assertThat(object.revisions).isNotNull();
  assertThat(object.revisions).isEmpty();
}
 
Example #6
Source File: EntityClassesTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntityClasses_baseEntitiesHaveUniqueKinds() {
  assertWithMessage("base entity kinds")
      .about(streams())
      .that(ALL_CLASSES.stream().filter(hasAnnotation(Entity.class)).map(Key::getKind))
      .containsNoDuplicates();
}
 
Example #7
Source File: EntityClassesTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntityClasses_eitherBaseEntityOrEntitySubclass() {
  for (Class<?> clazz : ALL_CLASSES) {
    boolean isEntityXorEntitySubclass =
        clazz.isAnnotationPresent(Entity.class) ^ clazz.isAnnotationPresent(EntitySubclass.class);
    assertWithMessage("class " + clazz.getSimpleName() + " is @Entity or @EntitySubclass")
        .that(isEntityXorEntitySubclass)
        .isTrue();
  }
}
 
Example #8
Source File: AppEngineRuleTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testOfyEntities_uniqueKinds() {
  try (ScanResult scanResult =
      new ClassGraph()
          .enableAnnotationInfo()
          .ignoreClassVisibility()
          .whitelistPackages("google.registry")
          .scan()) {
    Multimap<String, Class<?>> kindToEntityMultiMap =
        scanResult.getClassesWithAnnotation(Entity.class.getName()).stream()
            .filter(clazz -> !clazz.getName().equals(TestObject.class.getName()))
            .map(clazz -> clazz.loadClass())
            .collect(
                Multimaps.toMultimap(
                    Key::getKind,
                    clazz -> clazz,
                    MultimapBuilder.hashKeys().linkedListValues()::build));
    Map<String, Collection<Class<?>>> conflictingKinds =
        kindToEntityMultiMap.asMap().entrySet().stream()
            .filter(e -> e.getValue().size() > 1)
            .collect(entriesToImmutableMap());
    assertWithMessage(
            "Conflicting Ofy kinds found. Tests will break if they are registered with "
                + " AppEngineRule in the same test executor.")
        .that(conflictingKinds)
        .isEmpty();
  }
}
 
Example #9
Source File: ObjectifyService.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Register classes that can be persisted via Objectify as Datastore entities. */
private static void registerEntityClasses(
    ImmutableSet<Class<? extends ImmutableObject>> entityClasses) {
  // Register all the @Entity classes before any @EntitySubclass classes so that we can check
  // that every @Entity registration is a new kind and every @EntitySubclass registration is not.
  // This is future-proofing for Objectify 5.x where the registration logic gets less lenient.

  for (Class<?> clazz :
      Streams.concat(
              entityClasses.stream().filter(hasAnnotation(Entity.class)),
              entityClasses.stream().filter(hasAnnotation(Entity.class).negate()))
          .collect(toImmutableSet())) {
    String kind = Key.getKind(clazz);
    boolean registered = factory().getMetadata(kind) != null;
    if (clazz.isAnnotationPresent(Entity.class)) {
      // Objectify silently replaces current registration for a given kind string when a different
      // class is registered again for this kind. For simplicity's sake, throw an exception on any
      // re-registration.
      checkState(
          !registered,
          "Kind '%s' already registered, cannot register new @Entity %s",
          kind,
          clazz.getCanonicalName());
    } else if (clazz.isAnnotationPresent(EntitySubclass.class)) {
      // Ensure that any @EntitySubclass classes have also had their parent @Entity registered,
      // which Objectify nominally requires but doesn't enforce in 4.x (though it may in 5.x).
      checkState(registered,
          "No base entity for kind '%s' registered yet, cannot register new @EntitySubclass %s",
          kind, clazz.getCanonicalName());
    }
    com.googlecode.objectify.ObjectifyService.register(clazz);
    // Autogenerated ids make the commit log code very difficult since we won't always be able
    // to create a key for an entity immediately when requesting a save. So, we require such
    // entities to implement google.registry.model.Buildable as its build() function allocates the
    // id to the entity.
    if (factory().getMetadata(clazz).getKeyMetadata().isIdGeneratable()) {
      checkState(
          Buildable.class.isAssignableFrom(clazz),
          "Can't register %s: Entity with autogenerated ids (@Id on a Long) must implement"
              + " google.registry.model.Buildable.",
          kind);
    }
  }
}
 
Example #10
Source File: CommitLogMutation.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Deserializes embedded entity bytes and returns it. */
public com.google.appengine.api.datastore.Entity getEntity() {
  return createFromPbBytes(entityProtoBytes);
}