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:buysell.shopping.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:

    try {/*from   w  w  w  .  ja  va 2  s . c om*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("buysale");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("assetes");
        System.out.println("Collection created successfully");
        //String name = jTextField1.getText().toString();
        //String email = jTextField2.getText().toString();
        //String phoneno = jTextField3.getText().toString();
        // String price= jTextField4.getText().toString();
        //String photourl = jTextField5.getText().toString();
        String check = jCheckBox1.getText().toString();
        System.out.println(check);
        String type = jComboBox1.getSelectedItem().toString();
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("type", type);
        DBCursor cursor = coll.find(searchQuery);
        int i = 0;
        while (cursor.hasNext() && i != 1) {
            i++;
            DBObject obj = cursor.next();
            String name = (String) obj.get("name");
            String email = (String) obj.get("email");
            String phoneno = (String) obj.get("phoneno");
            String price = (String) obj.get("price");
            String url = (String) obj.get("photourl");
            jTextField1.setText(name);
            jTextField2.setText(email);
            jTextField3.setText(phoneno);
            jTextField4.setText(price);
            jLabel3.setIcon(new javax.swing.ImageIcon(url));
        }

        System.out.println("Document inserted successfully");
    } catch (NumberFormatException e) {
        System.out.println();
    }
}

From source file:buysell.subads.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {// w  w w.j  av a2s  .  co m
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("buysale");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("assetes");
        System.out.println("Collection created successfully");
        String name = jTextField1.getText().toString();
        String email = jTextField2.getText().toString();
        String phoneno = jTextField3.getText().toString();
        String price = jTextField4.getText().toString();
        String photourl = jTextField5.getText().toString();
        String type = jComboBox1.getSelectedItem().toString();
        DB dB = mongoClient.getDB("snehal");
        System.out.println("Connect to database successfully");
        DBCollection colle = dB.getCollection("user");
        System.out.println("Collection created successfully");
        String uname = jTextField6.getText().toString();
        String passwd = jPasswordField1.getText().toString();
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", uname);
        searchQuery.put("passwd", passwd);

        DBCursor cursor = colle.find(searchQuery);
        int i = 0;
        while (cursor.hasNext()) {
            i = 1;
            System.out.println(cursor.next());
        }
        if (i == 0) {
            JOptionPane.showMessageDialog(null, "user name or passwod is wrong");

        } else {
            if (jTextField2.getText().length() != 0 && jTextField3.getText().length() != 0
                    && jTextField4.getText().length() != 0 && jTextField1.getText().length() != 0
                    && jTextField5.getText().length() != 0) {

                BasicDBObject doc = new BasicDBObject("name", name).append("username", uname)
                        .append("passwd", passwd).append("email", email).append("phoneno", phoneno)
                        .append("price", price).append("type", type).append("photourl", photourl);

                coll.insert(doc);
                home h2 = new home();
                h2.setVisible(true);
                dispose();
                System.out.println("Document inserted successfully");
            } else {
                JOptionPane.showMessageDialog(null, "enter the every field");
            }
        }

    } catch (NumberFormatException e) {
        System.out.println();
    }
}

From source file:CapaDato.Conexion.java

public static void main(String[] Args) throws UnknownHostException {
    try {/*from w ww . j  ava2  s . c o m*/
        // Para conectarse al servidor MongoDB
        MongoClient conexion = new MongoClient("localhost", 27017);
        // Ahora conectarse a bases de datos
        DB ejemplo = conexion.getDB("Ejemplo");
        System.out.println("Conectarse a la base de datos exitoso");
        DBCollection coleccion = ejemplo.getCollection("Alumno");
        //             Set<String> collectionNames = ejemplo.getCollectionNames();
        //            for (final String s : collectionNames) 
        //            {
        //            System.out.println(s);
        //            }
        //Para consultar otro mtodo
        Object objeto = new Object();
        objeto = "null,{nombre:1}";
        DBCursor cursor = coleccion.find();

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

        //DBObject doc = coleccion.findOne();

        //Para consultar
        //DBCursor cursor = coleccion.find ();
        //System.out.println(cursor);
        //            int i = 1;
        //          while (cursor.hasNext ()) 
        //          { 
        //             System.out.println ("insertado documento:" + i); 
        //             System.out.println (cursor.next ()); 
        //             i ++;
        //          }

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

}

From source file:carrental.beans.billing.BillingBean.java

private int generateInvoiceNumber() throws Exception {
    DBCursor dbCursor = mongoConfig.mongo().getDB("carrental").getCollection("invoice").find()
            .sort(new BasicDBObject("number", -1)).limit(1);
    if (dbCursor.hasNext())
        return ((Integer) dbCursor.next().get("number")) + 1;
    return 1;/*from  www  .  j a  v a  2 s.c  o m*/
}

From source file:cc.acs.mongofs.gridfs.GridFS.java

