Example usage for com.mongodb.client MongoCollection find

List of usage examples for com.mongodb.client MongoCollection find

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection find.

Prototype

FindIterable<TDocument> find(ClientSession clientSession);

Source Link

Document

Finds all documents in the collection.

Usage

From source file:eu.vital.vitalcep.restApp.alert.Alerts.java

/**
 * Gets a filter.//from   www .  j  a  v  a 2 s .  co  m
 *
 * @param filterId
 * @param req
 * @return the filter 
 */
@DELETE
@Path("deletealert")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response deleteAlert(String filterId, @Context HttpServletRequest req) throws IOException {
    MongoClient mongo = null;
    MongoDatabase db = null;

    try {
        StringBuilder ck = new StringBuilder();
        Security slogin = new Security();

        Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck);
        if (!token) {
            return Response.status(Response.Status.UNAUTHORIZED).build();
        }
        this.cookie = ck.toString();

        JSONObject jo = new JSONObject(filterId);
        String idjo = jo.getString("id");

        mongo = new MongoClient(new MongoClientURI(mongoURL));
        db = mongo.getDatabase(mongoDB);

        try {
            db.getCollection("alerts");
        } catch (Exception e) {
            //System.out.println("Mongo is down");
            mongo.close();
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }

        MongoCollection<Document> coll = db.getCollection("alerts");

        Bson filter = Filters.eq("id", idjo);

        FindIterable<Document> iterable = coll.find(filter);

        String cepInstance;

        CEP cepProcess = new CEP();

        if (iterable != null && iterable.first() != null) {
            Document doc = iterable.first();
            cepInstance = doc.getString("cepinstance");

            MongoCollection<Document> collInstances = db.getCollection("cepinstances");

            ObjectId ci = new ObjectId(cepInstance);
            Bson filterInstances = Filters.eq("_id", ci);

            FindIterable<Document> iterable2 = collInstances.find(filterInstances);

            if (iterable2 != null) {
                Document doc2 = iterable2.first();
                cepProcess.PID = doc2.getInteger("PID");
                cepProcess.fileName = doc2.getString("fileName");
                cepProcess.cepFolder = doc2.getString("cepFolder");
                cepProcess.type = CEP.CEPType.ALERT.toString();
                CepProcess cp = new CepProcess(null, null, null, null);
                cp.PID = doc2.getInteger("PID");

                cepProcess.cp = cp;

                if (!cepProcess.cepDispose()) {
                    java.util.logging.Logger.getLogger(Alerts.class.getName()).log(Level.SEVERE,
                            "bcep Instance not terminated");
                } else {

                    Bson filter1 = Filters.eq("_id", ci);
                    Bson update = new Document("$set", new Document("status", "terminated"));
                    UpdateOptions options = new UpdateOptions().upsert(false);
                    UpdateResult updateDoc = db.getCollection("cepinstances").updateOne(filter1, update,
                            options);

                }
                ;
                CepContainer.deleteCepProcess(cp.PID);

            }
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        DeleteResult deleteResult = coll.deleteOne(eq("id", idjo));

        if (deleteResult.getDeletedCount() < 1) {
            return Response.status(Response.Status.NOT_FOUND).build();
        } else {
            return Response.status(Response.Status.OK).build();
        }
    } catch (Exception e) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        db = null;
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
    }
}

From source file:eu.vital.vitalcep.restApp.cepRESTApi.CEPICO.java

/**
 * Gets a filter./*w w w  .  ja v a  2s.  c om*/
 *
 * @param filterId
 * @param req
 * @return the filter 
 */
