Java Code Examples for com.googlecode.objectify.Key#create()

The following examples show how to use com.googlecode.objectify.Key#create() . 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: EppResourceUtils.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Nullable
private static <T extends EppResource> Key<CommitLogManifest>
    findMostRecentRevisionAtTime(final T resource, final DateTime timestamp) {
  final Key<T> resourceKey = Key.create(resource);
  Entry<?, Key<CommitLogManifest>> revision = resource.getRevisions().floorEntry(timestamp);
  if (revision != null) {
    logger.atInfo().log(
        "Found revision history at %s for %s: %s", timestamp, resourceKey, revision);
    return revision.getValue();
  }
  // Fall back to the earliest revision if we don't have one before the requested timestamp.
  revision = resource.getRevisions().firstEntry();
  if (revision != null) {
    logger.atSevere().log(
        "Found no revision history at %s for %s, using earliest revision: %s",
        timestamp, resourceKey, revision);
    return revision.getValue();
  }
  // Ultimate fallback: There are no revisions whatsoever, so return null.
  logger.atSevere().log("Found no revision history at all for %s", resourceKey);
  return null;
}
 
Example 2
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a list of Conferences that the user created.
 * In order to receive the websafeConferenceKey via the JSON params, uses a POST method.
 *
 * @param user A user who invokes this method, null when the user is not signed in.
 * @return a list of Conferences that the user created.
 * @throws UnauthorizedException when the user is not signed in.
 */
@ApiMethod(
        name = "getConferencesCreated",
        path = "getConferencesCreated",
        httpMethod = HttpMethod.POST
)
public List<Conference> getConferencesCreated(final User user) throws UnauthorizedException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String userId = user.getUserId();
    Key<Profile> userKey = Key.create(Profile.class, userId);
    return ofy().load().type(Conference.class)
            .ancestor(userKey)
            .order("name").list();
}
 
Example 3
Source File: DeleteLoadTestDataAction.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private void deleteResource(EppResource resource) {
  final Key<EppResourceIndex> eppIndex =
      Key.create(EppResourceIndex.create(Key.create(resource)));
  final Key<? extends ForeignKeyIndex<?>> fki = ForeignKeyIndex.createKey(resource);
  int numEntitiesDeleted =
      tm()
          .transact(
              () -> {
                // This ancestor query selects all descendant entities.
                List<Key<Object>> resourceAndDependentKeys =
                    ofy().load().ancestor(resource).keys().list();
                ImmutableSet<Key<?>> allKeys =
                    new ImmutableSet.Builder<Key<?>>()
                        .add(fki)
                        .add(eppIndex)
                        .addAll(resourceAndDependentKeys)
                        .build();
                if (isDryRun) {
                  logger.atInfo().log("Would hard-delete the following entities: %s", allKeys);
                } else {
                  ofy().deleteWithoutBackup().keys(allKeys);
                }
                return allKeys.size();
              });
  getContext().incrementCounter("total entities deleted", numEntitiesDeleted);
}
 
Example 4
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a list of Conferences that the user created.
 * In order to receive the websafeConferenceKey via the JSON params, uses a POST method.
 *
 * @param user A user who invokes this method, null when the user is not signed in.
 * @return a list of Conferences that the user created.
 * @throws UnauthorizedException when the user is not signed in.
 */
@ApiMethod(
        name = "getConferencesCreated",
        path = "getConferencesCreated",
        httpMethod = HttpMethod.POST
)
public List<Conference> getConferencesCreated(final User user) throws UnauthorizedException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String userId = user.getUserId();
    Key<Profile> userKey = Key.create(Profile.class, userId);
    return ofy().load().type(Conference.class)
            .ancestor(userKey)
            .order("name").list();
}
 
Example 5
Source File: RefreshDnsOnHostRenameAction.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a packaged-up {@link DnsRefreshRequest} parsed from a task queue task.
 */
