Example usage for com.mongodb Mongo getDB

List of usage examples for com.mongodb Mongo getDB

Introduction

In this page you can find the example usage for com.mongodb Mongo getDB.

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:PanMostrar.java

/**
 * Creates new form PanMostrar/*from  ww  w.  j av a  2s .c o  m*/
 */

public PanMostrar() {

    //Conexion a mongoDb
    try {
        Mongo mongo = new Mongo("localhost", 27017);
        db = mongo.getDB("Escuela");
        tabla = db.getCollection("Alumnos");

    } catch (UnknownHostException ex) {
        Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
    }

    initComponents();

    int num = 1;
    DBCursor cursor = tabla.find();
    DefaultListModel model = new DefaultListModel();

    while (cursor.hasNext()) {
        BSONObject obj = cursor.next();

        // Obtener variables del JSON
        try {

            String name = (String) obj.get("Nombre");
            String ap = (String) obj.get("ApPaterno");
            String am = (String) obj.get("ApMaterno");
            String fechaNac = (String) obj.get("FechaNac");
            int edad = (int) obj.get("Edad");
            String sex = (String) obj.get("Sexo");
            String mat = (String) obj.get("Matricula");
            int semestre = (int) obj.get("Semestre");
            String carrera = (String) obj.get("Carrera");

            // Imprimir todo
            /*Mostrar.setText(Mostrar.getText() + "\n" + name +  " " + ap + " " + am + " " 
                + fechaNac + " " + edad + " " + sex + " " + mat + " " + semestre + 
                " " + carrera);*/

            model.addElement(num + "  " + name + " " + ap + " " + am + " " + fechaNac + " " + edad + " " + sex
                    + " " + mat + " " + semestre + " " + carrera);
            num++;

        } catch (Exception ex) {
            System.out.println("objeto no completo");
        }
        Lista.setModel(model);
    }
}

From source file:search.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w w .  j a  v  a 2  s  . c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet search</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet search at " + request.getContextPath() + "</h1>");
        String srch_id = request.getParameter("search");
        DB db;

        Mongo mongo = new Mongo("LocalHost", 27017);
        db = mongo.getDB("local");
        out.println("db connected is..." + db);
        DBCollection collection = db.getCollection("StartupHun");
        out.println("table used connected is..." + collection);
        BasicDBObject query = new BasicDBObject("founded_year", new BasicDBObject("$gt", 2005));
        BasicDBObject cat = new BasicDBObject();
        //query.put("name", srch_id);
        DBCursor cursor = collection.find();
        // Print out "highest" priority items
        BasicDBObject query1 = null;
        int i = 0;
        while (cursor.hasNext()) {
            //out.println(cursor.next());
            query1 = (BasicDBObject) cursor.next();

            out.println((Integer) query1.get("founded_year") + "  " + i);
            i++;
        }

        out.println("</body>");
        out.println("</html>");
    }
}

From source file:PanModificar.java

public PanModificar() {
    //Conexion a mongoDb
    try {//w w w .  j  av a  2  s. c o m
        Mongo mongo = new Mongo("localhost", 27017);
        db = mongo.getDB("Escuela");
        tabla = db.getCollection("Alumnos");

    } catch (UnknownHostException ex) {
        Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
    }
    DBCursor cursor = tabla.find();

    ArrayList rows = new ArrayList();
    String[] titulos = { "Nombre", "ApPaterno", "ApMaterno", "FechaNac", "Edad", "Sexo", "Matricula",
            "Semestre", "Carrera" };
    ArrayList<String> columndata = new ArrayList<String>(Arrays.asList(titulos));
    while (cursor.hasNext()) {
        BSONObject obj = cursor.next();

        // Obtener variables del JSON
        try {

            String name = (String) obj.get("Nombre");
            String ap = (String) obj.get("ApPaterno");
            String am = (String) obj.get("ApMaterno");
            String fechaNac = (String) obj.get("FechaNac");
            int edad = (int) obj.get("Edad");
            String sex = (String) obj.get("Sexo");
            String mat = (String) obj.get("Matricula");
            int semestre = (int) obj.get("Semestre");
            String carrera = (String) obj.get("Carrera");
            ArrayList<String> row = new ArrayList<String>(Arrays.asList(
                    new String[] { name, ap, am, fechaNac, "" + edad, sex, mat, "" + semestre, carrera }));
            rows.add(row);
        } catch (Exception ex) {
            System.out.println("objeto no completo");
        }

    }

    initComponents();
    jTable1.setModel(new CustomTableModel(columndata, rows, "no hay datos en la bd!!"));
    jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}

