Example usage for com.mongodb QueryBuilder start

List of usage examples for com.mongodb QueryBuilder start

Introduction

In this page you can find the example usage for com.mongodb QueryBuilder start.

Prototype

public static QueryBuilder start(final String key) 

Source Link

Document

Creates a new query with a document key

Usage

From source file:fr.wseduc.pages.filters.PageReadFilter.java

License:Open Source License

@Override
public void authorize(HttpServerRequest request, Binding binding, UserInfos user, Handler<Boolean> handler) {
    String sharedMethod = binding.getServiceMethod().replaceAll("\\.", "-");
    String id = request.params().get(conf.getResourceIdLabel());
    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());
        }//  w w w .ja va  2s  .c om
        QueryBuilder query = QueryBuilder.start("_id").is(id).or(
                QueryBuilder.start("owner.userId").is(user.getUserId()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("shared")
                        .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get())
                        .get());
        MongoAppFilter.executeCountQuery(request, conf.getCollection(), MongoQueryBuilder.build(query), 1,
                handler);
    } else {
        handler.handle(false);
    }
}

From source file:fr.wseduc.pages.filters.PagesFilter.java

License:Open Source License

public void pageRead(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());
        }/*ww  w  .  j av  a2 s . co m*/
        QueryBuilder query = QueryBuilder.start("_id").is(id).or(
                QueryBuilder.start("owner.userId").is(user.getUserId()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).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:fr.wseduc.rack.controllers.RackController.java

License:Open Source License

private void copyFiles(final HttpServerRequest request, final JsonArray idsArray, final String folder,
        final UserInfos user, final String destinationCollection) {

    String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}";
    criteria += ", \"to\" : \"" + user.getUserId() + "\" }";

    mongo.find(collection, new JsonObject(criteria), new Handler<Message<JsonObject>>() {

        private void persist(final JsonArray insert, int remains) {
            if (remains == 0) {
                mongo.insert(destinationCollection, insert, new Handler<Message<JsonObject>>() {
                    @Override/*from   w w w .j  a  va  2  s.  co m*/
                    public void handle(Message<JsonObject> inserted) {
                        if ("ok".equals(inserted.body().getString("status"))) {
                            /* Increment quota */
                            long totalSize = 0l;
                            for (Object insertion : insert) {
                                JsonObject added = (JsonObject) insertion;
                                totalSize += added.getJsonObject("metadata", new JsonObject()).getLong("size",
                                        0l);
                            }
                            updateUserQuota(user.getUserId(), totalSize);
                            renderJson(request, inserted.body());
                        } else {
                            renderError(request, inserted.body());
                        }
                    }
                });
            }
        }

        @Override
        public void handle(Message<JsonObject> r) {
            JsonObject src = r.body();
            if ("ok".equals(src.getString("status")) && src.getJsonArray("results") != null) {
                final JsonArray origs = src.getJsonArray("results");
                final JsonArray insert = new JsonArray();
                final AtomicInteger number = new AtomicInteger(origs.size());

                emptySize(user, new Handler<Long>() {

                    @Override
                    public void handle(Long emptySize) {
                        long size = 0;

                        /* Get total file size */
                        for (Object o : origs) {
                            if (!(o instanceof JsonObject))
                                continue;
                            JsonObject metadata = ((JsonObject) o).getJsonObject("metadata");
                            if (metadata != null) {
                                size += metadata.getLong("size", 0l);
                            }
                        }
                        /* If total file size is too big (> quota left) */
                        if (size > emptySize) {
                            badRequest(request, "files.too.large");
                            return;
                        }

                        /* Process */
                        for (Object o : origs) {
                            JsonObject orig = (JsonObject) o;
                            final JsonObject dest = orig.copy();
                            String now = MongoDb.formatDate(new Date());
                            dest.remove("_id");
                            dest.remove("protected");
                            dest.remove("comments");
                            dest.put("application", WORKSPACE_NAME);

                            dest.put("owner", user.getUserId());
                            dest.put("ownerName", dest.getString("toName"));
                            dest.remove("to");
                            dest.remove("from");
                            dest.remove("toName");
                            dest.remove("fromName");

                            dest.put("created", now);
                            dest.put("modified", now);
                            if (folder != null && !folder.trim().isEmpty()) {
                                dest.put("folder", folder);
                            } else {
                                dest.remove("folder");
                            }
                            insert.add(dest);
                            final String filePath = orig.getString("file");

                            if (folder != null && !folder.trim().isEmpty()) {

                                //If the document has a new parent folder, replicate sharing rights
                                String parentName, parentFolder;
                                if (folder.lastIndexOf('_') < 0) {
                                    parentName = folder;
                                    parentFolder = folder;
                                } else if (filePath != null) {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 1];
                                    parentFolder = folder;
                                } else {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 2];
                                    parentFolder = folder.substring(0, folder.lastIndexOf("_"));
                                }

                                QueryBuilder parentFolderQuery = QueryBuilder.start("owner")
                                        .is(user.getUserId()).and("folder").is(parentFolder).and("name")
                                        .is(parentName);

                                mongo.findOne(collection, MongoQueryBuilder.build(parentFolderQuery),
                                        new Handler<Message<JsonObject>>() {
                                            @Override
                                            public void handle(Message<JsonObject> event) {
                                                if ("ok".equals(event.body().getString("status"))) {
                                                    JsonObject parent = event.body().getJsonObject("result");
                                                    if (parent != null && parent.getJsonArray("shared") != null
                                                            && parent.getJsonArray("shared").size() > 0)
                                                        dest.put("shared", parent.getJsonArray("shared"));

                                                    if (filePath != null) {
                                                        storage.copyFile(filePath, new Handler<JsonObject>() {
                                                            @Override
                                                            public void handle(JsonObject event) {
                                                                if (event != null && "ok"
                                                                        .equals(event.getString("status"))) {
                                                                    dest.put("file", event.getString("_id"));
                                                                    persist(insert, number.decrementAndGet());
                                                                }
                                                            }
                                                        });
                                                    } else {
                                                        persist(insert, number.decrementAndGet());
                                                    }
                                                } else {
                                                    renderJson(request, event.body(), 404);
                                                }
                                            }
                                        });

                            } else if (filePath != null) {
                                storage.copyFile(filePath, new Handler<JsonObject>() {

                                    @Override
                                    public void handle(JsonObject event) {
                                        if (event != null && "ok".equals(event.getString("status"))) {
                                            dest.put("file", event.getString("_id"));
                                            persist(insert, number.decrementAndGet());
                                        }
                                    }
                                });
                            } else {
                                persist(insert, number.decrementAndGet());
                            }
                        }
                    }
                });
            } else {
                notFound(request, src.toString());
            }
        }
    });

}

