Example usage for com.mongodb.client MongoCollection insertOne

List of usage examples for com.mongodb.client MongoCollection insertOne

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection insertOne.

Prototype

void insertOne(TDocument document);

Source Link

Document

Inserts the provided document.

Usage

From source file:edu.ucuenca.storage.services.PopulateMongoImpl.java

License:Apache License

@Override
public void authorsByArea() {
    final Task task = taskManagerService.createSubTask("Caching Authors by Area", "Mongo Service");
    try (MongoClient client = new MongoClient(conf.getStringConfiguration("mongo.host"),
            conf.getIntConfiguration("mongo.port"));) {
        MongoDatabase db = client.getDatabase(MongoService.Database.NAME.getDBName());

        // Delete and create collection
        final MongoCollection<Document> collection = db
                .getCollection(MongoService.Collection.AUTHORS_AREA.getValue());
        collection.drop();//from w w  w . jav  a2 s  .  c o m

        final List<Map<String, Value>> areas = sparqlService.query(QueryLanguage.SPARQL,
                queriesService.getClusterAndSubclusterURIs());

        task.updateTotalSteps(areas.size());
        BoundedExecutor threadPool = BoundedExecutor.getThreadPool(5);
        for (int i = 0; i < areas.size(); i++) {
            final int j = i;
            final String cluster = areas.get(i).get("cluster").stringValue();
            final String subcluster = areas.get(i).get("subcluster").stringValue();

            threadPool.submitTask(new Runnable() {
                @Override
                public void run() {
                    // Print progress
                    log.info("Relating {}/{}. Cluster: '{}' - Subcluster: '{}'", j + 1, areas.size(), cluster,
                            subcluster);
                    task.updateDetailMessage("Cluster", cluster);
                    task.updateDetailMessage("Subluster", subcluster);
                    task.updateProgress(j + 1);
                    // Get authors of an area from the SPARQL endpoint and transform them to JSON .
                    String authorsByArea = commonService.getsubClusterGraph(cluster, subcluster);
                    Document parse = Document.parse(authorsByArea);
                    BasicDBObject key = new BasicDBObject();
                    key.put("cluster", cluster);
                    key.put("subcluster", subcluster);
                    parse.append("_id", key);
                    collection.insertOne(parse);
                }
            });

        }
        threadPool.end();
    } catch (MarmottaException | InterruptedException ex) {
        log.error(ex.getMessage(), ex);
    } finally {
        taskManagerService.endTask(task);
    }
}

From source file:edu.ucuenca.storage.services.PopulateMongoImpl.java

License:Apache License

@Override
public void authorsByDiscipline() {
    final Task task = taskManagerService.createSubTask("Caching Authors by Discipline", "Mongo Service");
    try (MongoClient client = new MongoClient(conf.getStringConfiguration("mongo.host"),
            conf.getIntConfiguration("mongo.port"));) {
        MongoDatabase db = client.getDatabase(MongoService.Database.NAME.getDBName());

        // Delete and create collection
        final MongoCollection<Document> collection = db
                .getCollection(MongoService.Collection.AUTHORS_DISCPLINE.getValue());
        collection.drop();/*from ww w .j  ava 2s .  co  m*/

        final List<Map<String, Value>> clusters = sparqlService.query(QueryLanguage.SPARQL,
                queriesService.getClusterURIs());

        task.updateTotalSteps(clusters.size());
        BoundedExecutor threadPool = BoundedExecutor.getThreadPool(5);
        for (int i = 0; i < clusters.size(); i++) {
            final int j = i;
            final String cluster = clusters.get(i).get("c").stringValue();
            threadPool.submitTask(new Runnable() {
                @Override
                public void run() {
                    // String subcluster = areas.get(i).get("subcluster").stringValue();
                    // Print progress
                    log.info("Relating {}/{}. Cluster: '{}'", j + 1, clusters.size(), cluster);
                    task.updateDetailMessage("Cluster", cluster);
                    // task.updateDetailMessage("Subluster", subcluster);
                    task.updateProgress(j + 1);
                    // Get authors of an area from the SPARQL endpoint and transform them to JSON .
                    String authorsByDisc = commonService.getClusterGraph(cluster);
                    Document parse = Document.parse(authorsByDisc);
                    BasicDBObject key = new BasicDBObject();
                    key.put("cluster", cluster);
                    //key.put("subcluster", subcluster);
                    parse.append("_id", key);
                    collection.insertOne(parse);
                }
            });

        }
        threadPool.end();
    } catch (MarmottaException | InterruptedException ex) {
        log.error(ex.getMessage(), ex);
    } finally {
        taskManagerService.endTask(task);
    }
}

From source file:edu.ucuenca.storage.services.PopulateMongoImpl.java

