List of usage examples for com.mongodb QueryBuilder start
public static QueryBuilder start(final String key)
From source file:org.apache.sling.mongodb.impl.MongoDBResourceProvider.java
License:Apache License
/** * @see org.apache.sling.api.resource.ModifyingResourceProvider#commit(ResourceResolver) *///from w ww . ja v a2 s.com public void commit(final ResourceResolver resolver) throws PersistenceException { try { for (final String deleted : this.deletedResources) { final String[] info = this.extractResourceInfo(deleted); // check if the collection still exists final DBCollection col = this.getCollection(info[0]); if (col != null) { if (col.findAndRemove(QueryBuilder.start(getPROP_PATH()).is(info[1]).get()) != null) { this.context.notifyRemoved(info); } } } for (final MongoDBResource changed : this.changedResources.values()) { final DBCollection col = this.context.getDatabase().getCollection(changed.getCollection()); if (col != null) { final String[] info = new String[] { changed.getCollection(), changed.getProperties().get(getPROP_PATH()).toString() }; // create or update? if (changed.getProperties().get(PROP_ID) != null) { col.update(QueryBuilder.start(getPROP_PATH()) .is(changed.getProperties().get(getPROP_PATH())).get(), changed.getProperties()); this.context.notifyUpdated(info); } else { // create col.save(changed.getProperties()); this.context.notifyUpdated(info); } } else { throw new PersistenceException("Unable to create collection " + changed.getCollection(), null, changed.getPath(), null); } } } finally { this.revert(resolver); } }
From source file:org.apache.sling.mongodb.impl.MongoDBResourceProvider.java
License:Apache License
/** * TODO - we have to check for deleted and added resources * @see org.apache.sling.api.resource.ResourceProvider#listChildren(org.apache.sling.api.resource.Resource) *///from ww w .j a v a2s . c o m public Iterator<Resource> listChildren(final Resource parent) { final String[] info = this.extractResourceInfo(parent.getPath()); if (info != null) { if (info.length == 0) { // all collections final Set<String> names = new HashSet<String>(context.getDatabase().getCollectionNames()); names.removeAll(this.context.getFilterCollectionNames()); final Iterator<String> i = names.iterator(); return new Iterator<Resource>() { public boolean hasNext() { return i.hasNext(); } public Resource next() { final String name = i.next(); return new MongoDBCollectionResource(parent.getResourceResolver(), parent.getPath() + '/' + name); } public void remove() { throw new UnsupportedOperationException("remove"); } }; } final DBCollection col = this.getCollection(info[0]); if (col != null) { final String pattern; if (info.length == 1) { pattern = "^([^/])*$"; } else { pattern = "^" + Pattern.quote(info[1]) + "/([^/])*$"; } final DBObject query = QueryBuilder.start(getPROP_PATH()).regex(Pattern.compile(pattern)).get(); final DBCursor cur = col.find(query).sort(BasicDBObjectBuilder.start(getPROP_PATH(), 1).get()); return new Iterator<Resource>() { public boolean hasNext() { return cur.hasNext(); } public Resource next() { final DBObject obj = cur.next(); final String objPath = obj.get(getPROP_PATH()).toString(); final int lastSlash = objPath.lastIndexOf('/'); final String name; if (lastSlash == -1) { name = objPath; } else { name = objPath.substring(lastSlash + 1); } return new MongoDBResource(parent.getResourceResolver(), parent.getPath() + '/' + name, info[0], obj, MongoDBResourceProvider.this); } public void remove() { throw new UnsupportedOperationException("remove"); } }; } } return null; }
From source file:org.apache.sling.mongodb.impl.MongoDBResourceProvider.java
License:Apache License
/** * Get a resource// w w w. j av a 2 s . c o m */ protected Resource getResource(final ResourceResolver resourceResolver, final String path, final String[] info) { if (info.length == 0) { // special resource : all collections return new MongoDBCollectionResource(resourceResolver, path); } else if (info.length == 1) { // special resource : collection if (this.hasCollection(info[0])) { return new MongoDBCollectionResource(resourceResolver, path); } return null; } logger.debug("Searching {} in {}", info[1], info[0]); final DBCollection col = this.getCollection(info[0]); if (col != null) { final DBObject obj = col.findOne(QueryBuilder.start(getPROP_PATH()).is(info[1]).get()); logger.debug("Found {}", obj); if (obj != null) { return new MongoDBResource(resourceResolver, path, info[0], obj, this); } } return null; }
From source file:org.einherjer.week2.samples.DotNotationSample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection lines = db.getCollection("dotNotationSample"); lines.drop();/*from www . j a v a2s. c o m*/ Random rand = new Random(); // insert 10 lines with random start and end points for (int i = 0; i < 10; i++) { lines.insert( new BasicDBObject("_id", i) .append("start", new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10)) .append("end", new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10))); } QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50); DBCursor cursor = lines.find(builder.get(), new BasicDBObject("start.y", true).append("_id", false)); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
From source file:org.einherjer.week2.samples.FieldSelectionSample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("fieldSelectionSample"); collection.drop();//w w w . jav a 2 s . c o m Random rand = new Random(); // insert 10 documents with two random integers for (int i = 0; i < 10; i++) { collection.insert(new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(100)).append("z", rand.nextInt(1000))); } DBObject query = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(70).get(); //use second find parameter to filter the returned fields DBCursor cursor = collection.find(query, new BasicDBObject("y", true).append("_id", false)); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
From source file:org.einherjer.week2.samples.FindCriteriaSample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findCriteriaSample"); collection.drop();/*w ww . ja v a 2 s .c om*/ // insert 10 documents with two random integers for (int i = 0; i < 10; i++) { collection .insert(new BasicDBObject("x", new Random().nextInt(2)).append("y", new Random().nextInt(100))); } //1- The query document can be created by using a QueryBuilder... QueryBuilder builder = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(70); //2- or, the query document can be created manually DBObject query = new BasicDBObject("x", 0).append("y", new BasicDBObject("$gt", 10).append("$lt", 90)); System.out.println("\nCount:"); long count = collection.count(builder.get()); System.out.println(count); System.out.println("\nFind all: "); DBCursor cursor = collection.find(builder.get()); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
From source file:org.entcore.blog.events.BlogSearchingEvents.java
License:Open Source License
@Override public void searchResource(List<String> appFilters, String userId, JsonArray groupIds, final JsonArray searchWords, final Integer page, final Integer limit, final JsonArray columnsHeader, final String locale, final Handler<Either<String, JsonArray>> handler) { if (appFilters.contains(BlogSearchingEvents.class.getSimpleName())) { final List<String> groupIdsLst = groupIds.getList(); final List<DBObject> groups = new ArrayList<DBObject>(); groups.add(QueryBuilder.start("userId").is(userId).get()); for (String gpId : groupIdsLst) { groups.add(QueryBuilder.start("groupId").is(gpId).get()); }//from ww w . j a va 2 s .co m final QueryBuilder rightsQuery = new QueryBuilder().or( QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(), QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(), QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(), QueryBuilder.start("author.userId").is(userId).get(), QueryBuilder.start("shared") .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()) .get()); final JsonObject projection = new JsonObject(); projection.put("_id", 1); //search all blogs of user mongo.find(Blog.BLOGS_COLLECTION, MongoQueryBuilder.build(rightsQuery), null, projection, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { final Either<String, JsonArray> ei = validResults(event); if (ei.isRight()) { final JsonArray blogsResult = ei.right().getValue(); final Set<String> setIds = new HashSet<String>(); for (int i = 0; i < blogsResult.size(); i++) { final JsonObject j = blogsResult.getJsonObject(i); setIds.add(j.getString("_id")); } //search posts for the blogs found searchPosts(page, limit, searchWords.getList(), setIds, new Handler<Either<String, JsonArray>>() { @Override public void handle(Either<String, JsonArray> event) { if (event.isRight()) { if (log.isDebugEnabled()) { log.debug( "[BlogSearchingEvents][searchResource] The resources searched by user are found"); } final JsonArray res = formatSearchResult( event.right().getValue(), columnsHeader, searchWords.getList()); handler.handle(new Right<String, JsonArray>(res)); } else { handler.handle(new Either.Left<String, JsonArray>( event.left().getValue())); } } }); } else { handler.handle(new Either.Left<String, JsonArray>(ei.left().getValue())); } } }); } else { handler.handle(new Right<String, JsonArray>(new JsonArray())); } }
From source file:org.entcore.common.http.filter.MongoAppFilter.java
License:Open Source License
public void sharedAndOwner(HttpServerRequest request, String sharedMethod, UserInfos user, Handler<Boolean> handler) { String id = request.params().get(resourceIdLabel); if (id != null && !id.trim().isEmpty()) { List<DBObject> groups = new ArrayList<>(); groups.add(QueryBuilder.start("userId").is(user.getUserId()).put(sharedMethod).is(true).get()); for (String gpId : user.getGroupsIds()) { groups.add(QueryBuilder.start("groupId").is(gpId).put(sharedMethod).is(true).get()); }/*from w w w. java 2 s .co m*/ QueryBuilder query = QueryBuilder.start("_id").is(id).or( QueryBuilder.start("owner.userId").is(user.getUserId()).get(), QueryBuilder.start("shared") .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()) .get()); executeCountQuery(request, collection, MongoQueryBuilder.build(query), 1, handler); } else { handler.handle(false); } }
From source file:org.entcore.common.http.filter.MongoAppFilter.java
License:Open Source License
public void ownerOnly(HttpServerRequest request, String sharedMethod, UserInfos user, Handler<Boolean> handler) { String id = request.params().get(resourceIdLabel); if (id != null && !id.trim().isEmpty()) { QueryBuilder query = QueryBuilder.start("_id").is(id).put("owner.userId").is(user.getUserId()); executeCountQuery(request, collection, MongoQueryBuilder.build(query), 1, handler); } else {/*from www .j a va 2s. co m*/ handler.handle(false); } }
From source file:org.entcore.common.http.filter.OwnerOnly.java
License:Open Source License
@Override public void authorize(HttpServerRequest request, Binding binding, UserInfos user, Handler<Boolean> handler) { String id = request.params().get(conf.getResourceIdLabel()); if (id != null && !id.trim().isEmpty()) { QueryBuilder query = QueryBuilder.start("_id").is(id).put("owner.userId").is(user.getUserId()); MongoAppFilter.executeCountQuery(request, conf.getCollection(), MongoQueryBuilder.build(query), 1, handler);/*w w w . j a va 2 s . co m*/ } else { handler.handle(false); } }