Example usage for com.mongodb BasicDBList BasicDBList

List of usage examples for com.mongodb BasicDBList BasicDBList

Introduction

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

Prototype

BasicDBList

Source Link

Usage

From source file:com.mongodash.dao.mapper.SettingsDBObjectMapper.java

@Override
public DBObject mapObject(Settings object) {

    DBObject dbObject = new BasicDBObject();

    if (SETTINGS_KEY.email == object.getKey()) {
        EmailSettings es = (EmailSettings) object;
        dbObject.put(Config.COMMON_FIELDS._id.name(), SETTINGS_KEY.email.toString());
        dbObject.put("enabled", es.isEnabled());
        dbObject.put("server", es.getServer());
        dbObject.put("port", es.getPort());
        dbObject.put("sender", es.getSender());

        if (StringUtils.hasText(es.getUsername()) && StringUtils.hasText(es.getPassword())) {
            dbObject.put("username", es.getUsername());
            dbObject.put("password", PasswordUtil.encrypt(es.getPassword()));
        }//w  ww .  java 2 s.  co  m
        dbObject.put("ssl", es.isSsl());
    } else if (SETTINGS_KEY.alerts == object.getKey()) {
        AlertSettings es = (AlertSettings) object;
        dbObject.put(Config.COMMON_FIELDS._id.name(), SETTINGS_KEY.alerts.toString());
        dbObject.put("enabled", es.isEnabled());
        dbObject.put("emailSubject", es.getEmailSubject());
        dbObject.put("emailRecipients", es.getEmailRecipients());
    } else if (SETTINGS_KEY.ldap == object.getKey()) {
        LdapSettings es = (LdapSettings) object;
        dbObject.put("_id", SETTINGS_KEY.ldap.toString());
        dbObject.put("enabled", es.isEnabled());
        dbObject.put("host", es.getHost());
        dbObject.put("port", es.getPort());
        dbObject.put("adminDn", es.getAdminDn());
        dbObject.put("adminPassword", es.getAdminPassword());
        dbObject.put("baseDn", es.getBaseDn());
        dbObject.put("loginAttr", es.getLoginAttribute());
        dbObject.put("secure", es.isSecure());
    } else if (SETTINGS_KEY.notifications == object.getKey()) {
        NotificationSettings es = (NotificationSettings) object;
        dbObject.put(Config.COMMON_FIELDS._id.name(), SETTINGS_KEY.notifications.toString());
        dbObject.put("enabled", es.isEnabled());
        dbObject.put("emailEnabled", es.isEmailEnabled());
        dbObject.put("emailSubject", es.getEmailSubject());
        dbObject.put("emailRecipients", es.getEmailRecipients());
        if (es.getEnabledNotifications() != null && es.getEnabledNotifications().size() > 0) {
            BasicDBList list = new BasicDBList();
            list.addAll(es.getEnabledNotifications());
            dbObject.put("enabledNotifications", list);
        }
    } else if (SETTINGS_KEY.licenseKey == object.getKey()) {
        LicenseKeySettings ls = (LicenseKeySettings) object;
        dbObject.put(Config.COMMON_FIELDS._id.name(), SETTINGS_KEY.licenseKey.toString());
        dbObject.put("privateKey", ls.getPrivateKey());
        dbObject.put("publicKey", ls.getPublicKey());
    }

    return dbObject;
}

From source file:com.mycompany.mongodemo.MongoDemoClass.java

