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:br.com.teste.mongo.MongoTeste.java

public void salvar(String termo, String nomeDoArquivo, String enderecoDoArquivo) {
    DB db = connect();/*from  w w w. ja v a  2 s . c  om*/
    DBCollection collection = db.getCollection(termo);
    BasicDBObject object = new BasicDBObject();
    object.append(nomeDoArquivo, enderecoDoArquivo);
    collection.insert(object);
}

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 w ww  .ja  v  a 2 s  .c o m*/
            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  ww w .java2s.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.gov.frameworkdemoiselle.component.audit.processors.rest.MONGOProcessors.java

License:Open Source License

/**
 *
 * @param trail/*  w  ww  . j  av a  2  s.  com*/
 */
@Override
public void execute(@Observes @AuditProcessor Trail trail) {

    super.execute(trail);

    try {
        //TODO Verificar alternativas para superar a depreciao das classes abaixo
        MongoClient mongo = new MongoClient(config.getServerUrl());
        DB db = mongo.getDB(config.getDataBaseName());
        DBCollection table = db.getCollection(config.getTableName());

        BasicDBObject document = new BasicDBObject();
        document.put("ClassName", trail.getClassName());
        document.put("How", trail.getHow());
        document.put("IdName", trail.getIdName());
        document.put("LayerName", trail.getLayerName());
        document.put("ObjSerial", trail.getObjSerial());
        document.put("ProcessorName", trail.getProcessorName());
        document.put("Profile", trail.getProfile());
        document.put("SystemName", trail.getSystemName());
        document.put("UserName", trail.getUserName());
        document.put("What", trail.getWhat());
        document.put("When", trail.getWhen());
        document.put("Where", trail.getWhere());
        table.insert(document);

    } catch (Exception e) {
        fail("MONGOProcessors :" + e.getMessage(), trail);
    }
}

From source file:br.gov.frameworkdemoiselle.component.billing.processors.mongo.MONGOProcessors.java

License:Open Source License

/**
 *
 * @param trail//from   w  w  w.j  a v a  2  s .com
 */
@Override
public void execute(@Observes @BillingProcessor Trail trail) {

    super.execute(trail);

    try {
        //TODO Verificar alternativas para superar a depreciao das classes abaixo
        MongoClient mongo = new MongoClient(config.getServerUrl());
        DB db = mongo.getDB(config.getDataBaseName());
        Boolean authentication = Boolean.TRUE;

        if (!"".equals(config.getDatabaseUser())) {
            authentication = db.authenticate(config.getDatabaseUser(), config.getDatabasePass().toCharArray());
        }

        if (authentication) {
            DBCollection table = db.getCollection(config.getCollectionName());

            BasicDBObject document = new BasicDBObject();
            document.put("ClassName", trail.getClassName());
            document.put("IdName", trail.getIdName());
            document.put("LayerName", trail.getLayerName());
            document.put("ObjSerial", trail.getObjSerial());
            document.put("ProcessorName", trail.getProcessorName());
            document.put("Profile", trail.getProfile());
            document.put("SystemName", trail.getSystemName());
            document.put("UserName", trail.getUserName());
            document.put("What", trail.getWhat());
            document.put("When", trail.getWhen());
            document.put("Where", trail.getWhere());
            table.insert(document);
        } else {
            fail("MONGOProcessors : Authentication failed!", trail);
            throw new RuntimeException("Authentication failed!");
        }

    } catch (Exception e) {
        fail("MONGOProcessors :" + e.getMessage(), trail);
    }
}

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

@Override
public int add(Pessoa pessoa) {
    getConnection();//from w  ww .java 2  s.  co m
    DB db = getConnection();
    DBCollection table = db.getCollection("pessoa");
    //
    BasicDBObject document = new BasicDBObject();
    document.put("nome", pessoa.getNome());
    document.put("cpf", pessoa.getCpf());
    document.put("idade", pessoa.getIdade());

    result = table.insert(document).getN();
    closeConnection(mongo);
    return result;
}

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

@Override
public String add(String tableName, String json) {
    if (tableName == null || tableName.equals("") || json == null || json.equals("")) {
        return "501";
    }/*from  ww  w .  j  a v  a2  s  . c o  m*/
    DBCollection table = db.getCollection(tableName);
    DBObject dbObject = (DBObject) JSON.parse(json);
    WriteResult wRes = table.insert(dbObject);
    return ((ObjectId) dbObject.get("_id")).toString();
}

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

@Override
public String addByMap(String tableName, Map columns) {
    if (tableName == null || tableName.equals("") || columns == null || columns.equals("")) {
        return "501";
    }//from  w  w  w  .j  a va 2 s .  com
    DBCollection table = db.getCollection(tableName);
    BasicDBObject document = new BasicDBObject(columns);
    WriteResult wRes = table.insert(document);
    return ((ObjectId) document.get("_id")).toString();
}

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

@Override
public String addDefault(String tableName, String json) {
    if (tableName == null || tableName.equals("") || json == null || json.equals("")) {
        return "501";
    }//from www.  j av  a 2  s.co  m
    DBCollection table = db.getCollection(tableName);
    DBObject dbObject = (DBObject) JSON.parse(json);
    dbObject.put("status", "active");
    dbObject.put("createDate", System.currentTimeMillis() + "");
    dbObject.put("updateDate", System.currentTimeMillis() + "");
    WriteResult wRes = table.insert(dbObject);
    return ((ObjectId) dbObject.get("_id")).toString();
}

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

@Override
public String addDefaultMap(String tableName, Map columns) {
    if (tableName == null || tableName.equals("") || columns == null || columns.equals("")) {
        return "501";
    }//  w ww. j a  va  2  s.  c o  m
    columns.put("status", "active");
    columns.put("createDate", System.currentTimeMillis() + "");
    columns.put("updateDate", System.currentTimeMillis() + "");
    DBCollection table = db.getCollection(tableName);
    BasicDBObject document = new BasicDBObject(columns);
    WriteResult wRes = table.insert(document);
    return ((ObjectId) document.get("_id")).toString();
}