Example usage for com.mongodb DBCursor close

List of usage examples for com.mongodb DBCursor close

Introduction

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

Prototype

@Override
    public void close() 

Source Link

Usage

From source file:com.fpt.xml.hth.db.lib.DAO.MovieDAO.java

/**
 * get list movies by param city//from  w  w  w .j a  va2 s.com
 *
 * @param city
 * @return List<MovieTheaterSessionDTO>
 */
public List<MovieTheaterSessionDTO> getAllByCity(String city) {
    connection();
    List<MovieTheaterSessionDTO> lst = new ArrayList<MovieTheaterSessionDTO>();
    DBCollection collection = movieCollection;

    BasicDBObject dbObject = new BasicDBObject();
    dbObject.append("theaters", new BasicDBObject("$elemMatch", new BasicDBObject("theater.city", city)));

    DBCursor cursor = collection.find(dbObject);

    while (cursor.hasNext()) {
        BasicDBObject basic = (BasicDBObject) cursor.next();
        MovieTheaterSessionDTO movieDto = converter.convertBasicObjectToModel(basic);
        //            List<TheaterSessionDTO> lstTheaterSession = new ArrayList<TheaterSessionDTO>();
        //            if (city != null && !city.isEmpty()) {
        //                for (TheaterSessionDTO theaterDTO : movieDto.getTheaters()) {
        //                    if (theaterDTO.getTheater().getCity().equals(city)) {                
        //                        lstTheaterSession.add(theaterDTO);
        //                    }
        //                }
        //            }
        //            movieDto.setTheaters(lstTheaterSession);
        lst.add(movieDto);
    }
    cursor.close();
    mongoClient.close();
    return lst;
}

From source file:com.gatf.executor.dataprovider.MongoDBTestDataSource.java

License:Apache License