public static void main(String[] args) {
    MongoClient mongo = new MongoClient("localhost", 27017);
    /*//from w ww  . ja v a  2 s.c  o m
    first create database and collection(table) in mongodb
    code
        use demodb // to create db
        db.createCollection("users") // create table users in db
     */
    DB db = mongo.getDB("demodb");

    DBCollection col = db.getCollection("users");

    // creating list of POST
    BasicDBList postList = new BasicDBList();
    postList.add("a1"); // add post reference in list
    postList.add("a2");
    postList.add("a3");
    // create nested element : posts
    BasicDBObject posts = new BasicDBObject("publicPost", postList).append("privatePost", postList)
            .append("exclusivePost", postList);

    // create insert document 
    BasicDBObject doc = new BasicDBObject("firstName", "vishal").append("lastName", "patel")
            .append("email", "vishal.6794@gmail.com").append("userName", "im_vishal")
            .append("password", "admin").append("userType", 1).append("lastAccessTime", new Date())
            .append("posts", posts).append("rating", 10).append("verified", true);

    // insert into collection using insert method
    col.insert(doc);

    /*
    display first document from collection
    in this case our collection is users
    */

    DBObject mydoc = col.findOne();
    System.out.println(mydoc);
}

From source file:com.mysema.query.mongodb.MongodbSerializer.java

License:Apache License

@Override
public Object visit(Operation<?> expr, Void context) {
    Operator<?> op = expr.getOperator();
    if (op == Ops.EQ) {
        return asDBObject(asDBKey(expr, 0), asDBValue(expr, 1));

    } else if (op == Ops.STRING_IS_EMPTY) {
        return asDBObject(asDBKey(expr, 0), "");

    } else if (op == Ops.AND) {
        BasicDBObject left = (BasicDBObject) handle(expr.getArg(0));
        left.putAll((BSONObject) handle(expr.getArg(1)));
        return left;

    } else if (op == Ops.NOT) {
        //Handle the not's child
        BasicDBObject arg = (BasicDBObject) handle(expr.getArg(0));

        //Only support the first key, let's see if there
        //is cases where this will get broken
        String key = arg.keySet().iterator().next();

        Operator<?> subOp = ((Operation<?>) expr.getArg(0)).getOperator();
        if (subOp != Ops.EQ && subOp != Ops.STRING_IS_EMPTY) {
            return asDBObject(key, asDBObject("$not", arg.get(key)));
        } else {/*w  ww .j  a va 2s.c  om*/
            return asDBObject(key, asDBObject("$ne", arg.get(key)));
        }

    } else if (op == Ops.OR) {
        BasicDBList list = new BasicDBList();
        list.add(handle(expr.getArg(0)));
        list.add(handle(expr.getArg(1)));
        return asDBObject("$or", list);

    } else if (op == Ops.NE) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$ne", asDBValue(expr, 1)));

    } else if (op == Ops.STARTS_WITH) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1)));

    } else if (op == Ops.STARTS_WITH_IC) {
        return asDBObject(asDBKey(expr, 0),
                Pattern.compile("^" + regexValue(expr, 1), Pattern.CASE_INSENSITIVE));

    } else if (op == Ops.ENDS_WITH) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(regexValue(expr, 1) + "$"));

    } else if (op == Ops.ENDS_WITH_IC) {
        return asDBObject(asDBKey(expr, 0),
                Pattern.compile(regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE));

    } else if (op == Ops.EQ_IGNORE_CASE) {
        return asDBObject(asDBKey(expr, 0),
                Pattern.compile("^" + regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE));

    } else if (op == Ops.STRING_CONTAINS) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(".*" + regexValue(expr, 1) + ".*"));

    } else if (op == Ops.STRING_CONTAINS_IC) {
        return asDBObject(asDBKey(expr, 0),
                Pattern.compile(".*" + regexValue(expr, 1) + ".*", Pattern.CASE_INSENSITIVE));

    } else if (op == Ops.MATCHES) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(asDBValue(expr, 1).toString()));

    } else if (op == Ops.MATCHES_IC) {
        return asDBObject(asDBKey(expr, 0),
                Pattern.compile(asDBValue(expr, 1).toString(), Pattern.CASE_INSENSITIVE));

    } else if (op == Ops.LIKE) {
        String regex = ExpressionUtils.likeToRegex((Expression) expr.getArg(1)).toString();
        return asDBObject(asDBKey(expr, 0), Pattern.compile(regex));

    } else if (op == Ops.BETWEEN) {
        BasicDBObject value = new BasicDBObject("$gte", asDBValue(expr, 1));
        value.append("$lte", asDBValue(expr, 2));
        return asDBObject(asDBKey(expr, 0), value);

    } else if (op == Ops.IN) {
        int constIndex = 0;
        int exprIndex = 1;
        if (expr.getArg(1) instanceof Constant<?>) {
            constIndex = 1;
            exprIndex = 0;
        }
        if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
            Collection<?> values = (Collection<?>) ((Constant<?>) expr.getArg(constIndex)).getConstant();
            return asDBObject(asDBKey(expr, exprIndex), asDBObject("$in", values.toArray()));
        } else {
            return asDBObject(asDBKey(expr, exprIndex), asDBValue(expr, constIndex));
        }

    } else if (op == Ops.LT) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$lt", asDBValue(expr, 1)));

    } else if (op == Ops.GT) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$gt", asDBValue(expr, 1)));

    } else if (op == Ops.LOE) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$lte", asDBValue(expr, 1)));

    } else if (op == Ops.GOE) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$gte", asDBValue(expr, 1)));

    } else if (op == Ops.IS_NULL) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$exists", false));

    } else if (op == Ops.IS_NOT_NULL) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$exists", true));

    } else if (op == MongodbOps.NEAR) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$near", asDBValue(expr, 1)));

    } else if (op == MongodbOps.ELEM_MATCH) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$elemMatch", asDBValue(expr, 1)));
    }

    throw new UnsupportedOperationException("Illegal operation " + expr);
}