License:Apache License

@Override
public void Countries() {
    Task task = taskManagerService.createSubTask("Caching countries", "Mongo Service");
    try (MongoClient client = new MongoClient(conf.getStringConfiguration("mongo.host"),
            conf.getIntConfiguration("mongo.port"));) {
        MongoDatabase db = client.getDatabase(MongoService.Database.NAME.getDBName());

        // Delete and create collection
        MongoCollection<Document> collection = db.getCollection(MongoService.Collection.COUNTRIES.getValue());
        collection.drop();/*from ww w. j a  va  2  s.  co m*/
        try {
            List<Map<String, Value>> countries = sparqlService.query(QueryLanguage.SPARQL,
                    queriesService.getCountries());
            task.updateTotalSteps(countries.size());
            for (int i = 0; i < countries.size(); i++) {
                String co = countries.get(i).get("co").stringValue();
                String code = getCountryCode(co);
                String countriesNodes = countrynodes(co, code).toString();
                Document parse = Document.parse(countriesNodes);
                parse.append("_id", co);
                collection.insertOne(parse);

                task.updateDetailMessage("Country", co);
                task.updateProgress(i + 1);
            }
        } catch (MarmottaException ex) {
            java.util.logging.Logger.getLogger(PopulateMongoImpl.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            taskManagerService.endTask(task);
        }
    }
}

From source file:edu.ucuenca.storage.services.PopulateMongoImpl.java

License:Apache License

@Override
public void LoadStatisticsbyAuthor() {
    final Task task = taskManagerService.createSubTask("Caching statistics by Author", "Mongo Service");
    try (MongoClient client = new MongoClient(conf.getStringConfiguration("mongo.host"),
            conf.getIntConfiguration("mongo.port"));) {
        MongoDatabase db = client.getDatabase(MongoService.Database.NAME.getDBName());
        MongoCollection<Document> collection = db
                .getCollection(MongoService.Collection.STATISTICS_AUTHOR.getValue());
        collection.drop();//w w  w.  j a  v  a  2s  . c o  m

        List<String> queries = new ArrayList();
        queries.add("date");
        queries.add("keywords");
        queries.add("providers");
        queries.add("provenance");
        queries.add("conference");

        final String uri = "";
        String name = "";
        String fullname = "";
        final List<Map<String, Value>> authors = sparqlService.query(QueryLanguage.SPARQL,
                queriesService.getAuthorsCentralGraph());
        Document parse = new Document();
        task.updateTotalSteps(authors.size());
        int ints = 0;
        // final int j = 0;
        for (Map<String, Value> o : authors) {
            //  j++;
            ints++;

            final String a = o.get("a").stringValue();
            task.updateDetailMessage("Author ", a);
            final SynchronizedParse sp = new SynchronizedParse();
            BoundedExecutor threadPool = BoundedExecutor.getThreadPool(5);

            log.info("Stats {} ", a);
            log.info("Stats {}/{}. Author: '{}' ", ints, authors.size(), a);
            //task.updateDetailMessage("URI", a);
            task.updateProgress(ints);
            for (final String q : queries) {

                threadPool.submitTask(new Runnable() {
                    @Override
                    public void run() {

                        String response;
                        try {
                            response = statisticsbyAuthorsQuery(a, q);
                            sp.appendParse(Document.parse(response), q);

                        } catch (MarmottaException ex) {
                            java.util.logging.Logger.getLogger(PopulateMongoImpl.class.getName())
                                    .log(Level.SEVERE, null, ex);
                        }

                    }
                });

                /*  ints++;
                          uri = a;
                          parse.append(q, Document.parse(response));
                        
                          log.info("Stats Author {} ", uri);
                          log.info("Query {}", q);
                        
                          task.updateProgress(ints);*/
            }
            threadPool.end();
            Document authorp = sp.getDoc();
            authorp.append("_id", a);
            // parse.append("name", name);
            // parse.append("fullname", fullname);
            collection.insertOne(authorp);
        }
        taskManagerService.endTask(task);
        // loadStadistics(MongoService.Collection.STATISTICS.getValue(), queries);
    } catch (MarmottaException ex) {
        log.error("erro" + ex);
        java.util.logging.Logger.getLogger(PopulateMongoImpl.class.getName()).log(Level.INFO, null, ex);
    } catch (InterruptedException ex) {
        java.util.logging.Logger.getLogger(PopulateMongoImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.ucuenca.storage.services.ProfileValidationImpl.java

@Override
public String saveProfileData(String jsondata, String id, String uri, String prof) {
    try (MongoClient client = new MongoClient(conf.getStringConfiguration("mongo.host"),
            conf.getIntConfiguration("mongo.port"));) {

        MongoDatabase db = client.getDatabase(MongoService.Database.NAME.getDBName());

        // Delete and create collection
        MongoCollection<Document> collection = db
                .getCollection(MongoService.Collection.PROFILE_AUTHOR.getValue());
        // collection.drop();

        // ObjectMapper objectMapper = new ObjectMapper();
        mongos.removeProfileValAuthor(id);
        Document parse = Document.parse(jsondata);
        Document parseprof = Document.parse(prof);
        parse.append("_id", id);
        parse.append("uri", uri);
        parse.append("uri", uri);
        parse.append("profile", parseprof);
        collection.insertOne(parse);

        return "";
    }/* w w  w .  jav  a  2  s .com*/

}

From source file:edu.uniandes.ecos.codeaholics.config.DataBaseUtil.java

/***
 * Adiciona el Documentos en la coleccion especificada.
 * //from w  w  w.ja v  a  2 s  .c  o m
 * @param pRegister
 *            registro que se desea adicionar
 * @param pCollection
 *            colection de destino
 */
public static void save(Document pRegister, String pCollection) throws MongoWriteException {

    log.debug("Saving " + pRegister);
    log.debug("In Collection " + pCollection);
    MongoCollection<Document> collection = db.getCollection(pCollection);

    //TODO: check this ... this will never throw an exception since we always insert documents by _id
    collection.insertOne(pRegister);

    log.info("-----------------------------------");
    log.info("Successful Insert");
    log.info("-----------------------------------");

}

From source file:entities.fertilizacion.AnalisisLaboratorio.java

public ObjectId save() {
    MongoManager mongo = MongoManager.getInstance();

    List<Document> elementos = new ArrayList<>();
    for (int i = 0; i < listadoElementos.size(); i++) {
        Document aux = new Document().append("elemento", listadoElementos.get(i).id);
        elementos.add(aux);// ww  w.  j a va  2 s.  c  o m
    }

    MongoCollection table = mongo.db.getCollection("analisislaboratorio");
    Document obj = new Document("codigo", this.codigo).append("matriz", this.matriz)
            .append("laboratorio", this.laboratorio).append("descripcion", this.descripcion)
            .append("costo", BDecimalToStr(this.costo)).append("darBaja", this.darBaja)
            .append("elementos", elementos);
    table.insertOne(obj);

    return (ObjectId) obj.get("_id");
}

From source file:entities.fertilizacion.Cliente.java

public ObjectId save() {
    MongoManager mongo = MongoManager.getInstance();

    MongoCollection table = mongo.db.getCollection("cliente");

    Document obj = new Document("codigo", this.codigo).append("nombre", this.nombre.toUpperCase())
            .append("tipo", this.tipo).append("rucci", this.rucCi).append("mercado", this.mercado)
            .append("afacturar", this.afacturar).append("vendedor", this.vendedor)
            .append("direccion", this.direccion).append("pais", this.pais).append("provincia", this.provincia)
            .append("canton", this.canton).append("sector", this.sector)
            .append("atencionfactura", this.atencionFactura).append("tipoCliente", this.tipoCliente)
            .append("departamento", this.departamento).append("observacionGenerico", this.observacionGenerico);

    List<String> ltelf = this.telefono;
    StringBuilder auxtelf = new StringBuilder(75);
    for (int i = 0; i < ltelf.size(); i++) {
        auxtelf.append(ltelf.get(i)).append(";");
    }//  www.j  a  v a2s.c  o  m

    List<String> lmail = this.email;
    StringBuilder auxmail = new StringBuilder(75);
    for (int j = 0; j < lmail.size(); j++) {
        auxmail.append(lmail.get(j)).append(";");
    }

    table.insertOne(obj.append("telefono", auxtelf.toString()).append("email", auxmail.toString()));

    return (ObjectId) obj.get("_id");
}

From source file:entities.fertilizacion.Codigo.java

public ObjectId save() {
    MongoManager mongo = MongoManager.getInstance();

    MongoCollection table = mongo.db.getCollection("codigo");

    Document obj = new Document("nombre", this.nombre.toUpperCase()).append("simbolo", this.simbolo)
            .append("modificarSecuencial", this.modificarSecuencial);

    table.insertOne(obj);

    return (ObjectId) obj.get("_id");
}

From source file:entities.fertilizacion.CompuestoQuimico.java

public void save() {
    MongoManager mongo = MongoManager.getInstance();

    MongoCollection table = mongo.db.getCollection("compuesto");

    Document obj = new Document("simbolo", this.simbolo).append("nombre", this.nombre)
            .append("valor", BDecimalToStr(this.valor)).append("peso", BDecimalToStr(this.peso));
    table.insertOne(obj);
}