Example usage for com.mongodb DBCollection insert

List of usage examples for com.mongodb DBCollection insert

Introduction

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

Prototype

public WriteResult insert(final List<? extends DBObject> documents) 

Source Link

Document

Insert documents into a collection.

Usage

From source file:payroll.FrmLogin.java

private void btnTimeinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimeinActionPerformed
    // TODO add your handling code here:
    String username = "";
    String password = "";

    Connect1 j = new Connect1();
    DBCollection dbc = j.connect("Passwords");

    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("Employee Id", txtUname.getText());
    try {/*from w  w  w  .j  a va 2 s  .  c o  m*/
        DBCursor cursor = dbc.find(searchQuery);
        if (cursor.hasNext() == false) {
            JOptionPane.showMessageDialog(null, "Employee id not found", "TIME IN FAILED",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        DBObject obj = cursor.next();

        password = (String) obj.get("Password");
        username = (String) obj.get("Employee Id");
        if (password.equals(txtPwd.getText()) && username.equals(txtUname.getText())) {

            Connect1 k = new Connect1();
            DBCollection dbc1 = k.connect("Attendance");
            Calendar cal = new GregorianCalendar();
            int date = cal.get(Calendar.DATE);

            int month = cal.get(Calendar.MONTH);
            int year = cal.get(Calendar.YEAR);

            BasicDBObject bdb2 = new BasicDBObject();
            bdb2.put("Employee ID", txtUname.getText());
            bdb2.put("Date", date);
            bdb2.put("Month", month);
            DBCursor cur2 = dbc1.find(bdb2);
            if (cur2.hasNext()) {
                JOptionPane.showMessageDialog(null, "You have already timed in today", "TIME IN FAILED",
                        JOptionPane.ERROR_MESSAGE);
                return;
            }

            int hour = cal.get(Calendar.HOUR_OF_DAY);
            int mins = cal.get(Calendar.MINUTE);
            //    System.out.println(Calendar.HOUR_OF_DAY);
            BasicDBObject bdb = new BasicDBObject();
            bdb.put("Date", date);
            bdb.put("Month", month);
            bdb.put("Employee ID", txtUname.getText());
            bdb.put("Login Hour", hour);
            bdb.put("Login Minute", mins);
            bdb.put("Logout Hour", -1);
            bdb.put("Logout Minute", -1);
            bdb.put("Normal time", 0);
            bdb.put("Overtime time", 0);

            dbc1.insert(bdb);

            txtUname.setText("");
            txtPwd.setText("");

            DBCollection dbc2 = j.connect("remaining_leaves");
            if (date == 1 && month == 1) {
                BasicDBObject bdb1 = new BasicDBObject();
                bdb1.put("Casual_leaves", 15);
                bdb1.put("Sick_leaves", 20);
                bdb1.put("ID", txtUname.getText());
                dbc2.insert(bdb1);

            }

        } else {
            JOptionPane.showMessageDialog(null, "WRONG USERNAME OR PASSWORD", "LOGIN FAILED",
                    JOptionPane.ERROR_MESSAGE);
            txtUname.setText("");
            txtPwd.setText("");

        }

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "WRONG USERNAME OR PASSWORD", "LOGIN FAILED",
                JOptionPane.ERROR_MESSAGE);
        txtUname.setText("");
        txtPwd.setText("");
    }

    JOptionPane.showMessageDialog(null, "WELCOME", "LOGIN SUCCESSFUL", JOptionPane.INFORMATION_MESSAGE);

}

From source file:payroll.FrmPassword.java