public List<Map<String, String>> provide(GatfTestDataProvider provider, AcceptanceTestContext context) {

    List<Map<String, String>> result = new ArrayList<Map<String, String>>();

    Assert.assertNotNull("provider cannot be null", provider);
    Assert.assertTrue("provider cannot be null", provider.getArgs() != null && provider.getArgs().length > 0);
    Assert.assertNotNull("mongodb-collection cannot be empty", provider.getArgs()[0]);
    Assert.assertNotNull("queryString cannot be empty", provider.getQueryStr());
    Assert.assertNotNull("variableNames cannot be empty", provider.getSourceProperties());
    Assert.assertNotNull("propertyNames cannot be empty", provider.getProviderProperties());

    String dbName = args[2].trim();
    String collName = provider.getArgs()[0].trim();
    String queryString = provider.getQueryStr().trim();
    String variableNames = provider.getProviderProperties();
    String propertyNames = provider.getSourceProperties();

    Assert.assertNotNull("mongodb-collection cannot be empty", collName.isEmpty());
    Assert.assertFalse("queryString cannot be empty", queryString.isEmpty());

    List<String> variableNamesArr = new ArrayList<String>();
    for (String varName : variableNames.split(",")) {
        if (!varName.trim().isEmpty()) {
            variableNamesArr.add(varName);
        }// w  w  w. j  a  v a 2s  .co  m
    }
    Assert.assertTrue("need to define at-least a single variable name",
            !variableNames.isEmpty() && variableNames.split(",").length > 0 && variableNamesArr.size() > 0);

    List<String> propertyNamesArr = new ArrayList<String>();
    for (String varName : propertyNames.split(",")) {
        if (!varName.trim().isEmpty()) {
            propertyNamesArr.add(varName);
        }
    }
    Assert.assertTrue("need to define at-least a single property name",
            !propertyNames.isEmpty() && propertyNames.split(",").length > 0 && propertyNamesArr.size() > 0);

    Assert.assertTrue("property name and variable name sizes don't match",
            propertyNamesArr.size() == variableNamesArr.size());

    StringBuilder build = new StringBuilder();
    build.append("Provider configuration [\n");
    build.append(String.format("dataSource name is %s\n", getDataSourceName()));
    build.append(String.format("mongodb-collection is %s\n", collName));
    build.append(String.format("queryString is %s\n", queryString));
    build.append(String.format("propertyNames is %s\n", propertyNames));
    build.append(String.format("variableNames is %s]", variableNames));
    logger.info(build.toString());

    Resource res = null;
    try {

        res = getResource();
        MongoClient mongoClient = (MongoClient) res.object;

        DB db = null;
        try {
            db = mongoClient.getDB(dbName);

            DBCollection coll = db.getCollection(collName);
            Assert.assertNotNull(String.format("Mongodb collection %s not found", collName), coll);

            DBObject queryObject = null;
            try {
                queryObject = (DBObject) JSON.parse(queryString);
            } catch (Exception e) {
                Assert.assertNotNull("queryString passed is invalid");
            }

            DBCursor cursor = null;
            try {
                cursor = coll.find(queryObject);
                while (cursor.hasNext()) {
                    DBObject object = cursor.next();
                    Map<String, String> row = new HashMap<String, String>();
                    for (int i = 0; i < variableNamesArr.size(); i++) {
                        Assert.assertTrue(
                                String.format("Could not find %s field in the result document returned",
                                        propertyNamesArr.get(i)),
                                object.containsField(propertyNamesArr.get(i)));
                        row.put(variableNamesArr.get(i), object.get(propertyNamesArr.get(i)).toString());
                    }
                    result.add(row);
                }
            } catch (Exception e) {
                throw new AssertionError(e);
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        } catch (Exception e) {
            throw new AssertionError(
                    String.format("Fetching Test Data failed while executing query %s with the error %s",
                            queryString, ExceptionUtils.getStackTrace(e)));
        } finally {
            if (mongoClient != null)
                mongoClient.close();
        }
    } catch (Exception e) {
        throw new AssertionError(
                String.format("Fetching Test Data failed while executing query %s with the error %s",
                        queryString, ExceptionUtils.getStackTrace(e)));
    } finally {
        if (res != null)
            releaseToPool(res);
    }
    return result;
}

From source file:com.gederin.blog.dao.BlogPostDAO.java

License:Apache License

public List<DBObject> findByDateDescending(int limit) {

    List<DBObject> posts = null;
    posts = new ArrayList<DBObject>();
    DBCursor dbCursor = this.postsCollection.find().sort(new BasicDBObject("date", -1)).limit(limit);
    try {//from  w w  w.j  a  v  a  2  s.co m
        while (dbCursor.hasNext()) {
            DBObject dbObject = dbCursor.next();
            posts.add(dbObject);
        }
    } finally {
        dbCursor.close();
    }
    // XXX HW 3.2,  Work Here
    // Return a list of DBObjects, each one a post from the posts collection

    return posts;
}

From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Apache License

public List<MongoField> discoverFields(String db, String collection, String query, String fields,
        boolean isPipeline, int docsToSample) throws KettleException {
    DBCursor cursor = null;
    try {// www  .  j  a  v  a 2s.c o m
        int numDocsToSample = docsToSample;
        if (numDocsToSample < 1) {
            numDocsToSample = 100; // default
        }

        List<MongoField> discoveredFields = new ArrayList<MongoField>();
        Map<String, MongoField> fieldLookup = new HashMap<String, MongoField>();
        try {
            DB database = getDb(db);

            if (Const.isEmpty(collection)) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "MongoNoAuthWrapper.ErrorMessage.NoCollectionSpecified")); //$NON-NLS-1$
            }
            DBCollection dbcollection = database.getCollection(collection);

            Iterator<DBObject> pipeSample = null;

            if (isPipeline) {
                pipeSample = setUpPipelineSample(query, numDocsToSample, dbcollection);
            } else {
                if (Const.isEmpty(query) && Const.isEmpty(fields)) {
                    cursor = dbcollection.find().limit(numDocsToSample);
                } else {
                    DBObject dbObject = (DBObject) JSON.parse(Const.isEmpty(query) ? "{}" //$NON-NLS-1$
                            : query);
                    DBObject dbObject2 = (DBObject) JSON.parse(fields);
                    cursor = dbcollection.find(dbObject, dbObject2).limit(numDocsToSample);
                }
            }

            int actualCount = 0;
            while (cursor != null ? cursor.hasNext() : pipeSample.hasNext()) {
                actualCount++;
                DBObject nextDoc = (cursor != null ? cursor.next() : pipeSample.next());
                docToFields(nextDoc, fieldLookup);
            }

            postProcessPaths(fieldLookup, discoveredFields, actualCount);

            return discoveredFields;
        } catch (Exception e) {
            throw new KettleException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } catch (Exception ex) {
        if (ex instanceof KettleException) {
            throw (KettleException) ex;
        } else {
            throw new KettleException(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.ErrorMessage.UnableToDiscoverFields"), ex); //$NON-NLS-1$
        }
    }
}

