Example usage for com.mongodb DBCollection find

List of usage examples for com.mongodb DBCollection find

Introduction

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

Prototype

public DBCursor find(final DBObject query) 

Source Link

Document

Select documents in collection and get a cursor to the selected documents.

Usage

From source file:br.edu.unifesspa.lcc.indexer.GerarIndice.java

@Override
public void run() {
    if (!list.isEmpty()) {

        //Foi identificado um problema quando h poucos processamentos agendados,
        // ocorre de processar mais que uma vez, ao mesmo tempo, o mesmo Processamento Id, portando,  necessario remover o
        //processamento_indice do banco,quando comear o processamento
        //Fazer download da demanda----
        try {//from  ww w  .j  ava2  s  .  c  om
            DownloadInfo();
        } catch (InterruptedException ex) {
            // Logger.getLogger(GerarIndice.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
        //Fim de Fazer download da demada----

        //Insere em um banco, especificando qual assunto, a demanda est utilizando
        BasicDBObject search = new BasicDBObject();
        DB aux = mongo.getDB("demandas");
        DBCollection colDemandaAtiva = aux.getCollection("demandas_ativas");
        search.append("demanda", assunto.toString());
        search.append("Processamento_indiceId", procId);
        System.out.println("Inseriu na demanda_ativa");
        colDemandaAtiva.insert(search);
        //Fim inserir no banco, a demanda ativa

        //Aqui itera sobre a lista de indicadores que devem ser processados
        System.out.println("Est para entrar no forit e a lista : " + list);
        for (Integer integer : list) {
            try {
                System.out.println("Processando indicador: " + integer);
                est.getIndicador(integer, dbAssunto); //Gera o indicador
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //Depois de processar todos os indices, remove do banco das demandas_ativas, o assunto que foi processado.
        colDemandaAtiva.remove(search);
        System.out.println("REMOVEU");
        search.clear();

        //Se no tiver mais nenhuma demanda utilizando o assunto, dropa-se o banco da demanda
        search.append("demanda", assunto.toString());
        DBCursor cursor = colDemandaAtiva.find(search);
        if (cursor.size() == 0) {
            //dbAssunto.dropDatabase();
            System.out.println("DROPOU");

        }
    }
}

From source file:br.edu.unifesspa.lcc.indexer.GerarIndice.java

private void DownloadInfo() throws InterruptedException {
    //Verifica se j existe um banco de demanda criado no Mongo
    List<String> dbs = mongo.getDatabaseNames();
    if (!dbs.contains(assunto.toString())) {//Se o banco no existe, faz o download

        RestTemplate rt = new RestTemplate();
        DB territorios = mongo.getDB("territorios");
        DBCollection colTerritorios = territorios.getCollection("territorio");
        HttpEntity<String> entity = new HttpEntity<>("parameters", Processar.headers);
        BasicDBObject insert = new BasicDBObject();

        BasicDBObject insertDemanda = new BasicDBObject();

        DBCollection colDaDemanda = dbAssunto.getCollection(assunto.toString());

        System.out.println("db =" + dbAssunto);
        DBCollection k_classe = dbAssunto.getCollection("k");
        //K_CLASSES  -----------------------------------------------------------------------------------------------
        try {/*from   w ww. j  a  v  a  2 s . c om*/

            ResponseEntity<domain.K_classes[]> kClasse = rt.exchange(
                    "http://xingu.lcc.unifesspa.edu.br:8080/api/k_classess?idassunto=" + assunto,
                    HttpMethod.GET, entity, domain.K_classes[].class);
            System.out.println("K-classe tamanho: " + kClasse.getBody().length);
            //System.out.println("Tamanho body:" + kClasse.getBody().length);
            for (domain.K_classes k : kClasse.getBody()) {
                insert.append("k_ordem", k.getk_ordem());
                insert.append("k_classes_id", k.getId());
                insert.append("ck", Integer.parseInt(k.getk_codigo()));
                insert.append("dk", k.getk_descricao());

                k_classe.insert(insert);
                insert.clear();

            }
            System.out.println("DEVERIA TER INSERIDO O K");
        } catch (Exception e) {
            e.printStackTrace();
            insert.clear();
        }
        //FIM K-CLASSES E COMEO INPUT_PRESENTES --------------------------------------------------------------------------------------------------------
        BasicDBObject insertCI = new BasicDBObject();
        try {
            System.out.println("Comeando a inserir os Inputs do assunto: " + assunto);
            ResponseEntity<domain.Input_presenteDTO[]> input = rt.exchange(
                    "http://xingu.lcc.unifesspa.edu.br:8080/api/input_presentes/getInputPresenteByAssantoId/"
                            + assunto,
                    HttpMethod.GET, entity, Input_presenteDTO[].class);
            System.out.println("Fez o download do assunto: " + assunto);
            System.out.println("Tamano input: " + input.getBody().length + "  Assunto: " + assunto);
            DBCollection colInput_presente = dbAssunto.getCollection("i"); // inserir assunto na base
            BasicDBObject search2 = new BasicDBObject();

            //    int cont = 0;
            for (Input_presenteDTO Input2 : input.getBody()) {
                //       System.out.println("Entrou");
                //Para a coleo "i"
                search2.append("ci", Integer.parseInt(Input2.getCodigo()));
                DBObject aux = colInput_presente.findOne(search2);
                if (aux != null) {
                    search2.clear();
                    // System.out.println("ja tem esse territorio inserido");
                } else {

                    DBCursor cursor = colTerritorios.find(search2);
                    while (cursor.hasNext()) {

                        aux = cursor.next();
                        // System.out.println("AUX: " + aux.toString());
                        if (Integer.parseInt(aux.get("ci").toString()) == Integer.parseInt(Input2.getCodigo())
                                && Integer.parseInt(aux.get("ano").toString()) == Integer
                                        .parseInt(Input2.getAno_ref())) {
                            // insertCI.append("uf_sigla", aux.get("uf_sigla"));
                            insertCI.append("longitude", Double.parseDouble(aux.get("longitude").toString()));
                            insertCI.append("latitude", Double.parseDouble(aux.get("latitude").toString()));
                            // System.out.println("Achou Territorio");
                        }

                    }
                    insertCI.append("ci", Integer.parseInt(Input2.getI_codigo_amc()));
                    insertCI.append("di", Input2.getTerritorio_nome());
                    insertCI.append("ano_ref", Integer.parseInt(aux.get("ano").toString()));
                    search2.clear();
                    colInput_presente.insert(insertCI);
                    insertCI.clear();
                }

                //Para a coleo com o mesmo nome da base
                insertDemanda.append("ci", Integer.parseInt(Input2.getI_codigo_amc()));
                insertDemanda.append("di", Input2.getTerritorio_nome());
                insertDemanda.append("ck", Integer.parseInt(Input2.getK_classesK_codigo()));
                insertDemanda.append("quant_valor", Double.parseDouble(Input2.getX_valor()));
                insertDemanda.append("ano", Integer.parseInt(Input2.getAno_ref()));

                //Aqui se acha a descrio da K-Classe envolvida, atravs do "k_classesK_codigo"                       
                search2.append("ck", Integer.parseInt(Input2.getK_classesK_codigo()));

                aux = k_classe.findOne(search2);
                insertDemanda.append("dk", (String) aux.get("dk"));
                search2.clear();

                //                    
                colDaDemanda.insert(insertDemanda);

                insertDemanda.clear();

                //   cont++;
                //   System.out.println(cont);
            }
            System.out.println("Inseriu input_presente do assunto: " + assunto);
            //Preparar banco------------------
            System.out.println("Preparando o assunto: " + assunto);
            datadao.prepareDatabase(false, dbAssunto);
            System.out.println("Fim preparar banco do assunto: " + assunto);
            //Fim preparar Banco----------
        } catch (Exception e) {
            e.printStackTrace();

            insert.clear();
            insertCI.clear();
        }

    } else {
        BasicDBObject search = new BasicDBObject();
        DB aux = mongo.getDB("demandas");
        DBCollection colDemandaAtiva = aux.getCollection("demandas_ativas");
        search.append("demanda", assunto.toString());
        boolean situacao = false;
        while (situacao == false) {

            DBCursor demanAtiva = colDemandaAtiva.find(search);
            if (demanAtiva.size() >= 1) {

                situacao = true;
            }
            Thread.currentThread().sleep(5000);
        }

    }

}

From source file:br.rdu.ifpb.mongo.repositorio.PessoaRepositoriMongo.java

@Override
public Pessoa find(String key, String value) {
    Pessoa pessoa = new Pessoa();
    DB db = getConnection();/*from www . j  av a  2 s .  c o m*/
    DBCollection table = db.getCollection("pessoa");
    BasicDBObject query = new BasicDBObject().append(key, value);

    DBCursor result = table.find(query);

    result.hasNext();

    DBObject DBO = result.next();
    pessoa.setId(DBO.toMap().get("_id").toString());
    pessoa.setNome(DBO.toMap().get("nome").toString());
    pessoa.setCpf(DBO.toMap().get("cpf").toString());
    int idade = Integer.parseInt(DBO.toMap().get("idade").toString());
    pessoa.setIdade(idade);

    return pessoa;
}

From source file:br.ufabc.impress.mongo.manager.DBHelper.java

@Override
public String getAll(String tableName) {
    if (tableName == null || tableName.equals("")) {
        return "501";
    }// www .ja  va  2  s .  co  m
    String row = "";
    DBCollection table = db.getCollection(tableName);
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("status", "active");
    DBCursor cursor = table.find(searchQuery);
    if (cursor.size() > 0) {
        JSON json = new JSON();
        row = json.serialize(cursor);
        cursor.close();
        return row;
    } else {
        cursor.close();
        return null;
    }
}

From source file:br.ufabc.impress.mongo.manager.DBHelper.java

@Override
public String getByKey(String tableName, String _id) {
    if (tableName == null || tableName.equals("") || _id == null || _id.equals("")) {
        return "501";
    }//from   www  .  j a v  a2  s  .c  o m
    String row = null;
    DBCursor cursor = null;
    DBCollection table = db.getCollection(tableName);
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("_id", new ObjectId(_id));
    cursor = table.find(searchQuery);
    if (cursor.size() > 0) {
        JSON json = new JSON();
        row = json.serialize(cursor);
        cursor.close();
        return row;
    } else {
        cursor.close();
        return null;
    }
}

From source file:br.ufabc.impress.mongo.manager.DBHelper.java

@Override
public String getByCondition(String tableName, Map condition) {
    if (tableName == null || tableName.equals("") || condition == null || condition.equals("")) {
        return "501";
    }//  w ww  .j  a  va  2  s .c o m
    String row = "";
    DBCollection table = db.getCollection(tableName);
    BasicDBObject searchQuery = new BasicDBObject(condition);
    BasicDBObject andQuery = new BasicDBObject();
    andQuery.put("$and", searchQuery);
    DBCursor cursor = table.find(searchQuery);
    if (cursor.size() > 0) {
        JSON json = new JSON();
        row = json.serialize(cursor);
        cursor.close();
        return row;
    } else {
        cursor.close();
        return null;
    }
}

From source file:BusinessLogic.Service.RestaurantService.java

public Restaurant getBy(String name) {
    ArrayList restaurantConsult = new ArrayList();
    MongoConnection dbSingleton = MongoConnection.getInstance();

    DB db = dbSingleton.getTestdb();/*  w  w w.j a va 2 s.co m*/
    DBCollection coll = db.getCollection(collName);
    BasicDBObject whereQuery = new BasicDBObject();
    // Sentence to search one account number
    whereQuery.put("name", name);

    DBCursor cursor = coll.find(whereQuery);
    while (cursor.hasNext()) {
        DBObject consultDocument = cursor.next();
        restaurantConsult.add(consultDocument.get("name"));
        restaurantConsult.add(consultDocument.get("direccion"));
        restaurantConsult.add(consultDocument.get("phone"));

    }
    Restaurant rs = new Restaurant(whereQuery);
    String response = "";
    response = "Name:" + restaurantConsult.get(0) + " ,Address: " + restaurantConsult.get(1) + " ,Phone: "
            + restaurantConsult.get(2);
    System.out.println(rs);
    return rs;

}

From source file:BusinessLogic.Service.RestaurantService.java

public String update(
        //String name, String direccion, String phone) {
        Restaurant rs) {/*ww  w.  j  a v  a 2s.c o m*/
    String name = rs.getName();
    String direccion = rs.getAddress();
    String phone = rs.getPhone();
    String reservationUpdate = null;
    try {
        // To connect to mongo dbserver
        MongoConnection dbSingleton = MongoConnection.getInstance();
        DB db = dbSingleton.getTestdb();
        DBCollection coll = db.getCollection(collName);

        System.out.println("Collection restaurants selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        // Sentence to search one account number
        whereQuery.put("name", name);

        DBCursor cursor = coll.find(whereQuery);

        while (cursor.hasNext()) {

            DBObject updateDocument = cursor.next();
            updateDocument.put("name", name);
            updateDocument.put("direccion", direccion);
            updateDocument.put("phone", phone);

            coll.update(whereQuery, updateDocument);

        }
        System.out.println("Document updated successfully");
        reservationUpdate = "Success";

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (reservationUpdate != null) {
        return "The restaurant has been updated successfully!";
    } else {
        return "The restaurant has not been updated!";
    }
}

From source file:BusinessLogic.Service.RestaurantService.java

public String delete(String name) {
    String deleteReservation = null;
    try {//from   www .jav  a2 s.  co m
        // To connect to mongo dbserver
        MongoConnection dbSingleton = MongoConnection.getInstance();
        DB db = dbSingleton.getTestdb();
        DBCollection coll = db.getCollection(collName);

        System.out.println("Collection restaurants selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        // Sentence to search one account number
        whereQuery.put("name", name);

        DBCursor cursor = coll.find(whereQuery);

        coll.remove(whereQuery);
        System.out.println("Document deleted successfully");
        deleteReservation = "Success";

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (deleteReservation != null) {
        return "The restaurant has been deleted successfully!";
    } else {
        return "The restaurant has not been deleted!";
    }

}

From source file:buysell.login.java

private void loginSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginSActionPerformed
    // TODO add your handling code here:
    shopping sh1 = new shopping();
    try {//from  w  w  w .j  a  v a  2  s  .c om
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("snehal");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("user");
        System.out.println("Collection created successfully");
        String name = jTextField1.getText().toString();
        String passwd = jPasswordField1.getText().toString();
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", name);
        searchQuery.put("passwd", passwd);

        DBCursor cursor = coll.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 {
            System.out.println("user get");
            sh1.setVisible(true);
            dispose();
        }
        System.out.println("Document inserted successfully");
    } catch (NumberFormatException e) {
        System.out.println();
    }

}