private void parserDBObject(BasicBSONObject ob,String akey, String aop,Object aval){ boolean isok=false; if (!(ob.keySet().isEmpty())) { for (String field : ob.keySet()) { if (akey.equals(field)){ Object val = ob.get(field); if (val instanceof BasicBSONObject) { ((BasicBSONObject) val).put(aop, aval); ob.put(field, (BasicBSONObject) val); isok=true; break; } else if (val instanceof BasicBSONList) { // newobj.put(field, ((BasicDBList)val).copy()); } } } } if (isok==false) { BasicBSONObject xo = new BasicBSONObject(); xo.put(aop, aval); ob.put(akey,xo); } }
private DBObject capabilitiesToObject(RobotCapabilities capabilities) { if (capabilities == null) { return null; } BasicDBObject capabilitiesObj = new BasicDBObject(); for (Capability capability : capabilities.getCapabilitiesMap().values()) { BasicBSONList contexts = new BasicBSONList(); for (Context c : capability.getContexts()) { contexts.add(c.name()); } capabilitiesObj.put(capability.getEventType().name(), new BasicDBObject() .append(CAPABILITY_CONTEXTS_FIELD, contexts) .append(CAPABILITY_FILTER_FIELD, capability.getFilter())); } BasicDBObject object = new BasicDBObject() .append(CAPABILITIES_CAPABILITIES_FIELD, capabilitiesObj) .append(CAPABILITIES_HASH_FIELD, capabilities.getCapabilitiesHash()) .append(CAPABILITIES_VERSION_FIELD, capabilities.getProtocolVersion().name()); return object; }
private static BSONObject translateLogicalOperationPredicate(LogicalOperationPredicate predicate) { final BasicBSONList opList = new BasicBSONList(); opList.add(translatePredicate(predicate.getLeft())); opList.add(translatePredicate(predicate.getRight())); final String op; if(predicate.getOperator().equals(LogicalOperationPredicate.Operator.AND)) op = "$and"; else if(predicate.getOperator().equals(LogicalOperationPredicate.Operator.OR)) op = "$or"; else throw new EvaluationException("Unexpected operator: " + predicate.getOperator()); return new BasicBSONObject(op, opList); }
@Test public void testGetValues() { // root.body.profile.name.first = George BSONObject root = new BasicBSONObject(); BSONObject body = new BasicBSONObject(); BasicBSONList list = new BasicBSONList(); list.add("hello"); list.add("goodbye"); list.add("have a nice day"); body.put("body", list); root.put("root", body); String[] values = BSONUtilities.getValues(root, "root.body"); assertNotNull(values); assertEquals(values.length, 3); }
/** * convert bson types to java primitives. BasicBSONList, Binary, * BSONTimestamp, Code, CodeWScope, MinKey, MaxKey, Symbol, ObjectId */ private Object convert(Object o) { if (o instanceof BSONTimestamp) { return ((BSONTimestamp) o).getTime(); } else if (o instanceof Symbol || o instanceof Code || o instanceof CodeWScope || o instanceof MinKey || o instanceof MaxKey || o instanceof ObjectId) { return o.toString(); } else if (o instanceof BasicBSONList) { List<Object> l = new ArrayList<Object>(); for (Object item : ((BasicBSONList) o)) { l.add(convert(item)); } return l; } else { return o; } }
@Override public Object call(BasicBSONObject bsonResponse) { if(bsonResponse.getString(ServerHelper.RESQUEST_TAG) == ServerHelper.GET_TRANSACTION_TAG){ //Log.i("ADAPTER", "getting result : "+bsonResponse.get(ServerHelper.SERVER_TRANSACTIONS_KEY).toString()); BasicBSONList bsonList = (BasicBSONList) bsonResponse.get(ServerHelper.SERVER_TRANSACTIONS_KEY); this.items.clear(); for(int i = 0; i < bsonList.size(); i++){ BasicBSONObject bsonData = (BasicBSONObject) bsonList.get(i); if(!bsonData.getString(ServerHelper.SERVER_SENDER_KEY).equals(ServerHelper.SYSTEM_USER_TAG)){ int transactionAmount = Integer.parseInt(bsonData.getString(ServerHelper.SERVER_TRANSACTION_AMOUNT_KEY)); Transaction tmpTransaction = new Transaction( bsonData.getString(ServerHelper.SERVER_ID_KEY), bsonData.getString(ServerHelper.SERVER_RECEIVER_KEY), bsonData.getString(ServerHelper.SERVER_SENDER_KEY), transactionAmount); this.add(tmpTransaction); } } } //Log.i("TransactionListAdapter", this.items.toString()); this.notifyDataSetChanged(); return null; }
public BasicBSONList getGrouyBys() { if (this.groupby instanceof BasicBSONList) { return (BasicBSONList)this.groupby; } else { return null; } }
public void setGrouyBy(BSONObject gb) { this.groupby=gb; this.type=true; if (gb instanceof BasicBSONList) { Object gb2=((BasicBSONList)gb).get(0); if (gb2 instanceof BSONObject) { for (String field :((BSONObject)gb2).keySet()) { Object val = ((BSONObject)gb2).get(field); setField(field,getObjectToType(val)); } } } }
/** * or规则 第一个参数为值 * * @param value * @param keys * @return */ public BSONObjectBuilder addOrRule(Object value, String... keys) { BasicBSONList bsonList = new BasicBSONList(); for (String key : keys) { BSONObject arg = new BasicBSONObject(); arg.put(key, value); bsonList.add(arg); } bson.put(MatchConst._OR, bsonList); return this; }
public List<BSONObject> search(String[] args, String value, BSONObject selector) { BSONObject matcher = new BasicBSONObject(); BasicBSONList bsonList = new BasicBSONList(); for (String key : args) { BSONObject arg = new BasicBSONObject(); // BSONObject regex = new BasicBSONObject(); // regex.put(MatchConst._REGEX,value); arg.put(key, value); bsonList.add(arg); } matcher.put(MatchConst._OR, bsonList); return query(matcher, selector, null); }
/** * @param keywords * @param field * @param selector * @param order * @return */ protected List<BSONObject> search(String keywords, String field, String[] selector, BSONObject order, boolean isMatchStrict) { int length = selector.length; BSONObject selectorBson = new BasicBSONObject(); for (int i = 0; i < length; i++) { selectorBson.put(selector[i], selector[i]); } if (keywords != null && !keywords.isEmpty()) { BSONObject matcherOne = new BasicBSONObject(); BasicBSONList arr = new BasicBSONList(); BSONObject parmasOne = new BasicBSONObject(); matcherOne.put(MatchConst._REGEX, keywords); matcherOne.put(MatchConst._OPTIONS, "i"); parmasOne.put("pinyin", matcherOne); arr.add(parmasOne); BSONObject parmasTwo = new BasicBSONObject(); BSONObject matcherTwo = new BasicBSONObject(); matcherTwo.put(MatchConst._REGEX, keywords); if (!isMatchStrict) { parmasTwo.put(field, matcherTwo); } else { parmasTwo.put(field, keywords); } arr.add(parmasTwo); BSONObject query = new BasicBSONObject(); query.put(MatchConst._OR, arr); List<BSONObject> record = query(query, null, order); return record; } return null; }
private <A extends Object> void loadObject(A object, DBObject document) throws IllegalAccessException, IllegalArgumentException, SecurityException, InstantiationException { Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String fieldName = field.getName(); Object fieldContent = document.get(fieldName); if (fieldContent instanceof BasicBSONList) { Class<?> fieldArgClass = null; ParameterizedType genericFieldType = (ParameterizedType) field.getGenericType(); Type[] fieldArgTypes = genericFieldType.getActualTypeArguments(); for (Type fieldArgType : fieldArgTypes) { fieldArgClass = (Class<?>) fieldArgType; } List<Object> list = new ArrayList<>(); boolean isInternal = field.isAnnotationPresent(Internal.class); for (Object item : (BasicBSONList) fieldContent) { if (isInternal) { Object o = fieldArgClass.newInstance(); loadObject(o, (DBObject) item); list.add(o); } else { list.add(item); } } field.set(object, list); } else if ((fieldContent != null) && field.getType().isEnum()) { field.set(object, Enum.valueOf((Class) field.getType(), (String) fieldContent)); } else if ((fieldContent != null) && field.isAnnotationPresent(Reference.class)) { field.set(object, findById(field.getType(), ((org.bson.types.ObjectId) fieldContent).toString())); } else if (field.isAnnotationPresent(ObjectId.class)) { field.set(object, ((org.bson.types.ObjectId) document.get("_id")).toString()); } else if (field.getType().isPrimitive() && (fieldContent == null)) { } else if (fieldContent != null) { field.set(object, fieldContent); } } }
@SuppressWarnings("unchecked") private static Object canonicalize(final Object from) { if (from instanceof BSONObject && !(from instanceof BasicBSONList)) { return canonicalizeBSONObject((BSONObject) from); } else if (from instanceof List) { return canonicalizeList((List<Object>) from); } else if (from instanceof Map) { return canonicalizeMap((Map<String, Object>) from); } else { return from; } }
private void updateMention(BasicDBObject entity, BasicDBObject update, String mentionId) { // String mentionType = ViewerType.MENTIONER.name(); BasicBSONList viewTypes = (BasicBSONList) entity.get(StreamItemMongoEntity.viewerTypes.getName()); int actionNum = 1; if (viewTypes == null || viewTypes.size() == 0) { // update = StreamViewType.MENTIONER.append(update); update.append(StreamItemMongoEntity.viewerId.getName(), mentionId); } else { // String[] arrViewTypes = viewTypes.toArray(new String[0]); BasicDBObject actionNo = (BasicDBObject) entity.get(StreamItemMongoEntity.actionNo.getName()); if (ArrayUtils.contains(arrViewTypes, mentionType)) { //increase number by 1 actionNum = actionNo.getInt(mentionType) + 1; } else { //add new type MENTIONER update.append(StreamItemMongoEntity.viewerTypes.getName(), ArrayUtils.add(arrViewTypes, mentionType)); } //update actionNo actionNo.append(mentionType, actionNum); update.append(StreamItemMongoEntity.actionNo.getName(), actionNo); } }
protected void _saveActivity(ExoSocialActivity activity) { // DBCollection activityCol = CollectionName.ACTIVITY_COLLECTION.getCollection(this.abstractMongoStorage); BasicDBObject query = new BasicDBObject(); query.append(ActivityMongoEntity.id.getName(), new ObjectId(activity.getId())); BasicDBObject activityEntity = (BasicDBObject) activityCol.findOne(query); String[] orginLikers = ((BasicBSONList) activityEntity.get(ActivityMongoEntity.likers.getName())).toArray(new String[0]); long currentMillis = System.currentTimeMillis(); activity.setUpdated(currentMillis); BasicDBObject update = new BasicDBObject(); fillActivityEntityFromActivity(null, activity, update, false); WriteResult result = activityCol.update(query, new BasicDBObject("$set", update)); LOG.debug("==============>UPDATED ACTIVITY: " + result.toString()); // updateActivityRef(activity.getId(), activity.getUpdated().getTime(), activity.isHidden()); LOG.debug("==============>UPDATED ACTIVITY REF [ACTIVITY_ID]: " + activity.getId()); // String[] removedLikes = StorageUtils.sub(orginLikers, activity.getLikeIdentityIds()); String[] addedLikes = StorageUtils.sub(activity.getLikeIdentityIds(), orginLikers); if (removedLikes.length > 0 || addedLikes.length > 0) { manageActivityLikes(addedLikes, removedLikes, activity); } }
private void like(ExoSocialActivity activity, String userId) throws ActivityStorageException { // DBCollection streamCol = CollectionName.STREAM_ITEM_COLLECTION.getCollection(this.abstractMongoStorage); BasicDBObject query = new BasicDBObject(StreamItemMongoEntity.activityId.getName(), activity.getId()); query.append(StreamItemMongoEntity.viewerId.getName(), userId); String likeType = ViewerType.LIKER.name(); Identity poster = new Identity(activity.getPosterId()); poster.setRemoteId(activity.getStreamOwner()); BasicDBObject o = (BasicDBObject) streamCol.findOne(query); if (o == null) { //create new stream item for LIKER o = StreamViewType.LIKER.append(new BasicDBObject()); fillStreamItem(poster, activity, o); o.append(StreamItemMongoEntity.viewerId.getName(), userId); o.append(StreamItemMongoEntity.time.getName(), activity.getUpdated().getTime()); streamCol.insert(o); } else { //update LIKER BasicDBObject update = new BasicDBObject(); BasicBSONList viewTypes = (BasicBSONList) o.get(StreamItemMongoEntity.viewerTypes.getName()); if (ArrayUtils.contains(viewTypes.toArray(new String[0]), likeType)) { update.append(StreamItemMongoEntity.time.getName(), activity.getUpdated().getTime()); } else { update.append(StreamItemMongoEntity.viewerTypes.getName(), ArrayUtils.add(viewTypes.toArray(new String[0]), likeType)); update.append(StreamItemMongoEntity.time.getName(), activity.getUpdated().getTime()); } //do update streamCol.update(new BasicDBObject("_id", new ObjectId(o.getString("_id"))), new BasicDBObject("$set", update)); } }
private void unLike(ExoSocialActivity activity, String userId) throws ActivityStorageException { // DBCollection streamCol = CollectionName.STREAM_ITEM_COLLECTION.getCollection(this.abstractMongoStorage); BasicDBObject query = new BasicDBObject(StreamItemMongoEntity.activityId.getName(), activity.getId()); query.append(StreamItemMongoEntity.viewerId.getName(), userId); String likeType = ViewerType.LIKER.name(); BasicDBObject o = (BasicDBObject) streamCol.findOne(query); if (o != null) { //update LIKER BasicDBObject update = new BasicDBObject(); BasicBSONList viewTypes = (BasicBSONList) o.get(StreamItemMongoEntity.viewerTypes.getName()); String posterId = o.getString(StreamItemMongoEntity.poster.getName()); boolean removeable = userId.equals(posterId) ? false : true ; String[] oldViewTypes = viewTypes.toArray(new String[0]); String[] newViewTypes = (String[]) ArrayUtils.removeElement(oldViewTypes, likeType); // if (newViewTypes.length == 0 && removeable) { streamCol.remove(o); return; } // update.append(StreamItemMongoEntity.viewerTypes.getName(), newViewTypes); //do update streamCol.update(new BasicDBObject("_id", new ObjectId(o.getString("_id"))), new BasicDBObject("$set", update)); } }
/** * Checks the conversion of NeutralQueries (containing ORed criteria) * into Mongo-appropriate Query objects. * * This test uses an example similar to: * * select * * from student * where economicDisadvantaged = true * and studentUniqueStateId = '000000054') * */ @Test public void testOrConvert() { NeutralQuery mainQuery = new NeutralQuery(); //not part of the or, so added to the main query mainQuery.addCriteria(new NeutralCriteria("economicDisadvantaged=true")); //construct a query representing all the criteria in 1 or branch NeutralQuery orQuery1 = new NeutralQuery(); //construct a query representing all the criteria in a second or branch NeutralQuery orQuery2 = new NeutralQuery(); orQuery2.addCriteria(new NeutralCriteria("studentUniqueStateId", "=", "000000054")); //add the or queries mainQuery.addOrQuery(orQuery1); mainQuery.addOrQuery(orQuery2); //the converter will convert the NeutralQuery into a mongo Query Object Query query = mongoQueryConverter.convert("student", mainQuery); assertNotNull("Should not be null", query); DBObject obj = query.getQueryObject(); assertNotNull("Should not be null", obj); assertNotNull("Should not be null", obj.get("$or")); assertTrue(((BasicBSONList) obj.get("$or")).size() == 1); }
protected BSONObject encodeCoordinates(CoordinateSequence coordinates) { BasicBSONList list = new BasicBSONList(); for (int i = 0; i < coordinates.size(); ++i) { BasicBSONList coordinate = new BasicBSONList(); coordinate.add(coordinates.getX(i)); coordinate.add(coordinates.getY(i)); list.add(coordinate); } return list; }
protected BSONObject encodeCoordinates(Polygon geometry) { BasicBSONList list = new BasicBSONList(); list.add(encodeCoordinates(geometry.getExteriorRing())); for (int i = 0; i < geometry.getNumInteriorRing(); ++i) { list.add(encodeCoordinates(geometry.getInteriorRingN(i))); } return list; }
private static BSONObject translateNegatedPredicate(NegatedPredicate predicate) { final BasicBSONList norList = new BasicBSONList(); norList.add(translatePredicate(predicate.getPredicate())); return new BasicBSONObject("$nor", norList); }
private void getDatabaseCredentialsFromEnv() { if (System.getenv().containsKey("VCAP_SERVICES")) { try { BSONObject vcap_services = (BSONObject) JSON.parse(System.getenv("VCAP_SERVICES")); BasicBSONList service = (BasicBSONList) vcap_services.get("timeseriesdatabase"); BSONObject catalog = (BSONObject) service.get(0); BSONObject credentials = (BSONObject) catalog.get("credentials"); this.url = (String) credentials.get("sql_url"); } catch (Exception e) { throw new RuntimeException("Could not parse VCAP_SERVICES", e); } } else { if (System.getenv().containsKey("HOST")) { host = System.getenv("HOST"); } else { throw new RuntimeException("Missing HOST env variable"); } if (System.getenv().containsKey("PORT")) { port = Integer.parseInt(System.getenv("PORT")); } else { throw new RuntimeException("Missing PORT env variable"); } if (System.getenv().containsKey("DATABASE")) { databaseName = System.getenv("DATABASE"); } else { throw new RuntimeException("Missing DATABASE env variable"); } if (System.getenv().containsKey("USER")) { user = System.getenv("USER"); } else { throw new RuntimeException("Missing USER env variable"); } if (System.getenv().containsKey("PASSWORD")) { password = System.getenv("PASSWORD"); } else { throw new RuntimeException("Missing PASSWORD env variable"); } if (System.getenv().containsKey("CONN_PROPERTIES")) { additionalConnectionProperties = System.getenv().get("CONN_PROPERTIES"); } } }
protected BSONObject createList() { return new BasicBSONList(); }
private void fillActivity(ExoSocialActivity activity, BasicDBObject activityEntity) { activity.setId(activityEntity.getString(ActivityMongoEntity.id.getName())); activity.setTitle(activityEntity.getString(ActivityMongoEntity.title.getName())); activity.setTitleId(activityEntity.getString(ActivityMongoEntity.titleId.getName())); activity.setBody(activityEntity.getString(ActivityMongoEntity.body.getName())); activity.setBodyId(activityEntity.getString(ActivityMongoEntity.bodyId.getName())); activity.setPosterId(activityEntity.getString(ActivityMongoEntity.poster.getName())); activity.setUserId(activityEntity.getString(ActivityMongoEntity.poster.getName())); activity.setStreamOwner(activityEntity.getString(ActivityMongoEntity.owner.getName())); activity.setPermanLink(activityEntity.getString(ActivityMongoEntity.permaLink.getName())); BasicBSONList likers = (BasicBSONList) activityEntity.get(ActivityMongoEntity.likers.getName()); activity.setLikeIdentityIds(likers != null ? likers.toArray(new String[0]) : new String[0]); BasicBSONList mentions = (BasicBSONList) activityEntity.get(ActivityMongoEntity.mentioners.getName()); activity.setMentionedIds(mentions != null ? mentions.toArray(new String[0]) : new String[0]); BasicBSONList commenters = (BasicBSONList) activityEntity.get(ActivityMongoEntity.commenters.getName()); activity.setCommentedIds(commenters != null ? commenters.toArray(new String[0]) : new String[0]); activity.isHidden(activityEntity.getBoolean(ActivityMongoEntity.hidable.getName())); activity.isLocked(activityEntity.getBoolean(ActivityMongoEntity.lockable.getName())); activity.setPostedTime(activityEntity.getLong(ActivityMongoEntity.postedTime.getName())); activity.setUpdated(activityEntity.getLong(ActivityMongoEntity.lastUpdated.getName())); activity.setAppId(activityEntity.getString(ActivityMongoEntity.appId.getName())); activity.setExternalId(activityEntity.getString(ActivityMongoEntity.externalId.getName())); activity.setType(activityEntity.getString(ActivityMongoEntity.activity_type.getName())); Map<String, String> params = (Map<String, String>) activityEntity.get(ActivityMongoEntity.params.getName()); activity.setTemplateParams(params); List<String> commentIds = (List<String>) activityEntity.get(ActivityMongoEntity.commentIds.getName()); if (commentIds != null) activity.setReplyToId(commentIds.toArray(new String[]{})); String streamId = activityEntity.getString(ActivityMongoEntity.streamId.getName()); if (streamId != null) { activity.setStreamId(streamId); Identity identity = identityStorage.findIdentityById(streamId); ActivityStream stream = new ActivityStreamImpl(); stream.setPrettyId(identity.getRemoteId()); stream.setType(identity.getProviderId()); stream.setId(identity.getId()); activity.setActivityStream(stream); } }
private void removeMentioner(String activityId, String... mentionIds) { // DBCollection streamCol = CollectionName.STREAM_ITEM_COLLECTION.getCollection(this.abstractMongoStorage); BasicDBObject query = new BasicDBObject(StreamItemMongoEntity.activityId.getName(), activityId); query.append(StreamItemMongoEntity.viewerId.getName(), new BasicDBObject("$in", mentionIds)); DBCursor cur = streamCol.find(query); while (cur.hasNext()) { BasicDBObject it = (BasicDBObject) cur.next(); BasicDBObject update = new BasicDBObject(); //update BasicBSONList viewTypes = (BasicBSONList) it.get(StreamItemMongoEntity.viewerTypes.getName()); if (viewTypes != null) { String mentionType = ViewerType.MENTIONER.name(); String posterId = it.getString(StreamItemMongoEntity.poster.getName()); //if MENTIONER is Poster, don't remove stream item boolean removeable = ArrayUtils.contains(mentionIds, posterId) ? false : true; // String[] oldViewTypes = viewTypes.toArray(new String[0]); if (oldViewTypes.length == 0) continue; BasicDBObject actionNo = (BasicDBObject) it.get(StreamItemMongoEntity.actionNo.getName()); if (actionNo.containsField(mentionType)) { int number = actionNo.getInt(mentionType) - 1; if (number == 0) { //remove Mentioner String[] newViewTypes = (String[]) ArrayUtils.removeElement(oldViewTypes, ViewerType.MENTIONER.name()); if (newViewTypes.length == 0 && removeable) { // streamCol.remove(it); continue; } // actionNo.remove(mentionType); update.append(StreamItemMongoEntity.viewerTypes.getName(), newViewTypes); } else { actionNo.append(mentionType, number); } //{ "actionNo" : {mentioner -> number} } update.append(StreamItemMongoEntity.actionNo.getName(), actionNo); streamCol.update(new BasicDBObject("_id", new ObjectId(it.getString("_id"))), new BasicDBObject("$set", update)); } } } }
/** Handle an operand */ private static Operand handleOperand( String sourceField, BSONObject exp ) { Operand current = null; Object value = null; for ( String field : exp.keySet() ) { if ( field.startsWith( "$" ) ) { if ( "$gt".equals( field ) ) { value = exp.get( field ); GreaterThan gt = new GreaterThan(); gt.setProperty( sourceField ); gt.setLiteral( value ); current = gt; } else if ( "$gte".equals( field ) ) { value = exp.get( field ); GreaterThanEqual gte = new GreaterThanEqual(); gte.setProperty( sourceField ); gte.setLiteral( exp.get( field ) ); current = gte; // http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%3C%2C%3C%3D%2C%3E%2C%3E%3D // greater than equals // { "field" : { $gte: value } } } else if ( "$lt".equals( field ) ) { value = exp.get( field ); LessThan lt = new LessThan(); lt.setProperty( sourceField ); lt.setLiteral( value ); current = lt; } else if ( "$lte".equals( field ) ) { value = exp.get( field ); LessThanEqual lte = new LessThanEqual(); lte.setProperty( sourceField ); lte.setLiteral( value ); current = lte; } else if ( "$in".equals( field ) ) { value = exp.get( field ); BasicBSONList values = ( BasicBSONList ) value; int size = values.size(); Stack<Operand> expressions = new Stack<Operand>(); for (Object value1 : values) { Equal equal = new Equal(); equal.setProperty(sourceField); equal.setLiteral(value1); expressions.push(equal); } // we need to build a tree of expressions while ( expressions.size() > 1 ) { OrOperand or = new OrOperand(); or.addChild( expressions.pop() ); or.addChild( expressions.pop() ); expressions.push( or ); } current = expressions.pop(); } } } return current; }
@Test public void in() throws Exception { UUID appId = emf.lookupApplication( "test-organization/test-app" ); EntityManager em = emf.getEntityManager( appId ); Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put( "name", "Kings of Leon" ); properties.put( "genre", "Southern Rock" ); properties.put( "founded", 2000 ); em.create( "testin", properties ); properties = new LinkedHashMap<String, Object>(); properties.put( "name", "Stone Temple Pilots" ); properties.put( "genre", "Rock" ); properties.put( "founded", 1986 ); em.create( "testin", properties ); properties = new LinkedHashMap<String, Object>(); properties.put( "name", "Journey" ); properties.put( "genre", "Classic Rock" ); properties.put( "founded", 1973 ); em.create( "testin", properties ); // See http://www.mongodb.org/display/DOCS/Java+Tutorial Mongo m = new Mongo( "localhost", 27017 ); DB db = m.getDB( "test-organization/test-app" ); db.authenticate( "test", "test".toCharArray() ); BasicBSONList list = new BasicBSONList(); list.add( "Stone Temple Pilots" ); list.add( "Journey" ); BasicDBObject query = new BasicDBObject(); query.put( "name", new BasicDBObject( "$in", list ) ); DBCollection coll = db.getCollection( "testins" ); DBCursor cur = coll.find( query ); assertTrue( cur.hasNext() ); DBObject result = cur.next(); assertEquals( "Journey", result.get( "name" ) ); assertEquals( "Classic Rock", result.get( "genre" ) ); result = cur.next(); assertEquals( "Stone Temple Pilots", result.get( "name" ) ); assertEquals( "Rock", result.get( "genre" ) ); assertFalse( cur.hasNext() ); }
@Test public void or() throws Exception { UUID appId = emf.lookupApplication( "test-organization/test-app" ); EntityManager em = emf.getEntityManager( appId ); Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put( "name", "Kings of Leon" ); properties.put( "genre", "Southern Rock" ); properties.put( "founded", 2000 ); em.create( "testor", properties ); properties = new LinkedHashMap<String, Object>(); properties.put( "name", "Stone Temple Pilots" ); properties.put( "genre", "Rock" ); properties.put( "founded", 1986 ); em.create( "testor", properties ); properties = new LinkedHashMap<String, Object>(); properties.put( "name", "Journey" ); properties.put( "genre", "Classic Rock" ); properties.put( "founded", 1973 ); em.create( "testor", properties ); // See http://www.mongodb.org/display/DOCS/Java+Tutorial Mongo m = new Mongo( "localhost", 27017 ); DB db = m.getDB( "test-organization/test-app" ); db.authenticate( "test", "test".toCharArray() ); BasicBSONList list = new BasicBSONList(); list.add( new BasicDBObject( "founded", new BasicDBObject( "$gte", 2000 ) ) ); list.add( new BasicDBObject( "founded", new BasicDBObject( "$lte", 1973 ) ) ); BasicDBObject query = new BasicDBObject(); query.put( "$or", list ); DBCollection coll = db.getCollection( "testors" ); DBCursor cur = coll.find( query ); assertTrue( cur.hasNext() ); DBObject result = cur.next(); assertEquals( "Journey", result.get( "name" ) ); assertEquals( "Classic Rock", result.get( "genre" ) ); result = cur.next(); assertEquals( "Kings of Leon", result.get( "name" ) ); assertEquals( "Southern Rock", result.get( "genre" ) ); assertFalse( cur.hasNext() ); }
@Test public void and() throws Exception { UUID appId = emf.lookupApplication( "test-organization/test-app" ); EntityManager em = emf.getEntityManager( appId ); Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put( "name", "Kings of Leon" ); properties.put( "genre", "Southern Rock" ); properties.put( "founded", 2000 ); em.create( "testand", properties ); properties = new LinkedHashMap<String, Object>(); properties.put( "name", "Stone Temple Pilots" ); properties.put( "genre", "Rock" ); properties.put( "founded", 1986 ); em.create( "testand", properties ); properties = new LinkedHashMap<String, Object>(); properties.put( "name", "Journey" ); properties.put( "genre", "Classic Rock" ); properties.put( "founded", 1973 ); em.create( "testand", properties ); // See http://www.mongodb.org/display/DOCS/Java+Tutorial Mongo m = new Mongo( "localhost", 27017 ); DB db = m.getDB( "test-organization/test-app" ); db.authenticate( "test", "test".toCharArray() ); BasicBSONList list = new BasicBSONList(); list.add( new BasicDBObject( "founded", new BasicDBObject( "$gte", 2000 ) ) ); list.add( new BasicDBObject( "founded", new BasicDBObject( "$lte", 2005 ) ) ); BasicDBObject query = new BasicDBObject(); query.put( "$and", list ); DBCollection coll = db.getCollection( "testands" ); DBCursor cur = coll.find( query ); assertTrue( cur.hasNext() ); DBObject result = cur.next(); assertEquals( "Kings of Leon", result.get( "name" ) ); assertEquals( "Southern Rock", result.get( "genre" ) ); assertFalse( cur.hasNext() ); }
protected BSONObject encodeCoordinate(Coordinate coordinate) { BasicBSONList list = new BasicBSONList(); list.add(coordinate.x); list.add(coordinate.y); return list; }