From source file:com.groupon.jenkins.mongo.MongoRepository.java

License:Open Source License

protected <T> Iterable<T> find(DBObject query, DBObject fields, DBObject sort, Integer limit,
        Function<DBObject, T> transformer) {
    MongoClient client = getClient();/* w  w  w  .j av a  2  s  .  c  o m*/
    try {
        DBCursor cursor = fields == null ? getCollection(client).find(query)
                : getCollection(client).find(query, fields);
        if (sort != null) {
            cursor = cursor.sort(sort);
        }
        if (limit != null) {
            cursor = cursor.limit(limit);
        }
        List<T> result = new LinkedList<T>();

        try {
            while (cursor.hasNext()) {
                result.add(transformer.apply(cursor.next()));
            }
        } finally {
            cursor.close();
        }

        return result;
    } finally {
        client.close();
    }
}

From source file:com.hangum.tadpole.mongodb.core.composite.result.MongodbResultComposite.java

License:Open Source License

/**
 *   ? ? .//from   ww  w .  j av a2  s  . com
 * 
 * @param basicFields
 * @param basicWhere
 * @param basicSort
 */
private void find(BasicDBObject basicFields, DBObject basicWhere, BasicDBObject basicSort, int cntSkip,
        int cntLimit) throws Exception {
    if ((cntLimit - cntSkip) >= defaultMaxCount) {
        //         "  " + defaultMaxCount + " ? . Prefernece? ? ."
        //         Search can not exceed the number 5. Set in Perference.
        throw new Exception(String.format(Messages.MongoDBTableEditor_0, "" + defaultMaxCount)); //$NON-NLS-2$ //$NON-NLS-1$
    }

    DB mongoDB = MongoDBQuery.findDB(userDB);
    DBCollection dbCollection = MongoDBQuery.findCollection(userDB, collectionName);

    // ?? 
    DBCursor dbCursor = null;
    try {
        if (cntSkip > 0 && cntLimit > 0) {

            dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort).skip(cntSkip).limit(cntLimit);

        } else if (cntSkip == 0 && cntLimit > 0) {

            dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort).limit(cntLimit);
        } else {
            dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort);
        }

        DBObject explainDBObject = dbCursor.explain();
        sbConsoleExecuteMsg.append(JSONUtil.getPretty(explainDBObject.toString())).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sbConsoleErrorMsg.append(JSONUtil.getPretty(mongoDB.getLastError().toString())).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$

        mongoDB.forceError();
        mongoDB.resetError();

        //           if(logger.isDebugEnabled()) logger.debug(sbConsoleMsg);

        //  ?? .
        refreshDBView(dbCursor, dbCursor.count());

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

From source file:com.hangum.tadpole.mongodb.core.dialogs.users.UserManagerDialog.java

License:Open Source License

/**
 * table data//from   ww  w  .j  a  v  a 2 s  .c  o m
 */
private void initTable() {
    listUser.clear();
    DBCursor userCursor = null;

    try {
        userCursor = MongoDBQuery.getUser(userDB);
        for (DBObject dbObject : userCursor) {
            UserDTO user = new UserDTO();
            user.setId(dbObject.get("user").toString()); //$NON-NLS-1$
            user.setReadOnly(dbObject.get("readOnly").toString()); //$NON-NLS-1$

            listUser.add(user);
        }

        tableViewerUser.refresh();

    } catch (Exception e) {
        logger.error("mongodb user list", e); //$NON-NLS-1$

        Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
        ExceptionDetailsErrorDialog.openError(null, "Error", "Get User Exception", errStatus); //$NON-NLS-1$ //$NON-NLS-2$
    } finally {
        if (userCursor != null)
            userCursor.close();
    }

}