@DELETE
@Path("deletecepico")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response deleteCEPICO(String filterId, @Context HttpServletRequest req) throws IOException {

    StringBuilder ck = new StringBuilder();
    Security slogin = new Security();

    Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck);
    if (!token) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    this.cookie = ck.toString();

    JSONObject jo = new JSONObject(filterId);
    String idjo = jo.getString("id");

    MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));
    MongoDatabase db = mongo.getDatabase(mongoDB);

    try {
        db.getCollection("cepicos");
    } catch (Exception e) {
        //System.out.println("Mongo is down");
        mongo.close();
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }

    MongoCollection<Document> coll = db.getCollection("cepicos");

    Bson filter = Filters.eq("id", idjo);

    FindIterable<Document> iterable = coll.find(filter);

    String cepInstance;

    CEP cepProcess = new CEP();

    if (iterable != null && iterable.first() != null) {
        Document doc = iterable.first();
        cepInstance = doc.getString("cepinstance");

        MongoCollection<Document> collInstances = db.getCollection("cepinstances");

        ObjectId ci = new ObjectId(cepInstance);
        Bson filterInstances = Filters.eq("_id", ci);

        FindIterable<Document> iterable2 = collInstances.find(filterInstances);

        if (iterable2 != null) {
            Document doc2 = iterable2.first();
            cepProcess.PID = doc2.getInteger("PID");
            cepProcess.fileName = doc2.getString("fileName");
            cepProcess.cepFolder = doc2.getString("cepFolder");
            cepProcess.type = CEP.CEPType.CEPICO.toString();
            CepProcess cp = new CepProcess(null, null, null, null);
            cp.PID = doc2.getInteger("PID");

            cepProcess.cp = cp;

            if (!cepProcess.cepDispose()) {
                java.util.logging.Logger.getLogger(CEPICO.class.getName()).log(Level.SEVERE,
                        "bcep Instance not terminated");
            } else {

                Bson filter1 = Filters.eq("_id", ci);
                Bson update = new Document("$set", new Document("status", "terminated"));
                UpdateOptions options = new UpdateOptions().upsert(false);
                UpdateResult updateDoc = db.getCollection("cepinstances").updateOne(filter1, update, options);

            }
            ;

            CepContainer.deleteCepProcess(cp.PID);

        }
    } else {
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    DeleteResult deleteResult = coll.deleteOne(eq("id", idjo));

    if (deleteResult.getDeletedCount() < 1) {
        return Response.status(Response.Status.NOT_FOUND).build();
    } else {
        return Response.status(Response.Status.OK).build();
    }
}

From source file:eu.vital.vitalcep.restApp.filteringApi.ContinuosFiltering.java

/**
 * Gets a filter.//from w w w  .  j a va 2 s.co m
 *
 * @param filterId
 * @param req
 * @return the filter 
 */
@DELETE
@Path("deletecontinuousfilter")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response deletecontinuousfilter(String filterId, @Context HttpServletRequest req) throws IOException {

    StringBuilder ck = new StringBuilder();
    Security slogin = new Security();

    Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck);
    if (!token) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    this.cookie = ck.toString();

    JSONObject jo = new JSONObject(filterId);
    String idjo = jo.getString("id");

    MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));
    MongoDatabase db = mongo.getDatabase(mongoDB);

    try {
        db.getCollection("continuousfilters");
    } catch (Exception e) {
        //System.out.println("Mongo is down");
        db = null;
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();

    }

    MongoCollection<Document> coll = db.getCollection("continuousfilters");

    Bson filter = Filters.eq("id", idjo);

    FindIterable<Document> iterable = coll.find(filter);

    String cepInstance;

    CEP cepProcess = new CEP();

    if (iterable != null && iterable.first() != null) {
        Document doc = iterable.first();
        cepInstance = doc.getString("cepinstance");

        MongoCollection<Document> collInstances = db.getCollection("cepinstances");

        ObjectId ci = new ObjectId(cepInstance);
        Bson filterInstances = Filters.eq("_id", ci);

        FindIterable<Document> iterable2 = collInstances.find(filterInstances);

        if (iterable2 != null) {
            Document doc2 = iterable2.first();
            cepProcess.PID = doc2.getInteger("PID");
            cepProcess.fileName = doc2.getString("fileName");
            cepProcess.cepFolder = doc2.getString("cepFolder");
            cepProcess.type = CEP.CEPType.CONTINUOUS.toString();
            CepProcess cp = new CepProcess(null, null, null, null);
            cp.PID = doc2.getInteger("PID");

            cepProcess.cp = cp;

            if (!cepProcess.cepDispose()) {
                java.util.logging.Logger.getLogger(ContinuosFiltering.class.getName()).log(Level.SEVERE,
                        "bcep Instance not terminated");
            } else {

                Bson filter1 = Filters.eq("_id", ci);
                Bson update = new Document("$set", new Document("status", "terminated"));
                UpdateOptions options = new UpdateOptions().upsert(false);
                UpdateResult updateDoc = db.getCollection("cepinstances").updateOne(filter1, update, options);

            }
            ;
            CepContainer.deleteCepProcess(cp.PID);

        }
    }

    DeleteResult deleteResult = coll.deleteOne(eq("id", idjo));
    db = null;
    if (mongo != null) {
        mongo.close();
        mongo = null;
    }
    if (deleteResult.getDeletedCount() < 1) {
        return Response.status(Response.Status.NOT_FOUND).build();
    } else {

        return Response.status(Response.Status.OK).build();
    }
}

