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:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java

License:Apache License

private CentralAgeOffEventState getCentralAgeOffEventState(Long ageOffId) throws UnknownHostException {

    Mongo mongoClient = null;
    DBCollection ageOffColl = null;/*from  www  . ja va 2s  .  c  o m*/
    try {
        MongoConfigurationHelper mongoConfigurationHelper = new MongoConfigurationHelper(configuration);
        MongoHelper mongoHelper = new MongoHelper(configuration);
        mongoClient = mongoHelper.getMongo();
        DB mongoDB = mongoClient.getDB(mongoConfigurationHelper.getMongoDBDatabaseName());
        ageOffColl = mongoDB.getCollection(AGEOFF_COLLECTION);

        //Get the centralAgeOffEventState and return it
        BasicDBObject query = new BasicDBObject(EzCentralPurgeServiceHelpers.AgeOffEventId, ageOffId);
        DBCursor cursor = ageOffColl.find(query);
        DBObject dbObject = null;
        if (cursor.hasNext()) {
            dbObject = cursor.next();
        } else {
            return null;
        }
        return decodeCentralAgeOffEventState((DBObject) dbObject.get(CentralAgeOffStateString));

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

From source file:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java

License:Apache License

private void updateCentralAgeOffEventState(CentralAgeOffEventState centralAgeOffEventState, Long ageOffId)
        throws UnknownHostException {

    DBCollection ageOffColl = null;// w  w  w . j  a va  2 s  . co m
    Mongo mongoClient = null;
    try {
        MongoConfigurationHelper mongoConfigurationHelper = new MongoConfigurationHelper(configuration);
        MongoHelper mongoHelper = new MongoHelper(configuration);
        mongoClient = mongoHelper.getMongo();
        DB mongoDB = mongoClient.getDB(mongoConfigurationHelper.getMongoDBDatabaseName());
        ageOffColl = mongoDB.getCollection(AGEOFF_COLLECTION);

        // Update the state if it exists, insert if not
        BasicDBObject query = new BasicDBObject(EzCentralPurgeServiceHelpers.AgeOffEventId, ageOffId);
        BasicDBObject ageOffEvent = new BasicDBObject().append(AgeOffEventId, ageOffId)
                .append(CentralAgeOffStateString, encodeCentralAgeOffEventState(centralAgeOffEventState));
        boolean upsert = true;
        boolean multiUpdate = false;
        ageOffColl.update(query, ageOffEvent, upsert, multiUpdate);
    } catch (UnknownHostException e) {
        // TODO: log that couldn't connect to MongoDB
        throw e;
    } finally {
        if (mongoClient != null)
            mongoClient.close();
    }
}

From source file:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java

License:Apache License

private List<Long> getAllPurgeIdsInMongo() throws UnknownHostException {
    List<Long> result = null;
    DBCollection purgeColl = null;/* ww  w . j ava  2s  .  c  om*/
    Mongo mongoClient = null;

    try {
        MongoConfigurationHelper mongoConfigurationHelper = new MongoConfigurationHelper(configuration);
        MongoHelper mongoHelper = new MongoHelper(configuration);
        mongoClient = mongoHelper.getMongo();
        DB mongoDB = mongoClient.getDB(mongoConfigurationHelper.getMongoDBDatabaseName());
        purgeColl = mongoDB.getCollection(PURGE_COLLECTION);

        // Just get all ids from MongoDB
        result = new ArrayList<Long>();
        DBCursor cursor = purgeColl.find();
        while (cursor.hasNext()) {
            result.add((Long) cursor.next().get(EzCentralPurgeServiceHelpers.PurgeId));
        }

        return result;
    } finally {
        if (mongoClient != null) {
            mongoClient.close();
        }
    }
}

From source file:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java

License:Apache License

private CentralPurgeState getCentralPurgeState(Long purgeId) throws UnknownHostException {

    DBCollection purgeColl = null;//from w  ww.j  a  va  2s  .c  om
    Mongo mongoClient = null;
    try {
        MongoConfigurationHelper mongoConfigurationHelper = new MongoConfigurationHelper(configuration);
        MongoHelper mongoHelper = new MongoHelper(configuration);
        mongoClient = mongoHelper.getMongo();
        DB mongoDB = mongoClient.getDB(mongoConfigurationHelper.getMongoDBDatabaseName());
        purgeColl = mongoDB.getCollection(PURGE_COLLECTION);

        //Get the centralPurgeState and return it
        BasicDBObject query = new BasicDBObject(PurgeId, purgeId);
        DBCursor cursor = purgeColl.find(query);
        DBObject dbObject = null;
        if (cursor.hasNext()) {
            dbObject = cursor.next();
        } else {
            return null;
        }
        return decodeCentralPurgeState((DBObject) dbObject.get(CentralPurgeStateString));
    } finally {
        if (mongoClient != null) {
            mongoClient.close();
        }
    }
}

From source file:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java

License:Apache License

private void updateCentralPurgeState(CentralPurgeState centralPurgeState, Long purgeId)
        throws UnknownHostException {
    DBCollection purgeColl = null;//from w ww  .j  a v a2 s .  c  o m
    Mongo mongoClient = null;
    try {
        MongoConfigurationHelper mongoConfigurationHelper = new MongoConfigurationHelper(configuration);
        MongoHelper mongoHelper = new MongoHelper(configuration);
        mongoClient = mongoHelper.getMongo();
        DB mongoDB = mongoClient.getDB(mongoConfigurationHelper.getMongoDBDatabaseName());
        purgeColl = mongoDB.getCollection(PURGE_COLLECTION);

        // Update the state if it exists, insert if not
        BasicDBObject query = new BasicDBObject(PurgeId, purgeId);
        BasicDBObject purgeStatus = new BasicDBObject()
                .append(PurgeId, centralPurgeState.getPurgeInfo().getId())
                .append(CentralPurgeStateString, encodeCentralPurgeState(centralPurgeState));
        boolean upsert = true;
        boolean multiUpdate = false;
        purgeColl.update(query, purgeStatus, upsert, multiUpdate);
    } finally {
        if (mongoClient != null)
            mongoClient.close();
    }
}

From source file:flipkart.mongo.node.discovery.mock.model.MockReplicaSetModel.java

License:Apache License

public static Mongo mockMongoClient(DB mongoDB) {
    Mongo mongoClient = mock(Mongo.class);
    when(mongoClient.getDB(Matchers.anyString())).thenReturn(mongoDB);
    return mongoClient;
}

From source file:fr.cnes.sitools.datasource.mongodb.ActivationDataSourceResource.java

License:Open Source License

/**
 * Testing connections/* ww  w  . j a  v  a2  s  .co m*/
 * 
 * @param ds
 *          the DataSource to test
 * @param trace
 *          a {@link List} of String to store the trace of the test. Can be null
 * @return Representation results of the connection test.
 */
public boolean testDataSourceConnection(MongoDBDataSource ds, List<String> trace) {
    Boolean result = Boolean.TRUE;

    Mongo mongo = null;

    try {
        do {
            trace(trace, "Test mongo data source connection ...");
            try {
                mongo = new Mongo(ds.getUrl(), ds.getPortNumber());
            } catch (Exception e) {
                result = false;
                getMongoDBDataSourceAdministration().getLogger().info(e.getMessage());
                trace(trace, "Load driver class failed. Cause: " + e.getMessage());
                break;
            }

            try {
                // check if the database exists
                // List<String> databases = mongo.getDatabaseNames();
                // if (!databases.contains(ds.getDatabaseName())) {
                // result = false;
                // getMongoDBDataSourceAdministration().getLogger().info("Database does not exist");
                // trace.add("Database " + ds.getDatabaseName() + " does not exist");
                // break;
                // }

                DB db = mongo.getDB(ds.getDatabaseName());
                // if no user and password given lets authenticate on the database
                if (ds.isAuthentication() && !db.isAuthenticated()
                        && !db.authenticate(ds.getUserLogin(), ds.getUserPassword().toCharArray())) {
                    result = false;
                    getMongoDBDataSourceAdministration().getLogger().info("Authentication failed");
                    trace(trace, "Authentication failed");
                    break;
                }

                // try to get the stats of the database to check whether or not the database is accessible
                CommandResult cmd = db.getStats();
                if (!cmd.ok()) {
                    result = false;
                    getMongoDBDataSourceAdministration().getLogger()
                            .info("Error connecting to the database " + cmd);
                    trace(trace, "Error connecting to the database " + cmd);
                    break;
                }
                trace(trace, "Get connection to the database : OK");
            } catch (Exception e) {
                result = false;
                getMongoDBDataSourceAdministration().getLogger().info(e.getMessage());
                trace(trace, "Get connection to the database failed. Cause: " + e.getMessage());
                break;
            }
        } while (false);

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

    }

    return result;
}

From source file:Frames.AddUser.java

/**
 * Creates new form AddUser//w w  w  .ja va  2 s .com
 */
public AddUser() {
    try {
        Mongo mongo = new Mongo("localhost", 27017);
        BasedeDatos = mongo.getDB("ska");
        coleccion = BasedeDatos.getCollection("Usuario");
        System.out.println("coneccion de base de datos exitosa");
    } catch (Exception e) {
    }

    initComponents();
    setLocationRelativeTo(null);
}

From source file:Frames.Login.java

/**
 * Creates new form Login//from w  w w .  j  a  v  a  2 s  .com
 */
public Login() {
    try {
        Mongo mongo = new Mongo("localhost", 27017);
        BasedeDatos = mongo.getDB("ska");
        coleccion = BasedeDatos.getCollection("skatabla");
        System.out.println("coneccion de base de datos exitosa");
    } catch (Exception e) {
    }

    initComponents();
    setLocationRelativeTo(null);
}

From source file:guardar.en.base.de.datos.MainServidor.java

public static void main(String[] args)
        throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException {

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

    // nombre de la base de datos
    DB database = mongo.getDB("paginas");
    // coleccion de la db
    DBCollection collection = database.getCollection("indice");
    DBCollection collection_textos = database.getCollection("tabla");
    ArrayList<String> lista_textos = new ArrayList();

    try {/* ww w .  j  a  va  2 s.  com*/
        ServerSocket servidor = new ServerSocket(4545); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            String aux = new String();
            lista_textos.clear();
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("id");
            //hacer una query a la base de datos con la palabra que se quiere obtener

            BasicDBObject query = new BasicDBObject("palabra", b);
            DBCursor cursor = collection.find(query);
            ArrayList<DocumentosDB> lista_doc = new ArrayList<>();
            // de la query tomo el campo documentos y los agrego a una lista
            try {
                while (cursor.hasNext()) {
                    //System.out.println(cursor.next());
                    BasicDBList campo_documentos = (BasicDBList) cursor.next().get("documentos");
                    // en el for voy tomando uno por uno los elementos en el campo documentos
                    for (Iterator<Object> it = campo_documentos.iterator(); it.hasNext();) {
                        BasicDBObject dbo = (BasicDBObject) it.next();
                        //DOC tiene id y frecuencia
                        DocumentosDB doc = new DocumentosDB();
                        doc.makefn2(dbo);
                        //int id = (int)doc.getId_documento();
                        //int f = (int)doc.getFrecuencia();

                        lista_doc.add(doc);

                        //*******************************************

                        //********************************************

                        //QUERY A LA COLECCION DE TEXTOS
                        /* BasicDBObject query_textos = new BasicDBObject("id", doc.getId_documento());//query
                         DBCursor cursor_textos = collection_textos.find(query_textos);
                         try {
                        while (cursor_textos.hasNext()) {
                                    
                                    
                            DBObject obj = cursor_textos.next();
                                
                            String titulo = (String) obj.get("titulo");
                            titulo = titulo + "\n\n";
                            String texto = (String) obj.get("texto");
                                
                            String texto_final = titulo + texto;
                            aux = texto_final;
                            lista_textos.add(texto_final);
                        }
                         } finally {
                        cursor_textos.close();
                         }*/
                        //System.out.println(doc.getId_documento());
                        //System.out.println(doc.getFrecuencia());

                    } // end for

                } //end while query

            } finally {
                cursor.close();
            }

            // ordeno la lista de menor a mayor
            Collections.sort(lista_doc, new Comparator<DocumentosDB>() {

                @Override
                public int compare(DocumentosDB o1, DocumentosDB o2) {
                    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    return o1.getFrecuencia().compareTo(o2.getFrecuencia());
                }
            });
            int tam = lista_doc.size() - 1;
            for (int j = tam; j >= 0; j--) {

                BasicDBObject query_textos = new BasicDBObject("id",
                        (int) lista_doc.get(j).getId_documento().intValue());//query
                DBCursor cursor_textos = collection_textos.find(query_textos);// lo busco
                try {
                    while (cursor_textos.hasNext()) {

                        DBObject obj = cursor_textos.next();
                        String titulo = "*******************************";
                        titulo += (String) obj.get("titulo");
                        int f = (int) lista_doc.get(j).getFrecuencia().intValue();
                        String strinf = Integer.toString(f);
                        titulo += "******************************* frecuencia:" + strinf;
                        titulo = titulo + "\n\n";

                        String texto = (String) obj.get("texto");

                        String texto_final = titulo + texto + "\n\n";
                        aux = aux + texto_final;
                        //lista_textos.add(texto_final);
                    }
                } finally {
                    cursor_textos.close();
                }

            }

            //actualizar el cache
            try {
                Socket cliente_cache = new Socket("localhost", 4500); // nos conectamos con el servidor
                ObjectOutputStream mensaje_cache = new ObjectOutputStream(cliente_cache.getOutputStream()); // get al output del servidor, que es cliente : socket del cliente q se conecto al server
                JSONObject actualizacion_cache = new JSONObject();
                actualizacion_cache.put("actualizacion", 1);
                actualizacion_cache.put("busqueda", b);
                actualizacion_cache.put("respuesta", aux);
                mensaje_cache.writeObject(actualizacion_cache); // envio el msj al servidor
            } catch (Exception ex) {

            }

            //RESPONDER DESDE EL SERVIDORIndex al FRONT
            ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj
            resp.writeObject(aux);
            System.out.println("msj enviado desde el servidor");

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

}