static DnsRefreshRequest createFromTask(TaskHandle task, DateTime now) throws Exception {
  ImmutableMap<String, String> params = ImmutableMap.copyOf(task.extractParams());
  Key<HostResource> hostKey =
      Key.create(checkNotNull(params.get(PARAM_HOST_KEY), "Host to refresh not specified"));
  HostResource host =
      checkNotNull(ofy().load().key(hostKey).now(), "Host to refresh doesn't exist");
  boolean isHostDeleted =
      isDeleted(host, latestOf(now, host.getUpdateAutoTimestamp().getTimestamp()));
  if (isHostDeleted) {
    logger.atInfo().log("Host %s is already deleted, not refreshing DNS.", hostKey);
  }
  return new AutoValue_RefreshDnsOnHostRenameAction_DnsRefreshRequest.Builder()
      .setHostKey(hostKey)
      .setLastUpdateTime(host.getUpdateAutoTimestamp().getTimestamp())
      .setRequestedTime(
          DateTime.parse(
              checkNotNull(params.get(PARAM_REQUESTED_TIME), "Requested time not specified")))
      .setIsRefreshNeeded(!isHostDeleted)
      .setTask(task)
      .build();
}
 
Example 6
Source File: AsyncTaskEnqueuer.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Enqueues a task to asynchronously delete a contact or host, by key. */
public void enqueueAsyncDelete(
    EppResource resourceToDelete,
    DateTime now,
    String requestingClientId,
    Trid trid,
    boolean isSuperuser) {
  Key<EppResource> resourceKey = Key.create(resourceToDelete);
  logger.atInfo().log(
      "Enqueuing async deletion of %s on behalf of registrar %s.",
      resourceKey, requestingClientId);
  TaskOptions task =
      TaskOptions.Builder.withMethod(Method.PULL)
          .countdownMillis(asyncDeleteDelay.getMillis())
          .param(PARAM_RESOURCE_KEY, resourceKey.getString())
          .param(PARAM_REQUESTING_CLIENT_ID, requestingClientId)
          .param(PARAM_SERVER_TRANSACTION_ID, trid.getServerTransactionId())
          .param(PARAM_IS_SUPERUSER, Boolean.toString(isSuperuser))
          .param(PARAM_REQUESTED_TIME, now.toString());
  trid.getClientTransactionId()
      .ifPresent(clTrid -> task.param(PARAM_CLIENT_TRANSACTION_ID, clTrid));
  addTaskToQueueWithRetry(asyncDeletePullQueue, task);
}
 
Example 7
Source File: PremiumList.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Returns a new PremiumListRevision for the given key and premium list map. */
@VisibleForTesting
public static PremiumListRevision create(PremiumList parent, Set<String> premiumLabels) {
  PremiumListRevision revision = new PremiumListRevision();
  revision.parent = Key.create(parent);
  revision.revisionId = allocateId();
  // All premium list labels are already punycoded, so don't perform any further character
  // encoding on them.
  revision.probablePremiumLabels =
      BloomFilter.create(unencodedCharsFunnel(), premiumLabels.size());
  premiumLabels.forEach(revision.probablePremiumLabels::put);
  try {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    revision.probablePremiumLabels.writeTo(bos);
    checkArgument(
        bos.size() <= MAX_BLOOM_FILTER_BYTES,
        "Too many premium labels were specified; Bloom filter exceeds max entity size");
  } catch (IOException e) {
    throw new IllegalStateException("Could not serialize premium labels Bloom filter", e);
  }
  return revision;
}
 
Example 8
Source File: DeleteContactsAndHostsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Perform any type-specific tasks on the resource to be deleted (and/or its dependencies). */
private void performDeleteTasks(
    EppResource existingResource,
    EppResource deletedResource,
    DateTime deletionTime,
    HistoryEntry historyEntryForDelete) {
  if (existingResource instanceof ContactResource) {
    handlePendingTransferOnDelete(
        (ContactResource) existingResource,
        (ContactResource) deletedResource,
        deletionTime,
        historyEntryForDelete);
  } else if (existingResource instanceof HostResource) {
    HostResource host = (HostResource) existingResource;
    if (host.isSubordinate()) {
      dnsQueue.addHostRefreshTask(host.getHostName());
      tm().saveNewOrUpdate(
              tm().load(host.getSuperordinateDomain())
                  .asBuilder()
                  .removeSubordinateHost(host.getHostName())
                  .build());
    }
  } else {
    throw new IllegalStateException(
        "EPP resource of unknown type: " + Key.create(existingResource));
  }
}
 
Example 9
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a Profile object associated with the given user object. The cloud
 * endpoints system automatically inject the User object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @return Profile object.
 * @throws UnauthorizedException
 *             when the User object is null.
 */
@ApiMethod(name = "getProfile", path = "profile", httpMethod = HttpMethod.GET)
public Profile getProfile(final User user) throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO
    // load the Profile Entity
    String userId = user.getUserId();
    Key key = Key.create(Profile.class, userId);

    Profile profile = (Profile) ofy().load().key(key).now();
    return profile;
}
 
