Example usage for com.mongodb QueryBuilder start

List of usage examples for com.mongodb QueryBuilder start

Introduction

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

Prototype

public static QueryBuilder start(final String key) 

Source Link

Document

Creates a new query with a document key

Usage

From source file:it.sayservice.platform.smartplanner.otp.OTPStorage.java

License:Apache License

public List<Object> getObjectsByField(MongoTemplate template, String key, String value, String collectionName,
        Class destinationClass, String orderBy) {
    DBCollection collection = template.getCollection(collectionName);
    List<Object> result = new ArrayList<Object>();

    QueryBuilder qb = QueryBuilder.start(key).is(value);

    DBCursor cursor = collection.find(qb.get());
    if (orderBy != null) {
        BasicDBObject sb = new BasicDBObject();
        sb.put(orderBy, 1);/*  w  ww.  jav a2 s  .  co m*/
        cursor = cursor.sort(sb);
    }

    while (cursor.hasNext()) {
        BasicDBObject dbObject = (BasicDBObject) cursor.next();
        dbObject.remove("_id");

        ObjectMapper mapper = new ObjectMapper();
        Object res = mapper.convertValue(dbObject, destinationClass);
        result.add(res);
    }

    return result;
}

From source file:it.sayservice.platform.smartplanner.otp.OTPStorage.java

License:Apache License

public void bulkDelete(MongoTemplate template, String key, Collection<Object> values, String collectionName) {
    DBCollection collection = template.getCollection(collectionName);
    QueryBuilder qb = QueryBuilder.start(key).notIn(values);

    collection.remove(qb.get());/* w ww.j a v  a 2 s .  c  om*/

}

From source file:it.sayservice.platform.smartplanner.utils.LegGenerator.java

License:Apache License

public static Object getObjectByField(DB db, String key, String value, DBCollection collection,
        Class destinationClass) {
    Object result = null;// w ww. ja v  a2 s.co  m

    QueryBuilder qb = QueryBuilder.start(key).is(value);

    BasicDBObject dbObject = (BasicDBObject) collection.findOne(qb.get());

    if (dbObject != null) {
        dbObject.remove("_id");

        ObjectMapper mapper = new ObjectMapper();
        result = mapper.convertValue(dbObject, destinationClass);
    }

    return result;
}

From source file:javasensei.db.managments.BitacoraEjerciciosManager.java

public String guardarBitacoras(String logBitacoras) {
    JsonParser parser = new JsonParser();
    JsonArray array = parser.parse(logBitacoras).getAsJsonArray();
    List<DBObject> bitacoras = new ArrayList<>();

    synchronized (bitacoraEjercicios) {

        long sesionId = 1;

        //Sesion id
        DBCursor cursor = bitacoraEjercicios.find().sort(QueryBuilder.start("sesionId").is(-1).get()).limit(1);

        if (cursor != null && cursor.hasNext()) {
            sesionId = new Long(cursor.next().get("sesionId").toString()) + 1;
        }//w  w  w .j a  va 2 s  . c o  m

        if (array.size() > 0) {
            for (JsonElement object : array) {
                bitacoras.add(BitacoraEjerciciosDBO.createDbObject(object.getAsJsonObject(), sesionId));
            }

            bitacoraEjercicios.insert(bitacoras);
        }

        return bitacoras.toString();
    }
}

From source file:javasensei.db.managments.RankingManager.java

private int getIdLeccion(int idEjercicio) {
    return new Double(
            ejercicios/*from  ww  w.j av  a  2 s.  c  o  m*/
                    .findOne(QueryBuilder.start("id").is(idEjercicio).get(),
                            QueryBuilder.start("_id").is(0).put("idLeccion").is(1).get())
                    .get("idLeccion").toString()).intValue();
}

From source file:javasensei.db.managments.RankingManager.java