From source file:com.hangum.tadpole.mongodb.core.editors.main.MongoDBTableEditor.java

License:Open Source License

/**
 *   ? ? .//from   w ww.j a  va2  s  . c  o m
 * 
 * @param basicFields
 * @param basicWhere
 * @param basicSort
 */
private void find(BasicDBObject basicFields, DBObject basicWhere, BasicDBObject basicSort, int cntSkip,
        int cntLimit) throws Exception {
    if ((cntLimit - cntSkip) >= defaultMaxCount) {

        //         "  " + defaultMaxCount + " ? . Prefernece? ? ."
        //         Search can not exceed the number 5. Set in Perference.
        throw new Exception(String.format(Messages.MongoDBTableEditor_0, "" + defaultMaxCount)); //$NON-NLS-2$
    }

    mapColumns = new HashMap<Integer, String>();
    sourceDataList = new ArrayList<HashMap<Integer, Object>>();

    DB mongoDB = MongoConnectionManager.getInstance(userDB);
    DBCollection dbCollection = mongoDB.getCollection(tableName);

    // ?? 
    DBCursor dbCursor = null;
    try {
        if (cntSkip > 0 && cntLimit > 0) {

            sbConsoleMsg.append("############[query]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Fields]" + basicFields.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Where]" + basicWhere.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Sort] " + basicSort.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Skip]" + cntSkip).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Limit]" + cntLimit).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("############[query]#####################"); //$NON-NLS-1$

            dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort).skip(cntSkip).limit(cntLimit);

        } else if (cntSkip == 0 && cntLimit > 0) {

            sbConsoleMsg.append("############[query]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Fields]" + basicFields.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Where]" + basicWhere.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Sort] " + basicSort.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Limit]" + cntLimit).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("############[query]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$

            dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort).limit(cntLimit);
        } else {
            sbConsoleMsg.append("############[query]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Fields]" + basicFields.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Where]" + basicWhere.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("[Sort] " + basicSort.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
            sbConsoleMsg.append("############[query]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$

            dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort);
        }

        DBObject explainDBObject = dbCursor.explain();
        sbConsoleMsg.append("############[result]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sbConsoleMsg.append("[query explain]\r\n" + JSONUtil.getPretty(explainDBObject.toString())) //$NON-NLS-1$
                .append("\r\n"); //$NON-NLS-1$
        sbConsoleMsg.append("[error]\r\n" + JSONUtil.getPretty(mongoDB.getLastError().toString())) //$NON-NLS-1$
                .append("\r\n"); //$NON-NLS-1$
        sbConsoleMsg.append("############[result]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$

        mongoDB.forceError();
        mongoDB.resetError();

        if (logger.isDebugEnabled())
            logger.debug(sbConsoleMsg);

        //  ?? .
        int totCnt = 0;
        listTrees = new ArrayList<MongodbTreeViewDTO>();

        for (DBObject dbObject : dbCursor) {
            //      ?  ?
            if (mapColumns.size() == 0)
                mapColumns = MongoDBTableColumn.getTabelColumnView(dbObject);

            // append tree text columnInfo.get(key)
            MongodbTreeViewDTO treeDto = new MongodbTreeViewDTO(dbObject, "(" + totCnt + ") {..}", "", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                    "Document"); //$NON-NLS-1$
            parserTreeObject(dbObject, treeDto, dbObject);
            listTrees.add(treeDto);

            // append table text
            HashMap<Integer, Object> dataMap = new HashMap<Integer, Object>();
            for (int i = 0; i < mapColumns.size(); i++) {

                Object keyVal = dbObject.get(mapColumns.get(i));
                if (keyVal == null)
                    dataMap.put(i, ""); //$NON-NLS-1$
                else
                    dataMap.put(i, keyVal.toString());
            }
            // ??  ? ?   id
            dataMap.put(MongoDBDefine.PRIMARY_ID_KEY, dbObject);
            sourceDataList.add(dataMap);

            // append row text
            totCnt++;
        }
        txtCnt = dbCursor.count() + "/" + totCnt + Messages.MongoDBTableEditor_69; //$NON-NLS-1$
    } finally {
        if (dbCursor != null)
            dbCursor.close();
    }
}