Example 10
Source File: KeyStdDeserializer.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
@Override
public Key deserialize( JsonParser jp, DeserializationContext ctxt ) throws IOException {
    JsonNode node = jp.readValueAsTree();

    JsonParser rawJsonParser = node.get( KeyConstant.RAW ).traverse();
    rawJsonParser.setCodec( jp.getCodec() );
    com.google.appengine.api.datastore.Key key = rawJsonParser.readValueAs( com.google.appengine.api.datastore.Key.class );

    return Key.create( key );
}
 
Example 11
Source File: Conference.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
public Conference(final long id, final String organizerUserId,
                  final ConferenceForm conferenceForm) {
    Preconditions.checkNotNull(conferenceForm.getName(), "The name is required");
    this.id = id;
    this.profileKey = Key.create(Profile.class, organizerUserId);
    this.organizerUserId = organizerUserId;
    updateWithConferenceForm(conferenceForm);
}
 
Example 12
Source File: ClaimsListShard.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static Key<ClaimsListRevision> createKey(ClaimsListSingleton singleton) {
  ClaimsListRevision revision = new ClaimsListRevision();
  revision.versionId = allocateId();
  revision.parent = Key.create(singleton);
  return Key.create(revision);
}
 
Example 13
Source File: Conference.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
public Conference(final long id, final String organizerUserId,
                  final ConferenceForm conferenceForm) {
    Preconditions.checkNotNull(conferenceForm.getName(), "The name is required");
    this.id = id;
    this.profileKey = Key.create(Profile.class, organizerUserId);
    this.organizerUserId = organizerUserId;
    updateWithConferenceForm(conferenceForm);
}
 
Example 14
Source File: DeleteContactsAndHostsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Determine the proper history entry type for the delete operation, as a function of
 * whether or not the delete was successful.
 */
private HistoryEntry.Type getHistoryEntryType(EppResource resource, boolean successfulDelete) {
  if (resource instanceof ContactResource) {
    return successfulDelete ? CONTACT_DELETE : CONTACT_DELETE_FAILURE;
  } else if (resource instanceof HostResource) {
    return successfulDelete ? HOST_DELETE : HOST_DELETE_FAILURE;
  } else {
    throw new IllegalStateException("EPP resource of unknown type: " + Key.create(resource));
  }
}
 
Example 15
Source File: HistoryEntry.java    From nomulus with Apache License 2.0 4 votes vote down vote up
public B setParent(EppResource parent) {
  getInstance().parent = Key.create(parent);
  return thisCastToDerived();
}
 
Example 16
Source File: PollMessage.java    From nomulus with Apache License 2.0 4 votes vote down vote up
public B setParent(HistoryEntry parent) {
  getInstance().parent = Key.create(parent);
  return thisCastToDerived();
}
 
Example 17
Source File: VKey.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Creates a symmetric {@link VKey} in which both sql and ofy keys are {@code id}. */
public static <T> VKey<T> create(Class<? extends T> kind, long id) {
  return new VKey(kind, Key.create(kind, id), id);
}
 
Example 18
Source File: CommitLogCheckpoint.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Creates a key for the CommitLogCheckpoint for the given wall time. */
public static Key<CommitLogCheckpoint> createKey(DateTime checkpointTime) {
  return Key.create(
      CommitLogCheckpointRoot.getKey(), CommitLogCheckpoint.class, checkpointTime.getMillis());
}
 
Example 19
Source File: EntityGroupRoot.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** The root key for cross-tld resources such as registrars. */
public static Key<EntityGroupRoot> getCrossTldKey() {
  return Key.create(EntityGroupRoot.class, "cross-tld");
}
 
Example 20
Source File: ChatRoomParticipants.java    From appengine-websocketchat-java with Apache License 2.0 2 votes vote down vote up
/**
 * Creates an entity representing the list of the participants in a chat room within a single
 * server node.
 *
 * @param room a name of the chat room.
 * @param serverNode an identifier of a single server node, in the form of websocket URL,
 *                   e.x. "ws://173.255.112.201:65080/".
 * @param participants a set of participants in the given chat room within a single server node.
 */
public ChatRoomParticipants(String room, String serverNode, Set<String> participants) {
  this.parentKey = Key.create(ChatRoomParticipants.class, room);
  this.serverNode = serverNode;
  this.participants = new TreeSet<>(participants);
}