From source file:Modificar.java

/**
 * Creates new form Inicio//from w  w  w. j  a va 2s  .c  o m
 */
public Modificar(Object[] columnnames, Object[] data) {

    initComponents();
    //Conexion a mongoDb
    try {
        Mongo mongo = new Mongo("localhost", 27017);
        db = mongo.getDB("Escuela");
        collection = db.getCollection("Alumnos");
        this.columnnames = columnnames;
        this.data = data;
        NombreT.setText((String) data[0]);
        ApPaterno.setText((String) data[1]);
        ApMaterno.setText((String) data[2]);
        dia.setSelectedItem(((String) data[3]).split("-")[0]);
        mes.setSelectedItem(((String) data[3]).split("-")[1]);
        anio.setSelectedItem(((String) data[3]).split("-")[2]);
        EdadT.setText((String) data[4]);
        sexo.setSelectedItem((String) data[5]);
        matricula.setText((String) data[6]);
        semestre.setSelectedItem((String) data[7]);
        Carrera.setText((String) data[8]);

    } catch (UnknownHostException ex) {
        Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Ventana.java

public Ventana() {

    this.setTitle("Mexico SIN Hambre");
    initComponents();//from   w  w  w  .  j  a  v a2 s  . c o  m
    this.getContentPane().setBackground(Color.WHITE);
    this.setBounds(0, 0, 345, 51);
    setResizable(false);

    fields[0] = jLabel1;
    fields[1] = jLabel2;
    fields[2] = jLabel3;
    fields[3] = jLabel4;
    fields[4] = jLabel5;
    fields[5] = jLabel6;
    fields[6] = jLabel7;
    fields[7] = jLabel8;
    fields[8] = jLabel9;
    fields[9] = jLabel10;
    fields[10] = jLabel11;
    fields[11] = jLabel12;

    texts[0] = jTextField1;
    texts[1] = jTextField2;
    texts[2] = jTextField3;
    texts[3] = jTextField4;
    texts[4] = jTextField5;
    texts[5] = jTextField6;
    texts[6] = jTextField7;
    texts[7] = jTextField8;
    texts[8] = jTextField9;
    texts[9] = jTextField10;
    texts[10] = jTextField11;
    texts[11] = jTextField12;

    add_to_ActionListenner();
    make_lab_and_text_invisible();

    try {
        Mongo mongo = new Mongo("localhost", 27017);

        db = mongo.getDB("Beneficiarios");

    } catch (UnknownHostException ex) {
        Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:PanBorrar.java

/**
 * Creates new form PanBorrar/* w  ww. j  av a 2  s.co m*/
 */
public PanBorrar() {
    try {
        Mongo mongo = new Mongo("localhost", 27017);
        db = mongo.getDB("Escuela");
        tabla = db.getCollection("Alumnos");

    } catch (UnknownHostException ex) {
        Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
    }

    initComponents();
}

From source file:Inicio.java

/**
 * Creates new form Inicio/*from  w ww.  j  av  a2  s.  c  o  m*/
 */
public Inicio() {

    //Conexion a mongoDb
    try {
        Mongo mongo = new Mongo("localhost", 27017);
        db = mongo.getDB("Escuela");
        tabla = db.getCollection("Alumnos");

    } catch (UnknownHostException ex) {
        Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
    }

    initComponents();
}

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

License:Apache License

private void buildModel() throws UnknownHostException {
    userIsObject = false;//from   www .  j  ava 2 s.  co m
    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:at.tuwien.aic.Main.java

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

    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 UserController() {
    Mongo mongo;
    try {//from  w  w  w .  j  a  va 2 s  .c o m
        mongoFactory = new MongoFactory();
        int connectionsPerHost = 20;
        mongo = mongoFactory.createMongoInstance(connectionsPerHost);
        database = mongo.getDB("tmb16396");
        try {
            userCollection = database.getCollection("users");
        } catch (Exception e) {
            userCollection = database.createCollection("users", null);
        }
    } catch (MongoException ex) {
        ex.printStackTrace();
    }
}