From source file:fr.wseduc.rack.services.RackServiceMongoImpl.java

License:Open Source License

public void getRack(String id, Handler<Either<String, JsonObject>> handler) {
    mongo.findOne(collection, MongoQueryBuilder.build(QueryBuilder.start("_id").is(id)),
            MongoDbResult.validResultHandler(handler));
}

From source file:HAL.libraries.blackboard_client.BlackboardClient.java

License:Open Source License

/**
 * Retrieves the document corresponding to the given ObjectId.
 *
 * @param objId ObjectId of the requested object.
 * @return The object corresponding to the given id, or null if no such object was found.
 * @throws InvalidDBNamespaceException No collection has been selected.
 * @throws GeneralMongoException A MongoException occurred.
 **//*from   w  ww  . j  a  v a  2 s.  c om*/
public DBObject findDocumentById(ObjectId objId) throws InvalidDBNamespaceException, GeneralMongoException {
    if (currentCollection == null) {
        throw new InvalidDBNamespaceException("No collection has been selected.");
    }

    try {
        DBObject found = currentCollection.findOne(QueryBuilder.start("_id").is(objId).get());
        return found;
    } catch (MongoException mongoException) {
        throw new GeneralMongoException("An error occurred attempting to remove.", mongoException);
    }

}

From source file:HAL.libraries.blackboard_client.BlackboardClient.java

License:Open Source License

