Example usage for com.mongodb DBCursor hasNext

List of usage examples for com.mongodb DBCursor hasNext

Introduction

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

Prototype

@Override
public boolean hasNext() 

Source Link

Document

Checks if there is another object available.

Usage

From source file:alto.plugin.webradio.recommender.MongoDBDataModel.java

License:Apache License

/**
 * <p>//from  ww  w .j  a v a2  s. c o m
 * Triggers "refresh" -- whatever that means -- of the implementation.
 * The general contract is that any should always leave itself in a
 * consistent, operational state, and that the refresh atomically updates
 * internal state from old to new.
 * </p>
 *
 * @param alreadyRefreshed s that are known to have already been refreshed as
 *                         a result of an initial call to a method on some object. This ensures
 *                         that objects in a refresh dependency graph aren't refreshed twice
 *                         needlessly.
 * @see #refreshData(String, Iterable, boolean)
 */
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
    BasicDBObject query = new BasicDBObject();
    query.put("deleted_at", new BasicDBObject("$gt", mongoTimestamp));
    DBCursor cursor = collection.find(query);
    Date ts = new Date(0);
    while (cursor.hasNext()) {
        Map<String, Object> user = (Map<String, Object>) cursor.next().toMap();
        String userID = getID(user.get(mongoUserID), true);
        Collection<List<String>> items = Lists.newArrayList();
        List<String> item = Lists.newArrayList();
        item.add(getID(user.get(mongoItemID), false));
        item.add(Float.toString(getPreference(user.get(mongoPreference))));
        items.add(item);
        try {
            refreshData(userID, items, false);
        } catch (NoSuchUserException e) {
            log.warn("No such user ID: {}", userID);
        } catch (NoSuchItemException e) {
            log.warn("No such items: {}", items);
        }
        if (ts.compareTo(getDate(user.get("created_at"))) < 0) {
            ts = getDate(user.get("created_at"));
        }
    }
    query = new BasicDBObject();
    query.put("created_at", new BasicDBObject("$gt", mongoTimestamp));
    cursor = collection.find(query);
    while (cursor.hasNext()) {
        Map<String, Object> user = (Map<String, Object>) cursor.next().toMap();
        if (!user.containsKey("deleted_at")) {
            String userID = getID(user.get(mongoUserID), true);
            Collection<List<String>> items = Lists.newArrayList();
            List<String> item = Lists.newArrayList();
            item.add(getID(user.get(mongoItemID), false));
            item.add(Float.toString(getPreference(user.get(mongoPreference))));
            items.add(item);
            try {
                refreshData(userID, items, true);
            } catch (NoSuchUserException e) {
                log.warn("No such user ID: {}", userID);
            } catch (NoSuchItemException e) {
                log.warn("No such items: {}", items);
            }
            if (ts.compareTo(getDate(user.get("created_at"))) < 0) {
                ts = getDate(user.get("created_at"));
            }
        }
    }
    if (mongoTimestamp.compareTo(ts) < 0) {
        mongoTimestamp = ts;
    }
}

From source file:alto.plugin.webradio.recommender.MongoDBDataModel.java

License:Apache License

private void buildModel() throws UnknownHostException {
    userIsObject = false;/*from   w  w  w .ja v a2  s .  c om*/
    itemIsObject = false;
    idCounter = 0;
    preferenceIsString = true;
    Mongo mongoDDBB = new Mongo(mongoHost, mongoPort);
    DB db = mongoDDBB.getDB(mongoDB);
    mongoTimestamp = new Date(0);
    FastByIDMap<Collection<Preference>> userIDPrefMap = new FastByIDMap<Collection<Preference>>();
    if (!mongoAuth || db.authenticate(mongoUsername, mongoPassword.toCharArray())) {
        collection = db.getCollection(mongoCollection);
        collectionMap = db.getCollection(mongoMapCollection);
        DBObject indexObj = new BasicDBObject();
        indexObj.put("element_id", 1);
        collectionMap.ensureIndex(indexObj);
        indexObj = new BasicDBObject();
        indexObj.put("long_value", 1);
        collectionMap.ensureIndex(indexObj);
        collectionMap.remove(new BasicDBObject());
        DBCursor cursor = collection.find();
        while (cursor.hasNext()) {
            Map<String, Object> user = (Map<String, Object>) cursor.next().toMap();
            if (!user.containsKey("deleted_at")) {
                long userID = Long.parseLong(fromIdToLong(getID(user.get(mongoUserID), true), true));
                long itemID = Long.parseLong(fromIdToLong(getID(user.get(mongoItemID), false), false));
                float ratingValue = getPreference(user.get(mongoPreference));
                Collection<Preference> userPrefs = userIDPrefMap.get(userID);
                if (userPrefs == null) {
                    userPrefs = Lists.newArrayListWithCapacity(2);
                    userIDPrefMap.put(userID, userPrefs);
                }
                userPrefs.add(new GenericPreference(userID, itemID, ratingValue));
                if (user.containsKey("created_at")
                        && mongoTimestamp.compareTo(getDate(user.get("created_at"))) < 0) {
                    mongoTimestamp = getDate(user.get("created_at"));
                }
            }
        }
    }
    delegate = new GenericDataModel(GenericDataModel.toDataMap(userIDPrefMap, true));
}

