@Override public void setMessagesReadden(String userId, String tagId, UserTags tags) { Query<UnreaddenMessage> q = ds.createQuery(UnreaddenMessage.class).field("userId").equal(userId); if (!tagId.equals(UserTags.ALL_TAGS)) { SocioTag tag = tags.getTag(tagId); List<String> tagsIds = new ArrayList<String>(); List<SocioTag> leaves = tag.getLeaves(); for (SocioTag leaf : leaves) { tagsIds.add(leaf.getUniqueId()); } q.field("tagId").hasAnyOf(tagsIds); } List<UnreaddenMessage> unreadMessages = q.asList(); List<GeneralMessage> messages = new ArrayList<GeneralMessage>(); List<ReaddenMessage> readdenMessages = new ArrayList<ReaddenMessage>(); for (UnreaddenMessage unreaddenMessage : unreadMessages) { GeneralMessage message = unreaddenMessage.getMessage(); messages.add(message); ReaddenMessage readdenMessage = new ReaddenMessage(); readdenMessage.setUserId(userId); readdenMessage.setMessageUniqueId(message.getUniqueFieldValue().toString()); readdenMessages.add(readdenMessage); } ds.save(readdenMessages); ds.delete(q); for (GeneralMessage message : messages) { // TODO Next lines are just to save space in unpaid mongoDB on CloudBees Query<UnreaddenMessage> isMore = ds.createQuery(UnreaddenMessage.class).field("message").equal(message); if (isMore.countAll() <= 0) { ds.delete(message); } } }
public <T extends ISocioObject> void saveObject(T object) throws DuplicateMySocioObjectException { if (object instanceof IUniqueObject) { IUniqueObject uniqueObject = (IUniqueObject) object; Cache cache = cm.getCache("Objects"); String key = uniqueObject.getUniqueFieldName() + uniqueObject.getUniqueFieldValue(); Element element = cache.get(key); if (element != null) { ((SocioObject) object).setId((ObjectId) element.getValue()); return; } @SuppressWarnings("unchecked") Query<T> q = (Query<T>) ds.createQuery(object.getClass()) .field(uniqueObject.getUniqueFieldName()) .equal(uniqueObject.getUniqueFieldValue()); T objectT = (T) q.get(); if (objectT != null) { ((SocioObject) object).setId(objectT.getId()); element = new Element(key, objectT.getId()); cache.put(element); logger.info( "Duplicate object of type: " + object.getClass() + " for query: " + q.toString()); throw new DuplicateMySocioObjectException( "Duplicate object of type: " + object.getClass() + " for query: " + q.toString()); } } ds.save(object); }
@Override public List<play.db.Model> fetch( int offset, int size, String orderBy, String order, List<String> searchFields, String keywords, String where) { if (orderBy == null) orderBy = keyName(); if ("DESC".equalsIgnoreCase(order)) orderBy = null == orderBy ? null : "-" + orderBy; Query<? extends Model> q = ds().createQuery(clazz).offset(offset).limit(size); if (null != orderBy) q = q.order(orderBy); if (keywords != null && !keywords.equals("")) { List<Criteria> cl = new ArrayList<Criteria>(); for (String f : fillSearchFieldsIfEmpty_(searchFields)) { cl.add(q.criteria(f).containsIgnoreCase(keywords)); } q.or(cl.toArray(new Criteria[] {})); } processWhere(q, where); List<play.db.Model> l = new ArrayList<play.db.Model>(); l.addAll(q.asList()); return l; }
@Test public void testLoadingOfRefThroughInheritanceInList() throws Exception { // TODO us: exclusion does not work properly with maven + junit4 if (!LazyFeatureDependencies.testDependencyFullFilled()) { return; } morphia.map(ContainerWithRefList.class); morphia.map(OtherEntityChild.class); OtherEntityChild otherEntity = new OtherEntityChild(); ContainerWithRefList containerWithRefInList = new ContainerWithRefList(); ds.save(otherEntity, containerWithRefInList); otherEntity = ds.get(otherEntity); final ContainerWithRefList reload = ds.get(containerWithRefInList); Assert.assertNotNull(otherEntity); Assert.assertNotNull(reload); EmbedWithRef embedWithRef = new EmbedWithRef(); embedWithRef.otherEntity = otherEntity; reload.embedWithRef.add(embedWithRef); ds.save(otherEntity, reload); ds.get(reload); containerWithRefInList = ds.get(reload); Assert.assertNotNull(containerWithRefInList); Query<ContainerWithRefList> createQuery = ds.createQuery(ContainerWithRefList.class); containerWithRefInList = createQuery.get(); Assert.assertNotNull(containerWithRefInList); }
public static List<Quote> findAllSortedByCreationDate(boolean onlyApproved) { Query<Quote> query = DBHolder.ds.find(Quote.class).field("deleted").equal(false); if (onlyApproved) { query = query.field("quoteState").equal(QuoteState.APPROVED); } return query.order("-creationDate").asList(); }
public <T, V> Query<T> find( String kind, Class<T> clazz, String property, V value, int offset, int size) { Query<T> query = find(kind, clazz); query.offset(offset); query.limit(size); return query.filter(property, value); }
@Override public <T extends GeneralMessage> boolean isNewMessage(String userId, T message, Class<T> T) { Cache cache = cm.getCache("Messages"); String key = message.getUniqueFieldValue() + userId; Element element = cache.get(key); if (element != null) { return (Boolean) element.getValue(); } Query<UnreaddenMessage> isUnread = ds.createQuery(UnreaddenMessage.class) .field("userId") .equal(userId) .field("message") .equal(new Key<T>(T, message.getId())); Query<ReaddenMessage> isRead = ds.createQuery(ReaddenMessage.class) .field("userId") .equal(userId) .field("messageUniqueId") .equal(message.getUniqueFieldValue().toString()); Boolean newMessage = isUnread.countAll() <= 0 && isRead.countAll() <= 0; element = new Element(key, new Boolean(false)); cache.put(element); return newMessage; }
public Player getPlayer(String username) { Query<Player> query = ds.createQuery(Player.class).field("userName").equal(username); List<Player> results = query.asList(); if (results.isEmpty()) { return null; } return results.get(0); }
public User findByTwitterName(String twitterName) { Query<User> findQuery = ds.createQuery(User.class).field("twitterName").equal(twitterName); if (null == findQuery || findQuery.asList().isEmpty()) { return null; } else { return findQuery.asList().iterator().next(); } }
public EssayCount findByUser(String user) throws Exception { try { Query q = ds.createQuery(EssayCount.class).field("user").equal(user); EssayCount app = (EssayCount) q.get(); return app; } catch (Exception e) { throw e; } }
public List<EssayCount> findAll() throws Exception { try { Query q = ds.createQuery(EssayCount.class).order("-count"); List<EssayCount> list = q.asList(); return list; } catch (Exception e) { throw e; } }
public <T extends ISocioObject> List<T> getObjects(Class<T> T) { Query<T> q = (Query<T>) ds.createQuery(T); Iterable<T> objects = q.fetch(); ArrayList<T> ret = new ArrayList<T>(); for (T object : objects) { ret.add(object); } return ret; }
public static void init(String name) { Datastore ds = MorphiaPlugin.ds(); Query<Seq> q = ds.find(Seq.class, "_id", name); if (0 == q.countAll()) { Seq newId = new Seq(name); ds.save(newId); } return; }
@Test public void testQueryOverLazyReference() throws Exception { final ContainsPic cpk = new ContainsPic(); final Pic p = new Pic(); ds.save(p); cpk.lazyPic = p; ds.save(cpk); final Query<ContainsPic> query = ds.createQuery(ContainsPic.class); Assert.assertNotNull(query.field("lazyPic").equal(p).get()); }
public String getPage(String userId, String pageKey) { Query<UserPage> q = ds.createQuery(UserPage.class) .field("userId") .equal(userId) .field("pageKey") .equal(pageKey); UserPage userPage = q.get(); if (userPage == null) { return null; } return userPage.getPageHTML(); }
public <T> UpdateResults<T> update(T ent, UpdateOperations<T> ops) { MappedClass mc = mapr.getMappedClass(ent); Query<T> q = (Query<T>) createQuery(mc.getClazz()); q.disableValidation().filter(Mapper.ID_KEY, getId(ent)); if (mc.getFieldsAnnotatedWith(Version.class).size() > 0) { MappedField versionMF = mc.getFieldsAnnotatedWith(Version.class).get(0); Long oldVer = (Long) versionMF.getFieldValue(ent); q.filter(versionMF.getNameToStore(), oldVer); ops.set(versionMF.getNameToStore(), VersionHelper.nextValue(oldVer)); } return update(q, ops); }
public Boolean update(EssayCount count) throws Exception { try { Query q = ds.createQuery(EssayCount.class).field("_id").equal(count.getId()); EssayCount app = (EssayCount) q.get(); if (app != null) { ds.save(count); return true; } else { return false; } } catch (Exception e) { throw e; } }
@SuppressWarnings("rawtypes") private <T> UpdateResults<T> update( Query<T> query, UpdateOperations ops, boolean createIfMissing, boolean multi, WriteConcern wc) { DBObject u = ((UpdateOpsImpl) ops).getOps(); if (((UpdateOpsImpl) ops).isIsolated()) { Query<T> q = query.clone(); q.disableValidation().filter("$atomic", true); return update(q, u, createIfMissing, multi, wc); } return update(query, u, createIfMissing, multi, wc); }
@Override public Long count(List<String> searchFields, String keywords, String where) { Query<?> q = ds().createQuery(clazz); if (keywords != null && !keywords.equals("")) { List<Criteria> cl = new ArrayList<Criteria>(); for (String f : fillSearchFieldsIfEmpty_(searchFields)) { cl.add(q.criteria(f).contains(keywords)); } q.or(cl.toArray(new Criteria[] {})); } processWhere(q, where); return q.countAll(); }
@Override public <T extends GeneralMessage> List<T> getMessagesAfterDate( Class<T> T, Long date, String sourceField, String sourceId) { Query<T> q = (Query<T>) ds.createQuery(T) .field("date") .greaterThanOrEq(date) .field(sourceField) .equal(sourceId); Iterable<T> messages = q.fetch(); ArrayList<T> ret = new ArrayList<T>(); for (T message : messages) { ret.add(message); } return ret; }
@Override public void saveOrUpdate(User user) { Query<User> q = createQuery().filter("uid", user.getUid()); User pUser = q.get(); if (pUser == null) save(user); else { UpdateOperations<User> uo = createUpdateOperations(); uo.set("screenName", user.getScreenName()); uo.set("name", user.getName()); uo.set("profileImageUrl", user.getProfileImageUrl()); uo.set("followersSize", user.getFollowersSize()); uo.set("tweetsSize", user.getTweetsSize()); uo.set("detail", user.getDetail()); update(q, uo); user.setId(pUser.getId()); } }
public void plusOne(String user) throws Exception { try { Query q = ds.createQuery(EssayCount.class).field("user").equal(user); EssayCount ec = (EssayCount) q.get(); if (ec == null) { ec = new EssayCount(); ec.setCount(1); ec.setLastRate(new Date()); ec.setUser(user); ds.save(ec); } else { ec.setCount(ec.getCount() + 1); ec.setLastRate(new Date()); ds.save(ec); } } catch (Exception e) { throw e; } }
public List<User> findWithLimitAndOffset(int limit, int offset, String sortField) { Query<User> findQuery = ds.createQuery(User.class); if (limit > 0) { findQuery = findQuery.limit(limit); } if (offset > 0) { findQuery = findQuery.offset(offset); } if (null != sortField) { findQuery = findQuery.order(sortField); } if (null == findQuery) { return null; } List<User> users = findQuery.asList(); return (users.isEmpty()) ? null : users; }
public List<GeneralMessage> getUnreadMessages(String userId, String tagId, UserTags tags) { Query<UnreaddenMessage> q = ds.createQuery(UnreaddenMessage.class).field("userId").equal(userId.toString()); String order = tags.getOrder(); if (!tagId.equals(UserTags.ALL_TAGS)) { SocioTag tag = tags.getTag(tagId); order = tag.getOrder(); List<String> tagsIds = new ArrayList<String>(); List<SocioTag> leaves = tag.getLeaves(); for (SocioTag leaf : leaves) { tagsIds.add(leaf.getUniqueId()); } q.field("tagId").hasAnyOf(tagsIds); } if (order.equals(SocioTag.ASCENDING_ORDER)) { q.order("-messageDate"); } else { q.order("messageDate"); } q.limit(tags.getRange()); List<GeneralMessage> messagesList = new ArrayList<GeneralMessage>(); Iterable<UnreaddenMessage> messages = q.fetch(); for (UnreaddenMessage unreaddenMessage : messages) { messagesList.add(unreaddenMessage.getMessage()); } tags.setSelectedTag(tagId); ds.save(tags); return messagesList; }
@Override public void setMessageReadden(String userId, String messageId) { Query<UnreaddenMessage> q = ds.createQuery(UnreaddenMessage.class) .field("message") .equal(new Key<GeneralMessage>(GeneralMessage.class, new ObjectId(messageId))) .field("userId") .equal(userId); ds.delete(q); ReaddenMessage readdenMessage = new ReaddenMessage(); readdenMessage.setUserId(userId); readdenMessage.setMessageUniqueId( ds.get(GeneralMessage.class, new ObjectId(messageId)).getUniqueFieldValue().toString()); ds.save(readdenMessage); // TODO Next lines are just to save space in unpaid mongoDB on CloudBees Query<UnreaddenMessage> isMore = ds.createQuery(UnreaddenMessage.class) .field("message") .equal(new Key<GeneralMessage>(GeneralMessage.class, new ObjectId(messageId))); if (isMore.countAll() <= 0) { ds.delete(GeneralMessage.class, new ObjectId(messageId)); } }
@Override public <T extends AbstractUserMessagesProcessor> void saveProcessor( T processor, String uniqueFieldName, String uniqueFieldValue) throws DuplicateMySocioObjectException { @SuppressWarnings("unchecked") Query<T> q = (Query<T>) processorsDs .createQuery(processor.getClass()) .field(uniqueFieldName) .equal(uniqueFieldValue); String userId = processor.getUserId(); if (userId != null) { q.field("userId").equal(userId); } AbstractUserMessagesProcessor existingProcessor = q.get(); if (existingProcessor != null) { processor.setId(existingProcessor.getId()); logger.info("Duplicate processor for query: " + q.toString()); throw new DuplicateMySocioObjectException("Duplicate processor for query: " + q.toString()); } processorsDs.save(processor); }
/** * @param account * @param user * @throws Exception */ public void addAccountToUser(Account account, String userId, UserTags userTags) throws Exception { Query<UserAccount> q = ds.createQuery(UserAccount.class).field("account").equal(account); if (q.get() != null) { logger.debug( "Attempt was made to add existing account of type " + account.getAccountType() + " to user " + userId); return; } SocioUser user = getObject(SocioUser.class, userId); account.setUser(user); saveObject(account); UserAccount userAccount = new UserAccount(); userAccount.setUserId(userId); userAccount.setAccount(account); saveObject(userAccount); account.createAccountTagset(userTags); saveObject(userTags); for (Source source : account.getSources()) { addSourceToUser(userId, source); } }
public static List<Quote> findAllSortedByVoteFilteredByAuthor(String author, QuoteState state) { Query<Quote> query = DBHolder.ds.find(Quote.class).field("deleted").equal(false); query = query.field("quoteState").equal(state); return query.filter("author", author).order("-voteCount").asList(); }
public static List<Quote> findAllSortedByVote(QuoteState state) { Query<Quote> query = DBHolder.ds.find(Quote.class).field("deleted").equal(false); query = query.field("quoteState").equal(state); return query.order("-voteCount").asList(); }
@Override public Source getSource(String url) { Query<Source> q = ds.createQuery(Source.class).field("url").equal(url); return q.get(); }