private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
    // TODO add your handling code here:
    int id = 0;//w  w  w  .ja va2  s . co  m
    Connect1 j = new Connect1();
    DBCollection dbc = j.connect("Passwords");
    BasicDBObject bdb = new BasicDBObject();
    final JPanel p2 = new JPanel();
    final JOptionPane jo = new JOptionPane();
    Connect1 k = new Connect1();
    DBCollection dbc1 = k.connect("Emp_Records");
    DBCursor cursor = dbc1.find();
    while (cursor.hasNext() == true) {
        DBObject obj = cursor.next();
        id++;
    }
    String ID = "";

    id = id - 1;

    if (id < 10)
        ID = "EMP00" + id;
    else
        ID = "EMP0" + id;

    if (pwdRetype.getText().equals(pwdPassword.getText())) {
        bdb.put("Employee Id", ID);
        bdb.put("Password", pwdPassword.getText());
        dbc.insert(bdb);
        JOptionPane.showMessageDialog(p2, "Password Created Successfully", "Success",
                JOptionPane.INFORMATION_MESSAGE);
        this.setVisible(false);

    } else {
        JOptionPane.showMessageDialog(p2, "Passwords do not match", "Failed", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:plugins.TemplatePlugin.java

License:Open Source License

private void importFile(String fname, DBCollection col) throws UnexpectedException {
    BufferedReader reader = null;
    try {//w w  w  . jav a 2s  .  com
        reader = new BufferedReader(new FileReader(Play.applicationPath.getAbsolutePath() + fname));
        String strLine;

        while ((strLine = reader.readLine()) != null) {
            DBObject obj = (DBObject) parse(strLine);
            if (obj != null)
                col.insert(obj);
        }
        reader.close();
    } catch (Exception e) {
        throw new UnexpectedException(e);
    }
}

From source file:poke.server.storage.jdbc.DatabaseStorage.java

License:Apache License

@Override
public boolean addImageDetails(PhotoHeader photoHeader, PhotoPayload imageRequest, String uuid) {
    boolean inserted = false;
    DBCollection dbColl = db.getCollection("ImageRepository");
    BasicDBObject bdo = new BasicDBObject();
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    bdo.put("createdAt", dateFormat.format(cal.getTime()));
    bdo.put("name", imageRequest.getName());
    bdo.put("data", imageRequest.getData().toStringUtf8());
    bdo.put("modifiedAt", Long.parseLong(dateFormat.format(cal.getTime()).toString().replaceAll("\\W", "")));
    bdo.put("uuid", uuid.toString());
    dbColl.insert(bdo);
    logger.debug("Inserted: " + bdo.getObjectId("_id"));
    if (bdo.getObjectId("_id") != null)
        inserted = true;//from ww w .ja  v  a2  s  .  com
    return inserted;
}

From source file:Presentation.Bean.MenuBean.java

public ArrayList<Menu> getMenuList() {

    // To connect to mongo dbserver
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    // Now connect to your databases
    DB db = mongoClient.getDB("Restaurant");
    System.out.println("Connect to database successfully");

    DBCollection collection = db.getCollection("Menus");
    System.out.println("Collection menu selected successfully");

    // PASO 4.1: "CREATE" -> Metemos los objetos men (o documentos en Mongo) en la coleccion Menu
    for (Menu men : menuList) {
        collection.insert(men.toDBObjectMenu());
    }//w  w w  . j  a va2  s  .  c om

    // PASO 4.2.1: "READ" -> Leemos todos los documentos de la base de datos
    int numDocumentos = (int) collection.getCount();
    System.out.println("Nmero de documentos en la coleccin Menu: " + numDocumentos + "\n");

    // Busco todos los documentos de la coleccin y los imprimo
    DBCursor cursor = collection.find();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toString());
        }
    } finally {
        cursor.close();
    }

    return menuList;

}

From source file:pruebamongo.PruebaMongo.java