From source file:com.mythesis.userbehaviouranalysis.ProfileAnalysis.java

License:Apache License

/**
 * a method that stores the query that has been suggested by the user
 * @param crawlerOutputPath SWebRank output directory used to check if a relevant query already exists
 * @param profile the query's relevant profile
 * @param query the given query//from  w ww.  j ava2  s.  c  o  m
 */
public void storeQuery(String crawlerOutputPath, String profile, String query) {

    System.out.println(crawlerOutputPath);
    System.out.println(profile);
    System.out.println(query);
    //Find output paths
    File root = new File(crawlerOutputPath);
    File[] contents = root.listFiles();
    List<String> sWebRanklevels = new ArrayList<>();
    for (File f : contents) {
        if (f.getAbsolutePath().contains("level"))
            sWebRanklevels.add(f.getAbsolutePath());
    }

    //Find all query paths
    List<String> queries = new ArrayList<>();
    for (String s : sWebRanklevels) {
        File level = new File(s);
        File[] queriesFiles = level.listFiles();
        for (File f : queriesFiles) {
            if (!f.getAbsolutePath().contains("txt")) {
                String str = f.getAbsolutePath();
                queries.add(str.substring(str.lastIndexOf("\\") + 1).replace("-query", "").replace("+", " "));
            }
        }
    }

    //check if a relevant query already exists - I use Jaro-Winkler distance
    query = query.trim().replaceAll(" +", " ");
    for (String q : queries) {
        JaroWinklerDistance jwd = new JaroWinklerDistance();
        double distance = jwd.getDistance(q, query);
        if (distance > 0.9) { // threshold = 0.9
            return;
        }
    }

    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB("profileAnalysis");

    DBCollection DBqueries = db.getCollection("newQueries");
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("profile", profile);
    DBObject document = DBqueries.findOne(searchQuery);
    boolean flag = false;

    //check if a relevant query exists in the database - I use Jaro-Winkler distance
    if (document != null) {
        flag = true;
        BasicDBList storedQueries = (BasicDBList) document.get("queries");
        for (Object quer : storedQueries) {
            JaroWinklerDistance jwd = new JaroWinklerDistance();
            double distance = jwd.getDistance((String) quer, query);
            if (distance > 0.9) { // threshold = 0.9
                return;
            }
        }
    }

    //if document already exists add the new query
    if (flag) {
        DBqueries.update(searchQuery, new BasicDBObject("$push", new BasicDBObject("queries", query)));
    } else { //otherwise create a new document
        BasicDBList dbl = new BasicDBList();
        dbl.add(query);
        BasicDBObject entry = new BasicDBObject("profile", profile).append("queries", dbl);
        DBqueries.insert(entry);
    }
}