From source file:amazonwebcrawler.Mongo.java

public void removeData(String name) {
    try {/*  w ww .j av  a 2s.c o  m*/
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", name);

        DBCursor cursor = myTable.find(searchQuery);

        while (cursor.hasNext()) {
            myTable.remove(cursor.next());
        }
    } catch (MongoException e) {
        e.printStackTrace();
    }
}

From source file:amazonwebcrawler.Mongo.java

public void searchData(String name) {
    try {/* ww  w  .j av  a  2s  . c  o  m*/
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", name);

        DBCursor cursor = myTable.find(searchQuery);

        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }

    } catch (MongoException e) {
        e.printStackTrace();
    }
}

From source file:app.model.Model.java

public void setTable(JTable table, String collection) {
    DBCollection col = this.getCollection(collection);
    DBCursor cur = col.find();

    String[] columnNames = { "id", "CIDADE", "UF" };
    DefaultTableModel model = new DefaultTableModel(columnNames, 0);

    while (cur.hasNext()) {
        DBObject obj = cur.next();/*from w w  w .j  a va  2s .  co  m*/
        String cidade = (String) obj.get("CIDADE");
        String uf = (String) obj.get("UF");
        ObjectId id = (ObjectId) obj.get("_id");
        model.addRow(new Object[] { id, cidade, uf });
    }
    cur.close();
    table.setModel(model);
}

From source file:App.modules.main_menu.model.dao.Sign_in_DAO.java