License:Apache License

public List<GridFSDBFile> find(DBObject query) {
    List<GridFSDBFile> files = new ArrayList<GridFSDBFile>();

    DBCursor c = _filesCollection.find(query);
    while (c.hasNext()) {
        files.add(_fix(c.next()));// ww  w.ja  v  a 2  s. com
    }
    return files;
}

From source file:ch.agent.crnickl.mongodb.ReadMethodsForChroniclesAndSeries.java

License:Apache License

public Collection<Chronicle> getChroniclesByParent(Chronicle parent) throws T2DBException {
    Collection<Chronicle> result = new ArrayList<Chronicle>();
    if (check(Permission.DISCOVER, parent, false)) {
        try {/*  w w w .  j  a  v  a  2 s .c  o m*/
            Database db = parent.getDatabase();
            DBCursor cursor = getMongoDB(db).getChronicles()
                    .find(mongoObject(MongoDatabase.FLD_CHRON_PARENT, getIdOrZero(parent)));
            try {
                while (cursor.hasNext()) {
                    Chronicle chronicle = unpack(db, (BasicDBObject) cursor.next());
                    check(Permission.READ, chronicle);
                    result.add(chronicle);
                }
            } finally {
                cursor.close();
            }
        } catch (Exception e) {
            throw T2DBMsg.exception(e, E.E40122, parent.getName(true));
        }
    }
    return result;
}

From source file:ch.agent.crnickl.mongodb.ReadMethodsForChroniclesAndSeries.java

License:Apache License

/**
 * The method completes the attribute with the value found for one of the
 * entities in the list and returns true. If no value was found, the method
 * return false. If more than value was found, the one selected corresponds
 * to the first entity encountered in the list.
 * /*from   w w w.ja  va 2 s.  co m*/
 * @param chronicles a list of chronicles
 * @param attribute an attribute 
 * @return true if any value found
 * @throws T2DBException
 */
public boolean getAttributeValue(List<Chronicle> chronicles, Attribute<?> attribute) throws T2DBException {
    boolean found = false;
    Surrogate s = attribute.getProperty().getSurrogate();
    Database db = s.getDatabase();
    try {
        ObjectId[] chrOids = new ObjectId[chronicles.size()];
        int offset = 0;
        for (Chronicle chronicle : chronicles) {
            chrOids[offset++] = getId(chronicle);
        }
        DBCursor cursor = getMongoDB(db).getAttributes().find(mongoObject(MongoDatabase.FLD_ATTR_PROP, getId(s),
                MongoDatabase.FLD_ATTR_CHRON, mongoObject(Operator.IN.op(), chrOids)));

        offset = Integer.MAX_VALUE;
        BasicDBObject objAtOffset = null;

        while (cursor.hasNext()) {
            BasicDBObject obj = (BasicDBObject) cursor.next();
            ObjectId chrOid = obj.getObjectId(MongoDatabase.FLD_ATTR_CHRON);
            int offset1 = findOffset(chrOid, chronicles);
            if (offset1 < offset) {
                offset = offset1;
                objAtOffset = obj;
            }
            if (offset == 0)
                break;
        }

        if (objAtOffset != null) {
            ObjectId chrOid = objAtOffset.getObjectId(MongoDatabase.FLD_ATTR_CHRON);
            Surrogate chronicle = makeSurrogate(db, DBObjectType.CHRONICLE, chrOid);
            check(Permission.READ, chronicle);
            attribute.scan(objAtOffset.getString(MongoDatabase.FLD_ATTR_VALUE));
            String description = objAtOffset.getString(MongoDatabase.FLD_ATTR_DESC);
            if (description.length() > 0)
                attribute.setDescription(description);
            found = true;
        }
    } catch (Exception e) {
        throw T2DBMsg.exception(e, E.E40120, attribute.getProperty().getName());
    }
    return found;
}

From source file:ch.agent.crnickl.mongodb.ReadMethodsForChroniclesAndSeries.java

License:Apache License

/**
 * Return a list of chronicles with a given value for a given property.
 * /* w  w  w .java 2 s .c  o m*/
 * @param property a property
 * @param value a value
 * @param maxSize the maximum size of the result or 0 for no limit
 * @return a list of chronicles, possibly empty, never null
 * @throws T2DBException
 */