From source file:com.ibm.bluemix.smartveggie.dao.SubOutletVendorAllocationDaoImpl.java

@Override
public List<BasicDBObject> retrieveAllocatedSubOutlet() {

    List<BasicDBObject> listDBObjects = null;
    try {//  w  w  w  . jav a 2s . co m
        System.out.println("Retrieving Allocated SubOutlets...");
        listDBObjects = new ArrayList<BasicDBObject>();
        DB db = MongodbConnection.getMongoDB();
        DBCollection col = db.getCollection(ICollectionName.COLLECTION_ALLOC_SUBOUTLETS);
        DBCursor cursor = col.find();
        BasicDBObject obj = null;
        while (cursor.hasNext()) {
            obj = (BasicDBObject) cursor.next();
            System.out.println("Retrieved: " + obj);
            listDBObjects.add(obj);
        }
        cursor.close();
    } catch (Exception e) {
        throw e;
    }
    return listDBObjects;
}

From source file:com.ibm.bluemix.smartveggie.dao.SubOutletVendorAllocationDaoImpl.java

@Override
public BasicDBObject deallocatedSubOutlet(SubOutletVendorAllocationDTO subOutletVendorAllocationDTO) {
    try {// ww  w .ja  v a2 s  .  c  om
        System.out.println("starting object delete..");
        DB db = MongodbConnection.getMongoDB();
        BasicDBObject query = new BasicDBObject();
        if (subOutletVendorAllocationDTO != null) {
            if (subOutletVendorAllocationDTO.getVendorUsername() != null
                    && !subOutletVendorAllocationDTO.getVendorUsername().equalsIgnoreCase("")) {
                query.append("vendorUsername", subOutletVendorAllocationDTO.getVendorUsername());
            }
            if (subOutletVendorAllocationDTO.getSmartCityCode() != null
                    && !subOutletVendorAllocationDTO.getSmartCityCode().equalsIgnoreCase("")) {
                query.append("smartCityCode", subOutletVendorAllocationDTO.getSmartCityCode());
            }
            if (subOutletVendorAllocationDTO.getSmartOutletCode() != null
                    && !subOutletVendorAllocationDTO.getSmartOutletCode().equalsIgnoreCase("")) {
                query.append("smartOutletCode", subOutletVendorAllocationDTO.getSmartOutletCode());
            }
            if (subOutletVendorAllocationDTO.getSuboutletCode() != null
                    && !subOutletVendorAllocationDTO.getSuboutletCode().equalsIgnoreCase("")) {
                query.append("suboutletCode", subOutletVendorAllocationDTO.getSuboutletCode());
            }
            if (subOutletVendorAllocationDTO.getSuboutletAllocatedFrom() != null
                    && !subOutletVendorAllocationDTO.getSuboutletAllocatedFrom().equalsIgnoreCase("")) {
                query.append("suboutletAllocatedFrom",
                        subOutletVendorAllocationDTO.getSuboutletAllocatedFrom());
            }
            if (subOutletVendorAllocationDTO.getSuboutletAllocatedTo() != null
                    && !subOutletVendorAllocationDTO.getSuboutletAllocatedTo().equalsIgnoreCase("")) {
                query.append("suboutletAllocatedTo", subOutletVendorAllocationDTO.getSuboutletAllocatedTo());
            }
        }
        System.out.println("Querying for Delete: " + query);
        DBCollection col = db.getCollection(ICollectionName.COLLECTION_ALLOC_SUBOUTLETS);
        DBCursor cursor = col.find(query);
        BasicDBObject obj = null;
        while (cursor.hasNext()) {
            obj = (BasicDBObject) cursor.next();
            System.out.println("Retrieved Allocated Vendor manager outlet: " + obj);
        }
        col.remove(query);
        cursor.close();
        return obj;
    } catch (Exception e) {
        throw e;
    }
}