From source file:eu.vre4eic.evre.telegram.commands.RegisterAuthCommand.java

License:Apache License

@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) {

    String userName = user.getFirstName() + " " + user.getLastName();
    StringBuilder messageBuilder = new StringBuilder();
    if (arguments.length != 2) {
        messageBuilder.append("Hi ").append(userName).append("\n");
        messageBuilder.append("please use: /register username pwd");
    } else {// w  ww.  j av  a 2 s . co m
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase db = mongoClient.getDatabase("evre");
        MongoCollection<Document> collection = db.getCollection("eVREUserProfile");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("userId", arguments[0]);
        FindIterable<Document> itcursor = collection.find(searchQuery);
        //FindIterable<Document> itcursor=collection.find();
        MongoCursor<Document> cursor = itcursor.iterator();
        if (cursor.hasNext()) {

            Document userCan = cursor.next();
            String pwd = userCan.getString("password");

            Binary binS = userCan.get("salt", org.bson.types.Binary.class);
            String salt = new String(binS.getData());
            boolean validUser = false;
            if (pwd.equals(arguments[1]))
                validUser = true;

            if (salt != null && !checkEncryptedData(arguments[1], salt.getBytes()).equals(arguments[1]))
                validUser = true;

            //if(pwd.equals(arguments[1])){
            if (validUser) {

                userCan.replace("authId", chat.getId());
                BasicDBObject updateObj = new BasicDBObject();
                updateObj.put("$set", userCan);
                //check this!!!
                collection.updateOne(searchQuery, updateObj);

                messageBuilder.append("Done ").append(userName).append(",\n");
                messageBuilder.append(
                        "this Telegram account is now registered as e-VRE Authenticator for " + arguments[0]);

            } else {//error credentials wrong
                messageBuilder.append("Hi ").append(userName).append("\n");
                messageBuilder.append("credentials not valid!");
            }

        } else {//error credentials wrong
            messageBuilder.append("Hi ").append(userName).append("\n");
            messageBuilder.append("credentials not valid!");
        }
        mongoClient.close();
    }

    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(messageBuilder.toString());

    try {
        absSender.sendMessage(answer);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }

}

From source file:eu.vre4eic.evre.telegram.commands.RemoveAuthCommand.java

License:Apache License