public String getRecommenderResources(int cantidad, int idEjercicio) {
    String result = "[]";

    try {//from   w  w  w  . j  a v a  2s .  c o  m
        int idLeccionPrincipal = getIdLeccion(idEjercicio);

        List<DBObject> listaRecursos = recursos
                .find(QueryBuilder.start("id").in(getRecommendersItemsIDAsArray(recommenderRecursos, cantidad))
                        .put("idLeccion").is(idLeccionPrincipal).get())
                .toArray();

        listaRecursos.replaceAll((DBObject object) -> {
            object.put("ranking",
                    rankingRecursos.findOne(
                            QueryBuilder.start("idRecurso").is(object.get("id")).put("idAlumno")
                                    .is(estudiante.getId()).get(),
                            QueryBuilder.start("_id").is(0).put("ranking").is(1).get()).get("ranking"));

            return object;
        });

        result = listaRecursos.toString();
    } catch (TasteException ex) {
        Logger.getLogger(RankingManager.class.getName()).log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:javasensei.db.managments.RankingManager.java

protected String getRecommenders(DBCollection collection, AbstractRecommender recommender, int cantidad,
        boolean random) {
    String result = "{}";

    List<RecommendedItem> recommenders = new ArrayList<>();
    try {/*from w w  w .j  ava2  s. c  o  m*/
        List<Long> array = new ArrayList();

        try {
            recommenders = getRecommendersItems(recommender, cantidad);//recommenderEjercicios.recommend(estudiante.getId(), cantidad); //5 Recomendaciones
        } catch (Exception ex) {
            System.out.println("El usuario no existe aun en el modelo de datos: " + estudiante.getId());
        }
        //Se agrega un item aleatorio...
        if (random && recommenders.size() < 1) { //RandomRecommender no funciona....

            double number = collection.count();

            DBObject object = collection.find().limit(1).skip((int) Math.floor(Math.random() * number)).next();

            array.add(Math.round(Double.parseDouble(object.get("idEjercicio").toString())));
        }

        //Las recomendaciones se transforman en json array
        for (RecommendedItem item : recommenders) {
            array.add(item.getItemID());
        }

        //Se crea un json array con los id obtenidos de los ejercicios
        result = ejercicios.find(QueryBuilder.start("id").in(array).get()).toArray().toString();
    } catch (Exception ex) {
        JavaException.printMessage(ex, System.out);
    }

    return result;
}

From source file:javasensei.db.managments.RankingManager.java

public boolean colocarRankingDefault() {
    boolean result = false;

    try {//  w w  w  .j a  v a 2 s . co  m
        QueryBuilder query = QueryBuilder.start("id").notIn(rankingEjercicios.distinct("idEjercicio",
                QueryBuilder.start("idAlumno").is(estudiante.getId()).get()));

        //Obtenemos los id de ejercicios que no estan rankeados por el alumno
        //Se colocara un valor 2 de default para dicho ranking, de acuerdo a la escala de LIKERT
        List<DBObject> objects = ejercicios.find(query.get()).toArray();

        if (!objects.isEmpty()) {
            List<DBObject> listObjects = new ArrayList<>();

            for (DBObject object : objects) {
                listObjects.add(BasicDBObjectBuilder.start().add("idEjercicio", object.get("id"))
                        .add("idAlumno", estudiante.getId()).add("ranking", 2) //2 De acuerdo a la escala
                        .get());
            }

            rankingEjercicios.insert(listObjects);

            updateDataModelEjercicios();
        }

        //Mismo proceso para ranking de recursos
        QueryBuilder queryRecursos = QueryBuilder.start("id").notIn(rankingRecursos.distinct("idRecurso",
                QueryBuilder.start("idAlumno").is(estudiante.getId()).get()));

        List<DBObject> idRecursos = recursos.find(queryRecursos.get()).toArray();

        if (!idRecursos.isEmpty()) {
            List<DBObject> listRankingRecursosSave = new ArrayList<>();

            for (DBObject object : idRecursos) {
                listRankingRecursosSave.add(BasicDBObjectBuilder.start().add("idRecurso", object.get("id"))
                        .add("idAlumno", estudiante.getId()).add("ranking", 2) //2 De acuerdo a la escala
                        .get());
            }

            rankingRecursos.insert(listRankingRecursosSave);

            updateDataModelRecursos();
        }

        result = true;

    } catch (Exception ex) {
        System.err.println(ex);
    }

    return result;
}

From source file:me.philnate.textmanager.updates.Update12_12.java

License:Open Source License

private void postCheckNameSplit() {
    // check that no docs with customerName are remaining
    DBCollection customer = ds.getCollection(Customer.class);
    checkArgument(0 == customer.find(QueryBuilder.start("contactName").exists(true).get()).count(),
            "Found customer object with contactName. Should not happen!");
    // check that all have at least a lastName, as customerName was required
    // before/*from ww  w  .  ja v  a  2s .c o  m*/
    checkArgument(customer.getCount() == customer
            .find(QueryBuilder.start("contactName").exists(false).and("lastName").exists(true).get()).count(),
            "Found customer without lastName");
}

From source file:me.philnate.textmanager.utils.PDFCreator.java

License:Open Source License

@SuppressWarnings("deprecation")
private void preparePDF() {
    try {/*from   ww  w.ja  v  a  2 s. co m*/
        File path = new File(SystemUtils.getUserDir(), "template");
        File template = new File(path, Setting.find("template").getValue());

        Velocity.setProperty("file.resource.loader.path", path.getAbsolutePath());
        Velocity.init();
        VelocityContext ctx = new VelocityContext();

        // User data/Settings
        for (Setting setting : ds.find(Setting.class).asList()) {
            ctx.put(setting.getKey(), setting.getValue());
        }

        NumberFormat format = NumberFormat.getNumberInstance(new Locale(Setting.find("locale").getValue()));
        // #60 always show 2 digits for fraction no matter if right most(s)
        // are zero
        format.setMinimumFractionDigits(2);
        format.setMaximumFractionDigits(2);
        ctx.put("number", format);
        // TODO update schema to have separate first and lastname
        // Customer data
        ctx.put("customer", customer);

        // General data
        ctx.put("month", new DateFormatSymbols().getMonths()[month]);
        ctx.put("math", new MathTool());
        // Billing data
        ctx.put("allItems", BillingItem.find(customer.getId(), year, month));
        ctx.put("billNo", bill.getBillNo());

        StringWriter writer = new StringWriter();
        Velocity.mergeTemplate(template.getName(), ctx, writer);
        File filledTemplate = new File(path, bill.getBillNo() + ".tex");
        FileUtils.writeStringToFile(filledTemplate, writer.toString(), "ISO-8859-1");

        ProcessBuilder pdfLatex = new ProcessBuilder(Setting.find("pdfLatex").getValue(),
                "-interaction nonstopmode", "-output-format pdf", filledTemplate.toString());

        // Saving template file (just in case it may be needed later
        GridFSFile texFile = tex.createFile(filledTemplate);
        texFile.put("month", month);
        texFile.put("year", year);
        texFile.put("customerId", customer.getId());
        texFile.save();

        pdfLatex.directory(path);
        String pdfPath = filledTemplate.toString().replaceAll("tex$", "pdf");
        if (0 == printOutputStream(pdfLatex)) {
            // display Bill in DocumentViewer
            new ProcessBuilder(Setting.find("pdfViewer").getValue(), pdfPath).start().waitFor();
            GridFSFile pdfFile = pdf.createFile(new File(pdfPath));
            pdfFile.put("month", month);
            pdfFile.put("year", year);
            pdfFile.put("customerId", customer.getId());
            pdf.remove(QueryBuilder.start("month").is(month).and("year").is(year).and("customerId")
                    .is(customer.getId()).get());
            pdfFile.save();
            File[] files = path.listFiles((FileFilter) new WildcardFileFilter(bill.getBillNo() + ".*"));
            for (File file : files) {
                FileUtils.forceDelete(file);
            }
        } else {
            new JOptionPane(
                    "Bei der Erstellung der Rechnung ist ein Fehler aufgetreten. Es wurde keine Rechnung erstellt.\n Bitte Schauen sie in die Logdatei fr nhere Fehlerinformationen.",
                    JOptionPane.ERROR_MESSAGE).setVisible(true);
        }
    } catch (IOException e) {
        Throwables.propagate(e);
    } catch (InterruptedException e) {
        Throwables.propagate(e);
    }
}