From source file:com.owly.srv.RemoteBasicStatMongoDAOImpl.java

License:Apache License

public List<String> getTypeStatFromServer(ArrayList<ShortRemoteServerId> listShortRemoteServerId,
        Integer minutesToCheck) {

    getLogger().info("MONGODB : get info of type of stats for an specific server");
    GregorianCalendar cal = new GregorianCalendar();
    Date nowDate = cal.getTime();
    cal.add(Calendar.MINUTE, -minutesToCheck);
    Date beforeDate = cal.getTime();
    SimpleDateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    getLogger().info("MONGODB : Get a metric in a period of time starting : " + dtformat.format(beforeDate)
            + " and ending : " + dtformat.format(nowDate));

    List<String> typeStat = new ArrayList<String>();

    //Varaibles to generat a query with or clause
    BasicDBObject query = new BasicDBObject();
    BasicDBList or = new BasicDBList();

    //Check all severs that arrive to the method and generate the or clause
    Iterator<ShortRemoteServerId> iterator = listShortRemoteServerId.iterator();
    while (iterator.hasNext()) {
        ShortRemoteServerId shortRmt = iterator.next();
        BasicDBObject clause = new BasicDBObject("ServerIP", shortRmt.getNodeIPAddress()).append("NameServer",
                shortRmt.getName());/*w  w w  .ja  v  a 2s. co  m*/
        or.add(clause);
    }
    query = new BasicDBObject("$or", or).append("StatDate", new BasicDBObject("$gt", beforeDate));

    getLogger().info("MONGODB : Get type of stats in the database for this clause" + query.toString());

    typeStat = remoteStatCollection.distinct("StatType", query);

    getLogger().info("MONGODB : List obtained");
    return typeStat;
}

From source file:com.owly.srv.RemoteBasicStatMongoDAOImpl.java

License:Apache License

public List<String> getTypeStatFromServer(ArrayList<ShortRemoteServerId> listShortRemoteServerId,
        Date startDate, Date endDate) {
    getLogger().info("MONGODB : get info of type of stats for an specific server");
    getLogger().info(/* w  ww .  jav a  2  s  .c o m*/
            "MONGODB : Get a metric in a period of time starting : " + startDate + " and ending : " + endDate);

    List<String> typeStat = new ArrayList<String>();

    //Varaibles to generat a query with or clause
    BasicDBObject query = new BasicDBObject();
    BasicDBList or = new BasicDBList();

    //Check all severs that arrive to the method and generate the or clause
    Iterator<ShortRemoteServerId> iterator = listShortRemoteServerId.iterator();
    while (iterator.hasNext()) {
        ShortRemoteServerId shortRmt = iterator.next();
        BasicDBObject clause = new BasicDBObject("ServerIP", shortRmt.getNodeIPAddress()).append("NameServer",
                shortRmt.getName());
        or.add(clause);
    }
    query = new BasicDBObject("$or", or).append("StatDate",
            new BasicDBObject("$gt", startDate).append("$lt", endDate));

    typeStat = remoteStatCollection.distinct("StatType", query);

    getLogger().info("MONGODB : List obtained");
    return typeStat;

}

From source file:com.owly.srv.RemoteBasicStatMongoDAOImpl.java

License:Apache License

