Example usage for com.mongodb.client MongoCursor close

List of usage examples for com.mongodb.client MongoCursor close

Introduction

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

Prototype

@Override
    void close();

Source Link

Usage

From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T> List<T> search(String unitName, Class<T> cls, Criteria criteria, List<String> orderBy,
        Integer limit) {//w  ww .  j ava 2s .com
    SerializationDefinition def = SerializationDefinition.get(cls);
    if (def == null)
        throw new RuntimeException("Cannot find SerializationDefinition for " + cls.getSimpleName());

    MongoDatabase db = mongoClient.getDatabase(databaseName);

    FindIterable<Document> query = criteria == null ? db.getCollection(unitName).find()
            : db.getCollection(unitName).find(criteria.convert(new FilterQueryBuilder()));

    if (orderBy != null && !orderBy.isEmpty())
        if (orderBy.size() == 1)
            query = query.sort(orderBy(orderBy.get(0)));
        else {
            List<Bson> ob = new ArrayList<>();
            for (String s : orderBy)
                ob.add(orderBy(s));
            query = query.sort(Sorts.orderBy(ob));
        }

    List<T> result = new ArrayList<>();
    MongoCursor<Document> cursor = query.limit(limit).iterator();
    try {
        while (cursor.hasNext()) {
            T item = (T) def.newInstance();
            def.read(cursor.next(), item);
            result.add(item);
        }
    } finally {
        cursor.close();
    }

    return result;
}

From source file:com.sitewhere.event.persistence.mongodb.MongoDeviceEventManagement.java

License:Open Source License

@Override
public ISearchResults<IDeviceEvent> listDeviceEvents(IDeviceAssignment assignment,
        IDateRangeSearchCriteria criteria) throws SiteWhereException {
    MongoCollection<Document> events = getMongoClient().getEventsCollection();
    Document query = new Document(MongoDeviceEvent.PROP_DEVICE_ASSIGNMENT_ID, assignment.getId());
    MongoPersistence.addDateSearchCriteria(query, MongoDeviceEvent.PROP_EVENT_DATE, criteria);
    Document sort = new Document(MongoDeviceEvent.PROP_EVENT_DATE, -1)
            .append(MongoDeviceEvent.PROP_RECEIVED_DATE, -1);

    int offset = Math.max(0, criteria.getPageNumber() - 1) * criteria.getPageSize();
    FindIterable<Document> found = events.find(query).skip(offset).limit(criteria.getPageSize()).sort(sort);
    MongoCursor<Document> cursor = found.iterator();

    List<IDeviceEvent> matches = new ArrayList<IDeviceEvent>();
    SearchResults<IDeviceEvent> results = new SearchResults<IDeviceEvent>(matches);
    try {//  w w w  .  j av a 2s.com
        results.setNumResults(events.count(query));
        while (cursor.hasNext()) {
            Document match = cursor.next();
            matches.add(MongoDeviceEventManagementPersistence.unmarshalEvent(match));
        }
    } finally {
        cursor.close();
    }
    return results;
}

From source file:com.sitewhere.user.persistence.mongodb.MongoUserManagement.java

License:Open Source License

@Override
public List<IUser> listUsers(IUserSearchCriteria criteria) throws SiteWhereException {
    try {/* ww  w . j  a v  a 2  s.  co m*/
        MongoCollection<Document> users = getMongoClient().getUsersCollection();
        Document dbCriteria = new Document();
        if (!criteria.isIncludeDeleted()) {
            MongoSiteWhereEntity.setDeleted(dbCriteria, false);
        }
        FindIterable<Document> found = users.find(dbCriteria)
                .sort(new BasicDBObject(MongoUser.PROP_USERNAME, 1));
        MongoCursor<Document> cursor = found.iterator();

        List<IUser> matches = new ArrayList<IUser>();
        try {
            while (cursor.hasNext()) {
                Document match = cursor.next();
                matches.add(MongoUser.fromDocument(match));
            }
        } finally {
            cursor.close();
        }
        return matches;
    } catch (MongoTimeoutException e) {
        throw new SiteWhereException("Connection to MongoDB lost.", e);
    }
}