public <T> List<Chronicle> getChroniclesByAttributeValue(Property<T> property, T value, int maxSize)
        throws T2DBException {
    List<Chronicle> result = new ArrayList<Chronicle>();
    Surrogate s = property.getSurrogate();
    Database db = s.getDatabase();
    try {
        DBCursor cursor = getMongoDB(db).getAttributes().find(mongoObject(MongoDatabase.FLD_ATTR_PROP, getId(s),
                MongoDatabase.FLD_ATTR_VALUE, property.getValueType().toString(value)));
        while (cursor.hasNext()) {
            BasicDBObject obj = (BasicDBObject) cursor.next();
            ObjectId chrOid = obj.getObjectId(MongoDatabase.FLD_ATTR_CHRON);
            Surrogate chronicle = makeSurrogate(db, DBObjectType.CHRONICLE, chrOid);
            try {
                check(Permission.READ, chronicle);
                result.add(new ChronicleImpl(chronicle));
            } catch (T2DBException e) {
                // ignore "unreadable" chronicles
            }
        }
    } catch (Exception e) {
        throw T2DBMsg.exception(e, E.E40119, property.getName(), value);
    }
    return result;
}

From source file:ch.agent.crnickl.mongodb.ReadMethodsForChroniclesAndSeries.java

License:Apache License

/**
 * Return array of series in the positions corresponding to the
 * requested numbers. These numbers are series numbers within the schema,
 * not the series keys in the database. When a requested number in the array is
 * non-positive, the corresponding series will be null in the result. A
 * series can also be null when the requested number is positive but the
 * series has no data and has not been set up in the database (and therefore
 * has no series database key)./*from   w ww  .  j  av  a 2 s.c  o m*/
 * <p>
 * Note. There is no exception if the chronicle does not exist. This behavior makes
 * it easier to implement the wishful transaction protocol (i.e. testing again if it
 * was okay to delete a chronicle after it was deleted). 
 * 
 * @param chronicle a chronicle
 * @param names an array of simple names to plug into the series  
 * @param numbers an array of numbers
 * @return an array of series
 * @throws T2DBException
 */
public <T> Series<T>[] getSeries(Chronicle chronicle, String[] names, int[] numbers) throws T2DBException {

    if (names.length != numbers.length)
        throw new IllegalArgumentException("lengths of names[] and numbers[] differ");

    @SuppressWarnings("unchecked")
    Series<T>[] result = new SeriesImpl[numbers.length];
    if (result.length > 0) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] > 0) {
                if (map.put(numbers[i], i) != null)
                    throw new IllegalArgumentException("duplicate number: " + numbers[i]);
            }
        }
        Surrogate s = chronicle.getSurrogate();
        Database db = s.getDatabase();
        try {
            check(Permission.READ, chronicle);
        } catch (Exception e) {
            throw T2DBMsg.exception(e, E.E40104, s.toString());
        }
        try {
            DBCursor cursor = getMongoDB(db)
                    .getSeries().find(
                            mongoObject(MongoDatabase.FLD_SER_CHRON, getId(chronicle),
                                    MongoDatabase.FLD_SER_NUM, mongoObject(Operator.IN.op(), numbers)),
                            mongoObject(MongoDatabase.FLD_SER_NUM, 1));
            while (cursor.hasNext()) {
                BasicDBObject obj = (BasicDBObject) cursor.next();
                ObjectId serOid = obj.getObjectId(MongoDatabase.FLD_ID);
                int serNumber = obj.getInt(MongoDatabase.FLD_SER_NUM);
                int i = map.get(serNumber);
                result[i] = new SeriesImpl<T>(chronicle, names[i], numbers[i],
                        makeSurrogate(db, DBObjectType.SERIES, serOid));
            }
        } catch (Exception e) {
            throw T2DBMsg.exception(e, E.E40121, chronicle.getName(true));
        }
    }
    return result;
}

From source file:ch.agent.crnickl.mongodb.ReadMethodsForProperty.java

License:Apache License

/**
 * Find a collection of properties with names matching a pattern.
 * If the pattern is enclosed in slashes it is taken as a standard
 * regexp pattern; the slashes will be removed. If it is not enclosed
 * in slashes, it is taken as a minimal pattern and all occurrences of
 * "*" will be replaced with ".*" (zero or more arbitrary characters). 
 * //www  .ja v a  2 s .co  m
 * @param database a database
 * @param pattern a simple pattern or a regexp pattern
 * @return a collection of properties, possibly empty, never null
 * @throws T2DBException
 */
public Collection<Property<?>> getProperties(Database database, String pattern) throws T2DBException {
    try {
        DBCollection coll = getMongoDB(database).getProperties();
        DBObject query = null;
        if (pattern != null && pattern.length() > 0) {
            String regexp = extractRegexp(pattern);
            if (regexp == null)
                pattern = pattern.replace("*", ".*");
            else
                pattern = regexp;
            query = mongoObject(MongoDatabase.FLD_PROP_NAME, Pattern.compile(pattern));
        }
        DBCursor cursor = coll.find(query);
        Collection<Property<?>> result = new ArrayList<Property<?>>();
        try {
            while (cursor.hasNext()) {
                result.add(unpack(database, (BasicDBObject) cursor.next()));
            }
        } finally {
            cursor.close();
        }
        return result;
    } catch (Exception e) {
        throw T2DBMsg.exception(e, E.E20106, pattern);
    }
}