public Set<String> getTypeMetricFromStat(ArrayList<ShortRemoteServerId> listShortRemoteServerId,
        String typeOfStat, Integer minutesToCheck) {

    getLogger().info("MONGODB : get info of type of metrcis for an specific server and specific stat");
    GregorianCalendar cal = new GregorianCalendar();
    Date nowDate = cal.getTime();
    cal.add(Calendar.MINUTE, -minutesToCheck);
    Date beforeDate = cal.getTime();
    SimpleDateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    getLogger().info("MONGODB : Get a metric in a period of time starting : " + dtformat.format(beforeDate)
            + " and ending : " + dtformat.format(nowDate));

    //Varaibles to generat a query with or clause
    BasicDBObject query = new BasicDBObject();
    BasicDBList or = new BasicDBList();

    //Check all severs that arrive to the method and generate the or clause
    Iterator<ShortRemoteServerId> iterator = listShortRemoteServerId.iterator();
    while (iterator.hasNext()) {
        ShortRemoteServerId shortRmt = iterator.next();
        BasicDBObject clause = new BasicDBObject("ServerIP", shortRmt.getNodeIPAddress()).append("NameServer",
                shortRmt.getName());//from w  ww.ja  va 2 s  .  c  o  m
        or.add(clause);
    }
    query = new BasicDBObject("$or", or).append("StatType", typeOfStat).append("StatDate",
            new BasicDBObject("$gt", beforeDate));

    getLogger().info("MONGODB : Get type of stats in the database for this clause" + query.toString());

    //logger.debug("MONGODB : query ="+query.toString());

    //Create the selector
    BasicDBObject obj = new BasicDBObject("Metrics", true).append("_id", false);

    //Create the ordeby
    BasicDBObject orderBy = new BasicDBObject("StatDate", -1);

    DBObject res = remoteStatCollection.findOne(query, obj, orderBy);

    Set<String> typeMetric = (((BSONObject) res.get("Metrics")).toMap()).keySet();

    //logger.debug("MONGODB : query result"+typeMetric.toString());
    getLogger().info("MONGODB : List obtained");

    return typeMetric;
}

From source file:com.owly.srv.RemoteBasicStatMongoDAOImpl.java

License:Apache License

public Set<String> getTypeMetricFromStat(ArrayList<ShortRemoteServerId> listShortRemoteServerId,
        String typeOfStat, Date startDate, Date endDate) {

    getLogger().info("MONGODB : get info of type of stats for an specific server");
    getLogger().info(//from  w  w  w . j a va2s .  co  m
            "MONGODB : Get a metric in a period of time starting : " + startDate + " and ending : " + endDate);

    //Varaibles to generat a query with or clause
    BasicDBObject query = new BasicDBObject();
    BasicDBList or = new BasicDBList();

    //Check all severs that arrive to the method and generate the or clause
    Iterator<ShortRemoteServerId> iterator = listShortRemoteServerId.iterator();
    while (iterator.hasNext()) {
        ShortRemoteServerId shortRmt = iterator.next();
        BasicDBObject clause = new BasicDBObject("ServerIP", shortRmt.getNodeIPAddress()).append("NameServer",
                shortRmt.getName());
        or.add(clause);
    }
    query = new BasicDBObject("$or", or).append("StatType", typeOfStat).append("StatDate",
            new BasicDBObject("$gt", startDate).append("$lt", endDate));

    //logger.debug("MONGODB : query ="+query.toString());
    //Create the selector
    BasicDBObject obj = new BasicDBObject("Metrics", true).append("_id", false);

    //Create the ordeby
    BasicDBObject orderBy = new BasicDBObject("StatDate", -1);

    DBObject res = remoteStatCollection.findOne(query, obj, orderBy);
    Set<String> typeMetric = (((BSONObject) res.get("Metrics")).toMap()).keySet();

    //logger.debug("MONGODB : query result"+typeMetric.toString());
    getLogger().info("MONGODB : List obtained");

    return typeMetric;
}

From source file:com.owly.srv.RemoteBasicStatMongoDAOImpl.java

License:Apache License