From source file:com.sitewhere.user.persistence.mongodb.MongoUserManagement.java

License:Open Source License

@Override
public List<IGrantedAuthority> listGrantedAuthorities(IGrantedAuthoritySearchCriteria criteria)
        throws SiteWhereException {
    try {/*from   w  ww. j a  v a2  s .  c om*/
        MongoCollection<Document> auths = getMongoClient().getAuthoritiesCollection();
        FindIterable<Document> found = auths.find()
                .sort(new BasicDBObject(MongoGrantedAuthority.PROP_AUTHORITY, 1));
        MongoCursor<Document> cursor = found.iterator();

        List<IGrantedAuthority> matches = new ArrayList<IGrantedAuthority>();
        try {
            while (cursor.hasNext()) {
                Document match = cursor.next();
                matches.add(MongoGrantedAuthority.fromDBObject(match));
            }
        } finally {
            cursor.close();
        }
        return matches;
    } catch (MongoTimeoutException e) {
        throw new SiteWhereException("Connection to MongoDB lost.", e);
    }
}

From source file:com.yahoo.ycsb.db3.MongoDbClient.java

License:Open Source License

/**
 * Perform a range scan for a set of records in the database. Each field/value
 * pair from the result will be stored in a HashMap.
 * /*from  w w w  .  j a v  a 2  s .  c  o m*/
 * @param table
 *          The name of the table
 * @param startkey
 *          The record key of the first record to read.
 * @param recordcount
 *          The number of records to read
 * @param fields
 *          The list of fields to read, or null for all of them
 * @param result
 *          A Vector of HashMaps, where each HashMap is a set field/value
 *          pairs for one record
 * @return Zero on success, a non-zero error code on error. See the {@link DB}
 *         class's description for a discussion of error codes.
 */
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
        Vector<HashMap<String, ByteIterator>> result) {
    MongoCursor<Document> cursor = null;
    try {
        MongoCollection<Document> collection = database.getCollection(table);

        Document scanRange = new Document("$gte", startkey);
        Document query = new Document("_id", scanRange);
        Document sort = new Document("_id", INCLUDE);

        FindIterable<Document> findIterable = collection.find(query).sort(sort).limit(recordcount);

        if (fields != null) {
            Document projection = new Document();
            for (String fieldName : fields) {
                projection.put(fieldName, INCLUDE);
            }
            findIterable.projection(projection);
        }

        cursor = findIterable.iterator();

        if (!cursor.hasNext()) {
            System.err.println("Nothing found in scan for key " + startkey);
            return Status.ERROR;
        }

        result.ensureCapacity(recordcount);

        while (cursor.hasNext()) {
            HashMap<String, ByteIterator> resultMap = new HashMap<String, ByteIterator>();

            Document obj = cursor.next();
            fillMap(resultMap, obj);

            result.add(resultMap);
        }

        return Status.OK;
    } catch (Exception e) {
        System.err.println(e.toString());
        return Status.ERROR;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:course.homework.Homework3.java

License:Apache License

public static void main(String[] args) {

    MongoClient client = new MongoClient();
    MongoDatabase database = client.getDatabase("school");
    MongoCollection<Document> collection = database.getCollection("students");

    MongoCursor<Document> iterator = collection.find().iterator();
    while (iterator.hasNext()) {
        Document doc = iterator.next();
        List<Document> scores = (List<Document>) doc.get("scores");

        Optional<Document> bestHomeWork = scores.stream()
                .max((a, b) -> a.getString("type").equals("homework") && b.getString("type").equals("homework")
                        ? Double.compare(a.getDouble("score"), b.getDouble("score"))
                        : -1);/*from  w w  w  .j av  a 2s.co  m*/
        Double bestScore = bestHomeWork.get().getDouble("score");

        List<Document> result = scores.stream()
                .filter(x -> !x.getString("type").equals("homework") || x.getDouble("score").equals(bestScore))
                .collect(Collectors.toList());

        collection.updateOne(eq("_id", doc.get("_id")), new Document("$set", new Document("scores", result)));

    }
    iterator.close();
    client.close();

}

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

License:Apache License

public static void main(final String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase numbersDB = client.getDatabase("students");
    MongoCollection<Document> grades = numbersDB.getCollection("grades");

    MongoCursor<Document> cursor = grades.find(eq("type", "homework")).sort(ascending("student_id", "score"))
            .iterator();/*  www. ja  v a 2  s .  co  m*/

    Object studentId = -1;
    try {
        while (cursor.hasNext()) {
            Document entry = cursor.next();
            if (!entry.get("student_id").equals(studentId)) {
                System.out.println("Removing: " + entry);
                Object id = entry.get("_id");
                grades.deleteOne(eq("_id", id));

            }
            studentId = entry.get("student_id");
        }
    } finally {
        cursor.close();
    }
}

From source file:Dao.AccessDataNOSQL.java

License:Open Source License

/**
 * Mtodo para cargar en memoria las calificaciones
 *//*from  w  w w  .j  a v  a2 s.c o m*/
@Override
public void cargarEventosDAO() {
    MongoCollection<Document> collec = consultaBD("nosql", "ratings");
    MongoCursor<Document> cursor = collec.find().iterator();

    while (cursor.hasNext()) {
        try {
            String stringjson = cursor.next().toJson();
            JSONObject obj1 = new JSONObject(stringjson);

            String userId = obj1.getString("userId");
            String movieID = obj1.getString("movieId");
            String rating = obj1.getString("rating");
            String timestamp = obj1.getString("timestamp");

            User u = new User(Integer.parseInt(userId));
            Item i = new Movie(Integer.parseInt(movieID));

            double rat = Double.parseDouble(rating);
            int tim = Integer.parseInt(timestamp);

            Events evento = new Events(u, (Movie) i, rat, tim);
            getEventsDAO().add(evento);

        } catch (JSONException ex) {
            Logger.getLogger(AccessDataNOSQL.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    cursor.close();
}

From source file:Dao.AccessDataNOSQL.java

License:Open Source License

/**
 * Metodo para cargar en memoria los elementos
 *
 */// w w  w.j av  a2s .c  o m
@Override
public void cargarItemsDAO() {
    MongoCollection<Document> collec = consultaBD("nosql", "movies");

    MongoCursor<Document> cursor = collec.find().iterator();
    while (cursor.hasNext()) {
        try {
            String stringjson = cursor.next().toJson();
            //JsonReader jr=new JsonReader(stringjson);
            JSONObject obj1 = new JSONObject(stringjson);
            String movieId = obj1.getString("movieId");
            String title = obj1.getString("title");
            String genres = obj1.getString("genres");

            Movie peli = new Movie();
            peli.setId(Integer.parseInt(movieId));
            peli.setTitle(title);
            peli.setGenre(genres);

            getItemsDAO().add(peli);
        } catch (JSONException ex) {
            Logger.getLogger(AccessDataNOSQL.class.getName()).log(Level.SEVERE, null, ex);
            System.err.print("error en cargarItemsDAO en AccesoNoSQL");
        }
    }
    cursor.close();
}

From source file:Dao.AccessDataNOSQL.java

License:Open Source License

/**
 * Mtodo para cargar en memoria los usuarios
 *//*from w ww. ja va  2s .  c o  m*/
@Override
public void cargarUserDAO() {
    MongoCollection<Document> collec = consultaBD("nosql", "ratings");
    MongoCursor<Document> cursor = collec.find().iterator();

    while (cursor.hasNext()) {
        try {
            String stringjson = cursor.next().toJson();
            JSONObject obj1 = new JSONObject(stringjson);

            String userId = obj1.getString("userId");
            User u = new User();
            //Integer.parseInt(userId);
            u.setUserId(Integer.parseInt(userId));
            getUserDAO().add(u);

        } catch (JSONException ex) {
            Logger.getLogger(AccessDataNOSQL.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    cursor.close();
}