public static int Select_Admin_dni_mongo() {
    DBCursor cursor = null;
    int ok = 0;/*from w w w .ja  va  2  s .c  o m*/
    Singleton_App.c = new Client();

    try {

        BasicDBObject query = new BasicDBObject();
        query.put("user", Sign_in.User_txt.getText());
        query.put("pass", Sign_in.Pass_txt.getText());

        // BasicDBObject searchById = new BasicDBObject();
        // searchById.append("dni", 1).append("_id",0);

        cursor = Singleton_App.collection.find(query);

        if (cursor.count() != 0) {

            while (cursor.hasNext()) {

                BasicDBObject document = (BasicDBObject) cursor.next();

                Singleton_App.c = Singleton_App.c.Client_to_DB(document);

                ok = 1;

            }
        } else {

            ok = 0;
            // JOptionPane.showMessageDialog(null, "Cliente no encontrado "+ ok);
            // System.out.println("NOT DATA"); 

        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // JOptionPane.showMessageDialog(null, Singleton_App.c);
    return ok;

}

From source file:App.modules.users.Client.Model.dao.Client_DB_DAO.java

/**
 * /*from ww  w.  ja va  2 s . com*/
 */

public static void print_table() {
    DBCursor cursor = null;
    // String rdo = "";
    Client c = new Client();

    Singleton_cli.cli.clear();
    try {
        cursor = Singleton_App.collection.find();
        if (cursor.count() != 0) {

            while (cursor.hasNext()) {
                BasicDBObject document = (BasicDBObject) cursor.next();

                // JOptionPane.showMessageDialog(null, c.toString());
                Singleton_cli.cli.add(c.Client_to_DB(document));
                // JOptionPane.showMessageDialog(null, Singleton_cli.cli.toString());
                // rdo = rdo + (c.getNombre() + " - " + w.getApellidos() + " - " +w.getEdad() + "\n");
            }
        } else {
            System.out.println("NOT DATA");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    //return rdo;   
}

From source file:app.ui.Init.java

public void setTable() {
    String collection = cbDelta.getSelectedItem().toString().trim() + "_formated_"
            + cbOL.getSelectedItem().toString().toLowerCase().replace("-", "");
    collection = collection.replace("rollup", "dice_rollup");
    collection = collection.replace("drilldown", "dice_drilldown_formated");
    DBCollection col = model.getCollection(collection);
    DBCursor cur = col.find();

    String[] columnNames = Util.getAttsNames(collection);
    String[] pseudoColumns = new String[columnNames.length + 1];
    String[] values = new String[columnNames.length + 1];

    for (int i = 0; i < columnNames.length; i++) {
        pseudoColumns[i] = columnNames[i];
    }/*w  w  w.  j a va 2s.  c om*/
    pseudoColumns[pseudoColumns.length - 1] = lsM.getSelectedValue().toString().trim();

    DefaultTableModel model = new DefaultTableModel(pseudoColumns, 0);

    for (int i = 0; i < pseudoColumns.length; i++) {
        pseudoColumns[i] = "_key" + (1 + i);
    }
    pseudoColumns[pseudoColumns.length - 1] = "_value";

    while (cur.hasNext()) {
        DBObject obj = cur.next();

        for (int i = 0; i < values.length - 1; i++) {
            values[i] = (String) obj.get(pseudoColumns[i]);
        }
        values[values.length - 1] = obj.get(pseudoColumns[values.length - 1]).toString();
        /*String cidade = (String) obj.get("CIDADE");
        String uf = (String) obj.get("UF");
        ObjectId id = (ObjectId) obj.get("_id");
        */

        //model.addRow(new Object[]{id, cidade, uf});
        //model.addRow(new Object[]{values});
        Object[] newObj = new Object[values.length];
        //{values}
        for (int i = 0; i < values.length; i++) {
            newObj[i] = values[i];
        }
        model.addRow(newObj);
    }
    cur.close();
    tbCR.setModel(model);
}

From source file:at.tuwien.aic.Main.java

private static void classifyTopic() {
    String topic = getNonEmptyString("Enter a topic you want to query");
    Mongo mongo;//  w ww .  j  av a2s.c  o m
    DB db = null;

    try {
        mongo = new Mongo(_prop.getProperty("db_host"));
        db = mongo.getDB(_prop.getProperty("db_name"));
    } catch (UnknownHostException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }

    Classifier c = ClassifyTweet.loadModel("resources/classifier.model");
    TweetScorer scorer = new TweetScorer();

    DBCollection tweetCollection = db.getCollection("tweets");

    Pattern pattern = Pattern.compile("^.+" + topic + ".+$");
    DBObject query = QueryBuilder.start("text").regex(pattern).get();
    DBCursor resultSet = tweetCollection.find(query);

    int count = 0;
    double value = 0;
    double tweetClassifiedScore = 0;
    double tweetPosUserScore = 0;
    double tweetNegUserScore = 0;

    while (resultSet.hasNext()) {
        try {
            DBObject obj = resultSet.next();
            String tweetText = (String) obj.get("text");

            tweetClassifiedScore += ClassifyTweet.classifyTweet(c, tweetText);
            double score = scorer.scoreTweet(obj);

            if (tweetClassifiedScore > 0) {
                tweetPosUserScore += score;
            } else {
                tweetNegUserScore += score;
            }
            ++count;
        } catch (NumberFormatException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSONException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // Normalizing between 0 an 1
    value = tweetPosUserScore / (tweetPosUserScore + tweetNegUserScore);
    System.out.println("This topic has a sentiment value of: " + value);
}

From source file:backend.facades.UserController.java

public List<UserEntity> getUserList() {
    List<UserEntity> userList = new ArrayList<UserEntity>();
    String sort = "registeredDate";
    String order = "desc";
    DBObject sortCriteria = new BasicDBObject(sort, "desc".equals(order) ? -1 : 1);
    BasicDBObject query = new BasicDBObject();

    DBCursor cursor = userCollection.find(query).sort(sortCriteria);
    try {/*from ww  w .j ava  2 s .c  o  m*/
        while (cursor.hasNext()) {
            DBObject document = cursor.next();
            UserEntity userEntity = new UserEntity();
            userEntity.setId((Long) document.get("_id"));
            userEntity.setUsername((String) document.get("username"));
            userEntity.setEmail((String) document.get("email"));
            userEntity.setFirstname((String) document.get("firstname"));
            userEntity.setPasswd((String) document.get("passwd"));
            userEntity.setLastname((String) document.get("lastname"));
            userEntity.setStatus((Integer) document.get("status"));
            userEntity.setImageId((String) document.get("imageId"));
            userEntity.setRegisteredDate((Date) document.get("registeredDate"));
            userEntity.setLastLoginDate((Date) document.get("lastLoginDate"));
            userEntity.setLanguageCode((String) document.get("languageCode"));
            userEntity.setUserRole((Integer) document.get("userRole"));
            userEntity.setModeratorValue((Integer) document.get("moderator"));
            Integer value = (Integer) document.get("subscribe");
            userEntity.setPersonalWebPage((String) document.get("webpage"));
            if (value != null && value.equals(StatusTypes.ACCEPT_LICENSE)) {
                userEntity.setAcceptSubscr(true);
            } else {
                userEntity.setAcceptSubscr(false);
            }
            userList.add(userEntity);
        }
    } finally {
        cursor.close();
    }
    return userList;
}