@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) {

    String userName = user.getFirstName() + " " + user.getLastName();
    StringBuilder messageBuilder = new StringBuilder();
    if (arguments.length != 2) {
        messageBuilder.append("Hi ").append(userName).append("\n");
        messageBuilder.append("please use: /remove username pwd");
    } else {//from  www  .  j  a va 2s. c om
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase db = mongoClient.getDatabase("evre");
        MongoCollection<Document> collection = db.getCollection("eVREUserProfile");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("userId", arguments[0]);
        FindIterable<Document> itcursor = collection.find(searchQuery);
        //FindIterable<Document> itcursor=collection.find();
        MongoCursor<Document> cursor = itcursor.iterator();
        if (cursor.hasNext()) {
            //System.out.println("################## "+cursor.next());
            Document userCan = cursor.next();
            String pwd = userCan.getString("password");
            if (pwd.equals(arguments[1])) {

                String aId = userCan.getString("authId");
                if (!aId.equals("0")) {
                    // we don't check if the chat.getId() is the same,
                    //because a user can remove this from another Telegram ID,
                    // need to check this

                    userCan.replace("authId", "0");
                    BasicDBObject updateObj = new BasicDBObject();
                    updateObj.put("$set", userCan);
                    //check this!!!
                    collection.updateOne(searchQuery, updateObj);

                    messageBuilder.append("Done ").append(userName).append(", \n");
                    messageBuilder.append(
                            "this Telegram account is no longer an e-VRE Authenticator for " + arguments[0]);
                } else {//the user with the provided credentials has no authenticator defined
                    messageBuilder.append("Hi ").append(userName).append(",\n");
                    messageBuilder.append("something went wrong, please contact the administrator!");
                }

            } else {//error credentials wrong
                messageBuilder.append("Hi ").append(userName).append("\n");
                messageBuilder.append("credentials not valid!");
            }

        } else {//error credentials wrong
            messageBuilder.append("Hi ").append(userName).append(",\n");
            messageBuilder.append("credentials not valid!");
        }
        mongoClient.close();
    }

    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(messageBuilder.toString());

    try {
        absSender.sendMessage(answer);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }
}

From source file:fucksocks.server.manager.MongoDBBasedUserManager.java

License:Apache License

public User fetchUserFromMongoDB(final String username) {
    if (mongoDBUtil == null) {
        mongoDBUtil = initMongoDBUtil();
    }/*from  w ww .  j  av  a 2  s . com*/
    return mongoDBUtil.doJob(new MongoDBCallback<User>() {
        @Override
        public User process(MongoCollection<Document> collection) {
            FindIterable<Document> result = collection.find(new Document(USER_USERNAME_KEY, username));
            for (Document document : result) {
                return formUser(document);
            }
            return null;
        }
    });
}

From source file:henu.dao.impl.CaclDaoImpl.java

License:Open Source License

@Override
public String getUserData(String cid, String uid) {
    MongoCollection<Document> collection = NosqlDB.getCollection(cid);
    String json = "";
    FindIterable<Document> findIterable = collection.find(Filters.eq("uid", uid));
    MongoCursor<Document> mongoCursor = findIterable.iterator();

    while (mongoCursor.hasNext()) {
        json += mongoCursor.next().toJson();
    }/*  w  ww  . j a v  a 2s .co m*/
    return json;
}

From source file:hrpod.data.MongoDBDao.java

public String find(String collectionName) {
    String json = null;/*w  w w  .  jav  a 2  s  .c  o  m*/
    MongoCollection<Document> collection = db.getCollection(collectionName);
    FindIterable<Document> iterable = collection.find(new Document("Job Code", "10075"));
    for (Document document : iterable) {
        json = document.toString();
    }
    return json;
}

From source file:if4031.ServerHandler.java

@Override
public String getMessage(List<ChannelLastMsg> clm, String token) throws TException {
    String messages = "";
    for (ChannelLastMsg channelStruct : clm) {
        MongoCollection<Document> messageCollection = database.getCollection(channelStruct.channel + "Message");
        FindIterable<Document> iterable = messageCollection
                .find(new Document("id", new Document("$gt", channelStruct.lastID)));
        for (Document doc : iterable) {
            //                if(doc.getString("nick").equals(token))
            messages = messages + channelStruct.channel + ":@" + token + ' ' + doc.getString("message") + '\n';
            //                    System.out.println(doc.getString("message"));
        }/*from  w  w  w.  j  av  a  2s  .  c om*/
    }
    return messages;
}

From source file:if4031.ServerHandler.java

@Override
public boolean isNickExist(String nick) throws TException {
    MongoCollection<Document> userCollection = database.getCollection("User");
    return userCollection.find(eq("nick", nick)).first() != null;
}