/**
 * Attempts to create and start a new monitor thread.
 * If creation of a new thread fails, the old thread will be kept alive.
 * @return true if the new thread was created successfully, false otherwise.
 **///from   ww  w  .j a va2  s.co  m
private boolean createNewMonitorThread() {
    OplogMonitorThread newThread = null;

    // Create a query that will select all documents matching one of the queries of the subscribers within the
    // selected database/collection combination.
    DBObject[] subs = new DBObject[subscriptions.size()];
    for (int i = 0; i < subscriptions.size(); ++i) {
        subs[i] = subscriptions.get(i).getQuery();
    }

    DBObject query =
            // If namespace is current database and collection.
            QueryBuilder.start("ns").is(currentDatabase.getName() + "." + currentCollection.getName())
                    // And it matches one of the subscriptions
                    .and(QueryBuilder.start().or(subs).get()).get();

    try {
        if (oplogUser != null) {
            newThread = new OplogMonitorThread(mongo, OPLOG_DATABASE_NAME, OPLOG_COLLECTION_NAME, oplogUser,
                    oplogPassword, query);
        } else {
            newThread = new OplogMonitorThread(mongo, OPLOG_DATABASE_NAME, OPLOG_COLLECTION_NAME, query);
        }
    } catch (MongoException ex) {
        // This can happen when the database has not been configured properly and the Oplog collection does not exist.
        // Creating a tailed cursor on a non-existing collection throws a MongoException.
        return false;
    }

    if (oplogMonitorThread != null) {
        oplogMonitorThread.interrupt();
    }
    oplogMonitorThread = newThread;
    oplogMonitorThread.setSubscriptions(subscriptions);
    oplogMonitorThread.start();

    return true;
}

From source file:HAL.libraries.blackboard_client.data_classes.BasicOperationSubscription.java

License:Open Source License

/**
 * @see rexos.HAL.libraries.blackboard_client.BlackboardSubscription#getQuery()
 **//*www  . jav  a2 s.  c  o m*/
@Override
public DBObject getQuery() {
    return QueryBuilder.start(OplogEntry.OPERATION_FIELD).is(operation.getOpCode()).get();
}

From source file:HAL.libraries.blackboard_client.data_classes.FieldUpdateSubscription.java

License:Open Source License

/**
 * @see rexos.HAL.libraries.blackboard_client.BasicOperationSubscription#getQuery()
 **//*from  w w w  .j a  v a 2 s .c  o m*/
@Override
public DBObject getQuery() {
    DBObject[] operationQueries = new DBObject[subscribedOperations.size()];
    int i = 0;
    for (MongoUpdateLogOperation operator : subscribedOperations) {
        operationQueries[i++] = QueryBuilder.start(createOplogUpdateFieldString(operator)).exists(true).get();
    }
    return QueryBuilder.start().and(super.getQuery(), QueryBuilder.start().or(operationQueries).get()).get();
}

From source file:homework.week2.course.UserDAO.java

License:Apache License

public DBObject validateLogin(String username, String password) {
    DBObject user = null;//from www  .j  a v  a  2s .c  o m

    // XXX look in the user collection for a user that has this username
    // assign the result to the user variable.
    QueryBuilder userQuery = QueryBuilder.start("_id").is(username);
    DBCursor cursor = usersCollection.find(userQuery.get());
    user = cursor.hasNext() ? cursor.next() : null;
    cursor.close();
    if (user == null) {
        System.out.println("User not in database");
        return null;
    }

    String hashedAndSalted = user.get("password").toString();

    String salt = hashedAndSalted.split(",")[1];

    if (!hashedAndSalted.equals(makePasswordHash(password, salt))) {
        System.out.println("Submitted password is not a match");
        return null;
    }

    return user;
}

From source file:homework.week3.course.BlogPostDAO.java

License:Apache License

public DBObject findByPermalink(String permalink) {

    DBObject post = null;//from  w ww  . j  a v  a  2  s  .co m
    // XXX HW 3.2, Work Here
    QueryBuilder findQuery = QueryBuilder.start("permalink").is(permalink);
    DBCursor cur = postsCollection.find(findQuery.get());
    post = cur.hasNext() ? cur.next() : null;
    return post;
}