Example usage for com.mongodb BasicDBObject append

List of usage examples for com.mongodb BasicDBObject append

Introduction

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

Prototype

@Override
public BasicDBObject append(final String key, final Object val) 

Source Link

Document

Add a key/value pair to this object

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 2s. c  o m*/
    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   www .  ja  v a  2 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  www . ja 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:byusentiment.Byusentiment.java

public static void loadTweets() throws IOException {
    try {//from   ww  w.  jav a2 s  .com
        CSVReader reader = new CSVReader(new FileReader("tweets-2.csv"));
        //reader.readNext();
        List myEntries = reader.readAll();
        String[] headers = (String[]) myEntries.get(0);

        //Adding data to the DbObject
        List<DBObject> toInsert = new ArrayList<DBObject>();
        for (int i = 1; i < myEntries.size(); i++) {
            BasicDBObject doc = new BasicDBObject();
            String[] row = (String[]) myEntries.get(i);

            for (int j = 0; j < row.length; j++) {
                doc.append(headers[j], row[j]);
            }
            toInsert.add(doc);
        }

        //Inserting data into the database             
        Byusentiment.coll.insert(toInsert);

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

From source file:Candidate.ArcCandidate.ArcCandidate.java

@Override
public BasicDBObject toDBObject() {
    BasicDBObject ret = super.toDBObject();

    ArrayList<String> rels = new ArrayList<>();
    for (Entry<Source, OntologicalElement> e : this.uriImplicate.entrySet()) {
        String[] elems = e.getValue().getUri().split(" ");
        if (this.dataProperty.startsWith("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")) {
            rels.add("&lt;" + elems[0] + "&gt; a &lt;" + elems[2] + "&gt;");
        } else if (this.dataProperty.startsWith("http://ontology.irstea.fr/AgronomicTaxon#hasHigherRank")) {
            rels.add("&lt;" + elems[0] + "&gt; &lt;" + this.dataProperty + "&gt; &lt;" + elems[2] + "&gt;");
        } else {//from w  ww.j  ava2s.c  o m
            String regexp = "^&lt;" + this.fromCandidate.getUriFromSource(e.getKey()).getUri() + "&gt;.*"
                    + e.getValue().getUri() + "[\\.,\\[]";
            rels.add(regexp);
        }
    }
    ret.append("rels", rels);

    return ret;
}

From source file:Candidate.Candidate.java

public BasicDBObject toDBObject() {
    BasicDBObject doc = new BasicDBObject();
    ArrayList<BasicDBObject> elemCandidates = new ArrayList<>();
    for (Entry<Source, OntologicalElement> e : this.uriImplicate.entrySet()) {
        Source s = e.getKey();/* w  ww.  j a  v a 2 s .  c om*/
        String elem = e.getValue().getUri();
        if (!elem.isEmpty()) {
            BasicDBObject elemC = new BasicDBObject();
            elemC.append("source", s.toDBObject());
            elemC.append("elem", elem);
            elemCandidates.add(elemC);
        }
    }
    doc.append("elemCandidates", elemCandidates);
    doc.append("trustScoreChoquet", this.getTrustScore());
    doc.append("trustScoreSimple", this.trustSimple);

    return doc;
}

From source file:Candidate.NodeCandidate.NodeCandidate.java

@Override
public BasicDBObject toDBObject() {
    BasicDBObject doc = super.toDBObject();
    ArrayList<BasicDBObject> alignsObject = new ArrayList<>();
    for (Alignment al : aligns) {
        BasicDBObject alignDoc = new BasicDBObject();
        alignDoc.append("uri1", al.getUri());
        alignDoc.append("uri2", al.getUriAlign());
        alignDoc.append("trustScore", al.getValue());
        alignsObject.add(alignDoc);//from  ww w.  java  2  s . com
    }
    doc.append("aligns", alignsObject);
    doc.append("ncId", this.id);
    doc.append("alreadyValidated", this.alreadyValidated);
    doc.append("trustScoreDegree", this.trustDegree);

    return doc;
}

From source file:ch.bfh.uniboard.persistence.mongodb.PersistenceService.java

License:GNU General Public License

@Override
public ResultContainer get(Query query) {
    try {/*from ww  w.jav  a2  s.  c  om*/
        //Check Database connection
        if (!this.connectionManager.isConnected()) {
            Attributes gamma = new Attributes();
            gamma.add(Attributes.ERROR, new StringValue("Internal Server Error. Service not available"));
            logger.log(Level.WARNING, "Database error: unable to connect to database");
            return new ResultContainer(new ArrayList<Post>(), gamma);
        }

        //TODO Remove this block and its tests
        //check basic wellformedness of query
        if (query == null || query.getConstraints() == null || query.getConstraints().isEmpty()
                || query.getConstraints().contains(null)) {
            Attributes gamma = new Attributes();
            gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Incomplete query"));
            logger.log(Level.WARNING, "Syntax error: Incomplete query");
            return new ResultContainer(new ArrayList<Post>(), gamma);
        }

        List<DBObject> constraintsList = new ArrayList<>();

        //iterates over the constraints and constructs the corresponding query string
        for (Constraint c : query.getConstraints()) {

            //constructs the key
            String keyString = "";
            if (c.getIdentifier() instanceof MessageIdentifier) {
                //TODO constraint that wants to compare the raw byte[]
                keyString += "searchable-message";
            } else if (c.getIdentifier() instanceof AlphaIdentifier) {
                keyString += "alpha";
            } else if (c.getIdentifier() instanceof BetaIdentifier) {
                keyString += "beta";
            } else {
                Attributes gamma = new Attributes();
                gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Unknown identifier"));
                logger.log(Level.WARNING, "Syntax error: Unknown identifier");
                return new ResultContainer(new ArrayList<Post>(), gamma);
            }

            //constructs the hierarchy of the keys
            for (String key : c.getIdentifier().getParts()) {
                keyString += "." + key;
            }

            //constructs the researched value string by checking the type of constraints and getting the searched values
            DBObject actualConstraint = new BasicDBObject();
            if (c instanceof Equal) {
                Equal op = (Equal) c;
                actualConstraint.put(keyString, op.getValue().getValue());
            } else if (c instanceof NotEqual) {
                NotEqual op = (NotEqual) c;
                actualConstraint.put(keyString, new BasicDBObject("$ne", op.getValue().getValue()));
            } else if (c instanceof In) {
                In op = (In) c;
                List<Object> values = new ArrayList<>();
                Class valueClass = op.getSet().get(0).getClass();
                for (Value v : op.getSet()) {
                    if (!(v.getClass().equals(valueClass))) {
                        Attributes gamma = new Attributes();
                        gamma.add(Attributes.REJECTED,
                                new StringValue("Syntax error: not same value type for IN constraint"));
                        logger.log(Level.WARNING, "Syntax error: not same value type for IN constraint");
                        return new ResultContainer(new ArrayList<Post>(), gamma);
                    }
                    values.add(v.getValue());
                }
                actualConstraint.put(keyString, new BasicDBObject("$in", values));
            } else if (c instanceof Between) {
                Between op = (Between) c;
                if (!(op.getStart().getClass().equals(op.getEnd().getClass()))) {
                    Attributes gamma = new Attributes();
                    gamma.add(Attributes.REJECTED,
                            new StringValue("Syntax error: not same value type for BETWEEN constraint"));
                    logger.log(Level.WARNING, "Syntax error: not same value type for BETWEEN constraint");
                    return new ResultContainer(new ArrayList<Post>(), gamma);
                }
                actualConstraint.put(keyString, new BasicDBObject("$gt", op.getStart().getValue()).append("$lt",
                        op.getEnd().getValue()));
            } else if (c instanceof Greater) {
                Greater op = (Greater) c;
                actualConstraint.put(keyString, new BasicDBObject("$gt", op.getValue().getValue()));
            } else if (c instanceof GreaterEqual) {
                GreaterEqual op = (GreaterEqual) c;
                actualConstraint.put(keyString, new BasicDBObject("$gte", op.getValue().getValue()));
            } else if (c instanceof Less) {
                Less op = (Less) c;
                actualConstraint.put(keyString, new BasicDBObject("$lt", op.getValue().getValue()));
            } else if (c instanceof LessEqual) {
                LessEqual op = (LessEqual) c;
                actualConstraint.put(keyString, new BasicDBObject("$lte", op.getValue().getValue()));
            } else {
                Attributes gamma = new Attributes();
                gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Unknown type of constraint"));
                logger.log(Level.WARNING, "Syntax error: Unknown type of constraint");
                return new ResultContainer(new ArrayList<Post>(), gamma);
            }
            constraintsList.add(actualConstraint);
        }

        //combine the different constrainst in an AND query
        DBObject completeQuery = new BasicDBObject();
        completeQuery.put("$and", constraintsList);

        DBCursor cursor;

        if (query.getOrder().size() > 0) {

            //Create orderBy
            BasicDBObject orderBy = new BasicDBObject();

            for (Order order : query.getOrder()) {
                String identifier;
                if (order.getIdentifier() instanceof MessageIdentifier) {
                    identifier = "message";
                } else if (order.getIdentifier() instanceof AlphaIdentifier) {
                    identifier = "alpha";
                } else if (order.getIdentifier() instanceof BetaIdentifier) {
                    identifier = "beta";
                } else {
                    Attributes gamma = new Attributes();
                    gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Unknown identifier"));
                    logger.log(Level.WARNING, "Syntax error: Unknown identifier");
                    return new ResultContainer(new ArrayList<Post>(), gamma);
                }
                for (String key : order.getIdentifier().getParts()) {
                    identifier += "." + key;
                }
                int ascDesc;
                if (order.isAscDesc()) {
                    ascDesc = 1;
                } else {
                    ascDesc = -1;
                }
                orderBy.append(identifier, ascDesc);
            }
            cursor = this.connectionManager.getCollection().find(completeQuery).sort(orderBy)
                    .limit(query.getLimit());
        } else {
            //apply query on database
            cursor = this.connectionManager.getCollection().find(completeQuery).limit(query.getLimit());
        }

        //creates the result container with the db result
        List<Post> list = new ArrayList<>();
        while (cursor.hasNext()) {
            DBObject object = cursor.next();
            //convert to PersistedPost
            list.add(PersistedPost.fromDBObject(object));
        }
        return new ResultContainer(list, new Attributes());
    } catch (Exception e) {
        Attributes gamma = new Attributes();
        gamma.add(Attributes.ERROR, new StringValue("General error: " + e.getMessage()));
        logger.log(Level.WARNING, "General Get error", e);
        return new ResultContainer(new ArrayList<Post>(), gamma);
    }
}

From source file:ch.qos.logback.contrib.mongodb.MongoDBAccessEventAppender.java

License:Open Source License

/**
 * {@inheritDoc}/*from ww w  . j  ava2s . c o m*/
 */
@Override
protected BasicDBObject toMongoDocument(IAccessEvent event) {
    final BasicDBObject doc = new BasicDBObject();
    doc.append("timeStamp", new Date(event.getTimeStamp()));
    if (serverName)
        doc.append("serverName", event.getServerName());
    addRemote(doc, event);
    addRequest(doc, event);
    addResponse(doc, event);
    return doc;
}

From source file:ch.qos.logback.contrib.mongodb.MongoDBAccessEventAppender.java

License:Open Source License

private void addRemote(BasicDBObject parent, IAccessEvent event) {
    final BasicDBObject remote = new BasicDBObject();
    final String host = event.getRemoteHost();
    if (remoteHost && host != null)
        remote.append("host", host);
    final String remoteUserName = event.getRemoteUser();
    if (remoteUser && remoteUserName != null && !remoteUserName.equals("-")) {
        remote.append("user", remoteUserName);
    }//from w w  w  .  j  ava 2  s .c  o m
    final String addr = event.getRemoteAddr();
    if (remoteAddr && addr != null)
        remote.append("addr", addr);
    if (!remote.isEmpty())
        parent.put("remote", remote);
}