public boolean isThereMetricDetails(ArrayList<ShortRemoteServerId> listShortRemoteServerId, String typeOfStat,
        String typeOfMetric, Integer minutesToCheck) {
    getLogger().info("MONGODB : Get availability of metrics in a period of time vbased in minutes");

    GregorianCalendar cal = new GregorianCalendar();
    Date nowDate = cal.getTime();
    cal.add(Calendar.MINUTE, -minutesToCheck);
    Date beforeDate = cal.getTime();
    SimpleDateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    getLogger().info("MONGODB : Get a metric in a period of time starting : " + dtformat.format(beforeDate)
            + " and ending : " + dtformat.format(nowDate));

    //Varaibles to generat a query with or clause
    BasicDBObject query = new BasicDBObject();
    BasicDBList or = new BasicDBList();

    //Check all severs that arrive to the method and generate the or clause
    Iterator<ShortRemoteServerId> iterator = listShortRemoteServerId.iterator();
    while (iterator.hasNext()) {
        ShortRemoteServerId shortRmt = iterator.next();
        BasicDBObject clause = new BasicDBObject("ServerIP", shortRmt.getNodeIPAddress()).append("NameServer",
                shortRmt.getName());//from   w w  w  .  j  a v  a2  s  .  co  m
        or.add(clause);
    }
    query = new BasicDBObject("$or", or).append("StatType", typeOfStat).append("StatDate",
            new BasicDBObject("$gt", beforeDate).append("$lt", nowDate));

    getLogger().debug("MONGODB : query =" + query.toString());

    //Create the selector
    BasicDBObject obj = new BasicDBObject("Metrics." + typeOfMetric, true).append("StatDate", true)
            .append("_id", false);

    getLogger().debug("MONGODB : selector =" + obj.toString());

    int nb_metrics = remoteStatCollection.find(query, obj).count();

    if (nb_metrics > 0) {
        getLogger().info("MONGODB : Metrics exist in this period of time");
        return true;

    } else {
        getLogger().info("MONGODB : Metrics do not exist in this period of time");
        return false;

    }
}

From source file:com.owly.srv.RemoteBasicStatMongoDAOImpl.java

License:Apache License

public boolean isThereMetricDetails(ArrayList<ShortRemoteServerId> listShortRemoteServerId, String typeOfStat,
        String typeOfMetric, Date startDate, Date endDate) {

    getLogger().info("MONGODB : get info of type of stats for an specific server");
    getLogger().info(/* www  .  ja v  a2 s  .  c o m*/
            "MONGODB : Get a metric in a period of time starting : " + startDate + " and ending : " + endDate);

    //Varaibles to generat a query with or clause
    BasicDBObject query = new BasicDBObject();
    BasicDBList or = new BasicDBList();

    //Check all severs that arrive to the method and generate the or clause
    Iterator<ShortRemoteServerId> iterator = listShortRemoteServerId.iterator();
    while (iterator.hasNext()) {
        ShortRemoteServerId shortRmt = iterator.next();
        BasicDBObject clause = new BasicDBObject("ServerIP", shortRmt.getNodeIPAddress()).append("NameServer",
                shortRmt.getName());
        or.add(clause);
    }
    query = new BasicDBObject("$or", or).append("StatType", typeOfStat).append("StatDate",
            new BasicDBObject("$gt", startDate).append("$lt", endDate));

    getLogger().debug("MONGODB : query =" + query.toString());

    //Create the selector
    BasicDBObject obj = new BasicDBObject("Metrics." + typeOfMetric, true).append("StatDate", true)
            .append("_id", false);

    getLogger().debug("MONGODB : selector =" + obj.toString());

    int nb_metrics = remoteStatCollection.find(query, obj).count();

    if (nb_metrics > 0) {
        getLogger().info("MONGODB : Metrics exist in this period of time");
        return true;

    } else {
        getLogger().info("MONGODB : Metrics do not exist in this period of time");
        return false;

    }
}