@Test public void testMarshall_Embedded() { RootEntity rootObject = new RootEntity(); // one entity ChildEntity childObject = new ChildEntity("Test City"); ChildEntity embeddedObject = new ChildEntity("Old Test City"); embeddedObject.setId(1L); embeddedObject.setType("EmbeddedType"); rootObject.setId("TestUser"); rootObject.setCount(25); childObject.setParent(rootObject); rootObject.setNewChildEntity(childObject); // one entity rootObject.setEmbeddedEntity(embeddedObject); // not included, @Embedded IdentityHashMap<Object, Entity> stack = testMarshaller.marshall(null, rootObject); Entity rootObjectEntity = stack.get(rootObject); Entity childObjectEntity = stack.get(childObject); EmbeddedEntity ee = (EmbeddedEntity) rootObjectEntity.getProperty("embeddedEntity"); Key childKey = (Key) rootObjectEntity.getProperty("newChildEntity"); Key parentKey = childKey.getParent(); assertEquals(2, stack.size()); assertNotNull(parentKey); assertEquals(EmbeddedEntity.class, ee.getClass()); assertTrue(childKey instanceof Key); assertEquals(rootObjectEntity.getKey().getId(), parentKey.getId()); assertEquals(rootObjectEntity.getKey().getName(), parentKey.getName()); assertEquals(1L, ee.getProperties().get("id")); assertEquals("EmbeddedType", ee.getProperties().get("type")); }
/** @throws Exception */ @Test public void allocateIdWithParentKey() throws Exception { Key parentKey = KeyFactory.createKey("Parent", 1); Key key = DatastoreUtil.allocateId(ds, parentKey, "Child"); assertThat(key, is(notNullValue())); assertThat(key.isComplete(), is(true)); }
/** @throws Exception */ @Test public void assignKeyIfNecessaryWhenParentExists() throws Exception { DatastoreUtil.allocateId(ds, "Child"); Key dummyKey2 = DatastoreUtil.allocateId(ds, "Child"); Key parentKey = DatastoreUtil.allocateId(ds, "Parent"); Entity entity = new Entity("Child", parentKey); DatastoreUtil.assignKeyIfNecessary(ds, entity); assertThat(entity.getKey().getId(), is(not(dummyKey2.getId() + 1))); }
@Override public ApiResponse generateRequestResponse(ApiRequest request) throws Exception { ApiResponse response = new ApiResponse(); // prevent spam UserEntry user = request.getUser(); long businessesCreated = user.getStats().getBusinessesCreated(); if (businessesCreated >= MAXIMUM_BUSINESS_CREATIONS) { Log.warn("Prevented business creation from user: "******"Spam prevention: You may not create any more businesses. Please contact us if you want to increase your quota.")); return response; } String name = request.getParameter("name"); String mail = request.getParameter("mail"); boolean addQueue = request.getParameterAsBoolean("addQueue", false); // create the business BusinessEntry businessEntry = new BusinessEntry(); businessEntry.setName(name); businessEntry.setMail(mail); Key businessKey = BusinessHelper.saveEntry(businessEntry); businessEntry.setKey(businessKey); // update user stats user.getStats().setBusinessesCreated(businessesCreated + 1); UserHelper.saveEntry(user); // add permission for business PermissionHelper.grantPermission(user, businessEntry, PermissionEntry.PERMISSION_OWN); if (addQueue) { // create a default queue QueueEntry queueEntry = new QueueEntry(businessKey.getId()); queueEntry.parseFromRequest(request); Key queueKey = QueueHelper.saveEntry(queueEntry); queueEntry.setKey(queueKey); // add permission for queue PermissionHelper.grantPermission( request.getUser(), queueEntry, PermissionEntry.PERMISSION_OWN); // add the new queue to the business in order to return both as one response ArrayList<QueueEntry> queues = new ArrayList<QueueEntry>(); queues.add(queueEntry); businessEntry.setQueues(queues); } response.setContent(businessEntry); return response; }
/** * ユーザーの取得 * * @param email * @return */ public static UserModel getOrNull(String userID) { Key key = createKey(userID); UserModel model = Memcache.get(key.toString()); if (model != null) return model; model = userModelDao.getOrNull(key); if (model != null) Memcache.put(model.getKey().toString(), model); return model; }
/** * Adds an Event todo in the Datastore * * @param et the event todo added * @return whether transaction is successful */ public boolean addEventTodo(EventTodoModel et) { boolean ok = false; if (getEventTodoModelByTodoId(et.getEventID(), et.getTodoId()) == null) { Key key = Datastore.allocateId(parentKey, "EventTodoModel"); Transaction trans = Datastore.beginTransaction(); et.setKey(key); et.setId(key.getId()); Datastore.put(et); trans.commit(); ok = true; } return ok; }
public void testFetch() { Entity entity = new Entity(HasTableAndColumnsInMappingJDO.TABLE_NAME); entity.setProperty(HasTableAndColumnsInMappingJDO.FOO_COLUMN_NAME, "foo val"); Key key = ds.put(entity); String keyStr = KeyFactory.keyToString(key); beginTxn(); HasTableAndColumnsInMappingJDO htacim = pm.getObjectById(HasTableAndColumnsInMappingJDO.class, keyStr); assertNotNull(htacim); assertEquals(Long.valueOf(key.getId()), htacim.getId()); assertEquals("foo val", htacim.getFoo()); commitTxn(); }
public String toString() { StringBuilder b = new StringBuilder(); Key k = KeyFactory.stringToKey(key); b.append("Question (").append(k.getId()).append(") : ").append(" Text=").append(questionText); b.append(" Date Posted=").append(datePosted); b.append(" ParentInfo = ").append(k.getParent().toString()); b.append("\n"); for (Comment c : comments) { b.append("\t\t").append(c.toString()).append("\n"); } return b.toString(); }
/** * Sets the currently selected row by key of its {@link UserItem}. * * @param key key of {@link UserItem} * @param forceExpand whether the selected row shall be expanded */ public void setSelectedKey(Key key, boolean forceExpand) { if (key == null) { RowWidget old = rows.get(selected); old.collapse(); old.removeStyleDependentName("selected"); selected = null; SelectionChangeEvent.fire(this); } else if (key.equals(selected)) { // was selected and is selected } else { boolean expand = true; // selected changed if (selected != null) { RowWidget old = rows.get(selected); old.removeStyleDependentName("selected"); if (old.isExpanded()) { old.collapse(); } else { expand = false; } } RowWidget newly = rows.get(key); if (expand || forceExpand) { newly.expand(); } selected = key; newly.addStyleDependentName("selected"); SelectionChangeEvent.fire(this); } }
public Long getId() { if (id != null) { return id.getId(); } else { return 0L; } }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); return result; }
/** * Keyを文字列に変換する. ※no-id-yetキー対応で例外時はそのままでは保存できないが表示用の文字列を返す。 * * @param key * @return */ private static String keyToString(Key key) { if (key == null) return null; try { return KeyFactory.keyToString(key); } catch (Exception e) { return key.toString(); } }
@Override public int compareTo(MemoStorable other) { if (myKey != null && other.myKey != null && myKey.equals(other.myKey)) { return 0; } if (this.storeTime == other.storeTime) { return (int) ((this.nanoTime - other.nanoTime) % Integer.MAX_VALUE); } return (int) ((this.storeTime - other.storeTime) % Integer.MAX_VALUE); }
@Override public void deleteConference(long conferenceId) { try { Conference c = em.find(Conference.class, conferenceId); em.getTransaction().begin(); // first remove related relation ... for (Key Skey : c.getStakeholders()) { Stakeholder s = em.find(Stakeholder.class, Skey.getId()); s.getConferences().remove(c.getId()); em.persist(s); } // then remove the entity em.remove(c); em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { em.close(); } }
@Override public boolean equals(Object o) { if (o instanceof MemoStorable) { MemoStorable other = (MemoStorable) o; if (myKey != null && other.myKey != null && myKey.equals(other.myKey)) { return true; } if ((myKey == null || other.myKey == null) && this.storeTime == other.storeTime) { return (this.nanoTime == other.nanoTime); } } return false; }
@Test public void testMarshall_Child() { RootEntity rootObject = new RootEntity(); // one entity ChildEntity childObject = new ChildEntity("Test City"); rootObject.setId("TestUser"); rootObject.setCount(25); childObject.setParent(rootObject); rootObject.setNewChildEntity(childObject); // one entity IdentityHashMap<Object, Entity> stack = testMarshaller.marshall(null, rootObject); Entity rootObjectEntity = stack.get(rootObject); Entity childObjectEntity = stack.get(childObject); Key childKey = (Key) rootObjectEntity.getProperty("newChildEntity"); Key parentKey = childKey.getParent(); assertEquals(2, stack.size()); assertNotNull(parentKey); assertTrue(childKey instanceof Key); assertEquals(rootObjectEntity.getKey().getId(), parentKey.getId()); assertEquals(rootObjectEntity.getKey().getName(), parentKey.getName()); }
private Entity createEntityCopy(Entity entity) { Key key = entity.getKey(); NamespaceManager.set(key.getNamespace()); Key newKey; if (key.getId() == 0) { newKey = KeyFactory.createKey(key.getKind(), key.getName()); } else { newKey = KeyFactory.createKey(key.getKind(), key.getId()); } Entity newEntity = new Entity(newKey); newEntity.setPropertiesFrom(entity); return newEntity; }
public static Note createNewNote( Key tactKey, NoteValue noteValue, Long orderNumber, Accidental accid, NotePitch pitch) { Entity note = new Entity(Note.KIND); if (tactKey != null) { note.setProperty(Note.TACT_ID, tactKey.getId()); } note.setProperty(NUMBER, orderNumber); note.setUnindexedProperty(Note.VALUE, noteValue.toString()); note.setUnindexedProperty(Note.PITCH, pitch.toString()); note.setUnindexedProperty(Note.DYNAMIC, Dynamic.f.toString()); note.setUnindexedProperty(Note.ACCIDENTAL, accid.toString()); note.setUnindexedProperty(Note.TRIOLA, false); note.setUnindexedProperty(Note.WITH_DOT, false); note.setUnindexedProperty(Note.AKCENT, false); note.setUnindexedProperty(TO_REMOVE, false); DataStoreWrapper.save(note); return new Note(note); }
public void delete(Key key) { if (deletedCache.getIfPresent(key) != null) return; if (myKey.equals(key)) { deletedCache.put(key, this); } try { Entity ent = datastore.get(key); if (ent.hasProperty("next")) { delete((Key) ent.getProperty("next")); // recurse } datastore.delete(key); try { datastore.get(myKey); } catch (EntityNotFoundException e) { } } catch (Exception e) { // e.printStackTrace(); } }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TechnicalInfo other = (TechnicalInfo) obj; if (key == null) { if (other.key != null) { return false; } } else if (!key.equals(other.key)) { return false; } return true; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } AnswerSessionModel other = (AnswerSessionModel) obj; if (key == null) { if (other.key != null) { return false; } } else if (!key.equals(other.key)) { return false; } return true; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Attendance other = (Attendance) obj; if (key == null) { if (other.key != null) { return false; } } else if (!key.equals(other.key)) { return false; } return true; }
/** * Test that an entity in the datastore with absent fields loads correctly, when the fields in the * entity class have default values */ @Test public void testNewVersionOfEntity() throws Exception { fact.register(EntityWithDefault.class); Objectify ofy = fact.begin(); // e1 has absent properties Entity e1 = new Entity("EntityWithDefault"); e1.setProperty("a", "1"); com.google.appengine.api.datastore.Key k1 = ofy.getDatastore().put(e1); EntityWithDefault o = ofy.get(new Key<EntityWithDefault>(EntityWithDefault.class, k1.getId())); assert o.a != null; assert "1".equals(o.a); assert o.b != null; assert "foo".equals(o.b); assert o.c != null; assert "bar".equals(o.c); assert o.s != null; assert "default2".equals(o.s.s); }
public String next() { Key next = wrapped.next().getKey(); return next.getName(); }
public static String makeViewerUrl(Key rootJobKey, Key jobKey) { // TODO(user): BASE_URL could be replaced with ServletContext#getContextPath return BASE_URL + "status.html?root=" + rootJobKey.getName() + "#pipeline-" + jobKey.getName(); }
private String getJobWideUniqueData(Key jobKey) { return getJobWideUniqueData(jobKey.getParent().getId(), jobKey.getId()); }
public static String sendMessage(ServletContext context, String recipient, String message) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String sender = "nobody"; if (user != null) { sender = user.getEmail(); } log.info("sendMessage: sender = " + sender); log.info("sendMessage: recipient = " + recipient); log.info("sendMessage: message = " + message); // ok = we sent to at least one device. boolean ok = false; // Send push message to phone C2DMessaging push = C2DMessaging.get(context); boolean res = false; String collapseKey = "" + message.hashCode(); // delete will fail if the pm is different than the one used to // load the object - we must close the object when we're done List<DeviceInfo> registrations = null; registrations = DeviceInfo.getDeviceInfoForUser(recipient); log.info("sendMessage: got " + registrations.size() + " registrations"); // Deal with upgrades and multi-device: // If user has one device with an old version and few new ones - // the old registration will be deleted. if (registrations.size() > 1) { // Make sure there is no 'bare' registration // Keys are sorted - check the first DeviceInfo first = registrations.get(0); Key oldKey = first.getKey(); if (oldKey.toString().indexOf("#") < 0) { // multiple devices, first is old-style. registrations.remove(0); // don't send to it pm.deletePersistent(first); } } int numSendAttempts = 0; for (DeviceInfo deviceInfo : registrations) { if (!"ac2dm".equals(deviceInfo.getType())) { continue; // user-specified device type } res = doSendViaC2dm(message, sender, push, collapseKey, deviceInfo); numSendAttempts++; if (res) { ok = true; } } if (ok) { return "Success: Message sent"; } else if (numSendAttempts == 0) { return "Failure: User " + recipient + " not registered"; } else { return "Failure: Unable to send message"; } } catch (Exception e) { return "Failure: Got exception " + e; } finally { pm.close(); } }
public String getId() { return Long.toString(key.getId()); }
public T findByKey(final Key key) { return findOne(key.getId()); }
@Override public int hashCode() { return (int) (myKey.hashCode() * this.nanoTime) % Integer.MAX_VALUE; }