private static void anadirDocumentos(MongoClient mongo) {

    //Seleccionamos la base de datos 'prueba'
    DB db = mongo.getDB("prueba");
    //Seleccionamos la coleccin 'contactos' dentro de esa base de datos
    DBCollection col = db.getCollection("contactos");

    //Creamos objeto con los elementos que se han de aadir
    DBObject obj = new BasicDBObject().append("_id", 12).append("nombre", "Catelyn").append("apellido",
            "Stark");
    try {//from ww w .  ja v a2s  .  c o m
        col.insert(obj);
        System.out.println("Elemento aadido satisfactoriamente.");
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
}

From source file:QueryBuilderClass.Field_selection_mongo.java

/**
 * @param args the command line arguments
 * @throws java.net.UnknownHostException
 *//*  w w w . ja va 2 s. c o m*/
public static void main(String[] args) throws UnknownHostException {

    MongoClient client = new MongoClient("localhost", 27017);
    DB myDB = client.getDB("m101");
    DBCollection collection = myDB.getCollection("Sample3");

    /**
     * random_number field generates random numbers 
    */
    Random random_numbers = new Random();

    collection.drop();

    for (int i = 0; i < 10; i++) {
        collection.insert(new BasicDBObject("x", random_numbers.nextInt(100))
                .append("y", random_numbers.nextInt(100)).append("z", random_numbers.nextInt(200)));
    }

    DBObject query = QueryBuilder.start("x").greaterThan(10).lessThan(70).and("y").greaterThan(10).lessThan(70)
            .get();

    DBCursor cursor = collection.find(query, new BasicDBObject("y", true).append("_id", false));

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

}

From source file:rapture.sheet.mongodb.MongoCellStore.java

License:Open Source License

public Boolean setBulkCell(String sheetName, int startRow, int startColumn, List<String> values, int height,
        int width, int dimension) {
    long epoch = getLatestEpoch(sheetName, dimension) + 1L;
    DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName);
    List<DBObject> toWrite = new ArrayList<DBObject>();

    int currentRow = startRow;
    int currentColumn = startColumn;
    int columnCount = 0;
    for (String val : values) {
        if (val != null) {
            BasicDBObject toPut = new BasicDBObject();
            toPut.put(KEY, sheetName);//from w  w w.  j  av a2s. co  m
            toPut.put(ROW, currentRow);
            toPut.put(COL, currentColumn);
            toPut.put(DIM, dimension);
            toPut.put(VALUE, val);
            toPut.put(EPOCH, epoch);
            toWrite.add(toPut);
        }
        currentColumn++;
        columnCount++;
        if (columnCount >= width) {
            currentRow++;
            currentColumn = startColumn;
            columnCount = 0;
        }
    }
    collection.insert(toWrite);
    return true;
}

From source file:rapture.sheet.mongodb.MongoCellStore.java

License:Open Source License

public void cloneSheet(final String srcName, final String targetName) {
    final DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName);
    MongoRetryWrapper<Object> wrapper = new MongoRetryWrapper<Object>() {

        public DBCursor makeCursor() {
            // Everything with the KEY being the srcName, modify the source
            // name to
            // targetName and store it back
            BasicDBObject query = new BasicDBObject();
            query.append(KEY, srcName);//from www  . jav a  2s  .co m
            return collection.find(query);
        }

        public Object action(DBCursor cursor) {
            while (cursor.hasNext()) {
                BasicDBObject object = (BasicDBObject) cursor.next();
                object.put(KEY, targetName);
                object.remove("_id");
                collection.insert(object);
            }
            return null;
        }
    };
    @SuppressWarnings("unused")
    Object o = wrapper.doAction();
}

From source file:rapture.sheet.mongodb.MongoMetaSheetStore.java

License:Open Source License

public void cloneSheet(final String srcName, final String targetName) {
    // Everything with the KEY being the srcName, modify the source name to
    // targetName and store it back
    final DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName);
    MongoRetryWrapper<Object> wrapper = new MongoRetryWrapper<Object>() {

        public DBCursor makeCursor() {

            BasicDBObject query = new BasicDBObject();
            query.append(KEY, srcName);//w  w  w  . j  a  v  a2 s . com
            return collection.find(query);
        }

        public Object action(DBCursor cursor) {
            while (cursor.hasNext()) {
                BasicDBObject object = (BasicDBObject) cursor.next();
                object.put(KEY, targetName);
                object.remove("_id");
                collection.insert(object);
            }

            return null;
        }
    };
    @SuppressWarnings("unused")
    Object o = wrapper.doAction();
}