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() 

Source Link

Document

Returns a new QueryBuilder.

Usage

From source file:io.hawkcd.services.PipelineService.java

License:Apache License

@Override
@Authorization(scope = PermissionScope.PIPELINE, type = PermissionType.VIEWER)
public ServiceResult getAllNonupdatedPipelines() {
    ServiceResult result = null;/*from w w  w.ja  v a 2s  .  c  o  m*/

    switch (super.DATABASE_TYPE) {
    case REDIS:
        result = this.getAll();
        List<Pipeline> pipelines = (List<Pipeline>) result.getEntity();

        List<Pipeline> updatedPipelines = pipelines.stream().filter(p -> !p.areMaterialsUpdated())
                .sorted((p1, p2) -> p1.getStartTime().compareTo(p2.getStartTime()))
                .collect(Collectors.toList());

        result.setEntity(updatedPipelines);
        break;
    case MONGODB:
        BasicDBObject query = (BasicDBObject) QueryBuilder.start().put("areMaterialsUpdated").is(false).get();
        BasicDBObject sortingFiler = new BasicDBObject("startTime", 1);
        result = this.getPipelineMongoService().QueryExecutor(query, sortingFiler);
        break;
    }

    return result;
}

From source file:io.hawkcd.services.PipelineService.java

License:Apache License

@Override
@Authorization(scope = PermissionScope.PIPELINE, type = PermissionType.VIEWER)
public ServiceResult getLastRun(String pipelineDefinitionId) {
    ServiceResult result = null;//from  w ww  .j  av  a  2 s  . co  m

    switch (super.DATABASE_TYPE) {
    case REDIS:
        result = this.getAllByDefinitionId(pipelineDefinitionId);
        List<Pipeline> pipelines = (List<Pipeline>) result.getEntity();

        Pipeline lastRun = null;
        int lastExecutionId = 0;
        for (Pipeline pipeline : pipelines) {
            if (pipeline.getExecutionId() > lastExecutionId) {
                lastRun = pipeline;
                lastExecutionId = pipeline.getExecutionId();
            }
        }

        result.setEntity(lastRun);
        break;
    case MONGODB:
        BasicDBObject query = (BasicDBObject) QueryBuilder.start().put("pipelineDefinitionId")
                .is(pipelineDefinitionId).get();
        BasicDBObject sortingFiler = new BasicDBObject("executionId", -1);

        result = this.getPipelineMongoService().QueryExecutor(query, sortingFiler, 0, 1);
        result.setEntity((Pipeline) ((ArrayList) this.getPipelineMongoService()
                .QueryExecutor(query, sortingFiler, 0, 1).getEntity()).get(0));
        break;
    }

    return result;
}

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

License:Apache License

private SymbolicRouteDayInfoHashCalendar findDayInfo(String router, String agencyId, String routeId,
        String date, boolean symbolic) {
    if (symbolic) {

        QueryBuilder qb = QueryBuilder.start();
        qb.and("routeId").is(routeId);
        qb.and("agencyId").is(agencyId);

        List<SymbolicRouteDayInfoHashCalendar> symbolicInfos = (List) storage.getObjectsByQuery(
                mongoRouterMapper.getMongoTemplateMap().get(router), qb.get(), Constants.AGENCY_INFO,
                SymbolicRouteDayInfoHashCalendar.class, null);

        SymbolicRouteDayInfoHashCalendar si = symbolicInfos.get(0);

        return si;

    } else {/*from   w w  w  .  ja v  a 2 s  . c  o m*/
        return null;
    }
}

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

License:Apache License

private List<TripSchedule> getSchedule(String router, String agencyId, String routeId, int day, String date,
        String collectionName, boolean symbolic) {
    QueryBuilder qb = QueryBuilder.start();

    if (symbolic) {
        qb.and("symbolicRouteIds").is(routeId);
    } else {/*from w  w w . j  av a2s . c  om*/
        qb = qb.and("routeId").is(routeId);
    }
    qb = qb.and("agencyId").is(agencyId);
    qb = qb.and("days").is(day);
    qb = qb.and("daysRemoved").notEquals(date);
    qb = qb.and("fromDate").lessThanEquals(date);
    qb = qb.and("toDate").greaterThanEquals(date);

    List<TripSchedule> schedules = (List) storage.getObjectsByQuery(
            mongoRouterMapper.getMongoTemplateMap().get(router), qb.get(), collectionName, TripSchedule.class,
            "routeId");

    qb = QueryBuilder.start();
    if (symbolic) {
        qb.and("symbolicRouteIds").is(routeId);
    } else {
        qb = qb.and("routeId").is(routeId);
    }
    qb = qb.and("agencyId").is(agencyId);
    qb = qb.and("daysAdded").is(date);
    qb = qb.and("fromDate").lessThanEquals(date);
    qb = qb.and("toDate").greaterThanEquals(date);

    List<TripSchedule> addedSchedules = (List) storage.getObjectsByQuery(
            mongoRouterMapper.getMongoTemplateMap().get(router), qb.get(), collectionName, TripSchedule.class,
            "routeId");
    for (TripSchedule toCheck : addedSchedules) {
        if (!schedules.contains(toCheck)) {
            schedules.add(toCheck);
        }
    }

    qb = QueryBuilder.start();
    if (symbolic) {
        qb.and("symbolicRouteIds").is(routeId);
        qb = qb.and("agencyId").is(agencyId);
        qb = qb.and("daysAdded").is(date);
        qb = qb.and("fromDate").lessThanEquals(date);
        qb = qb.and("toDate").greaterThanEquals(date);

        QueryBuilder fb = QueryBuilder.start();
        fb = fb.and("times").is("1");
        fb = fb.and("order").is("1");

        List<TripSchedule> toRemove = Lists.newArrayList();
        for (TripSchedule ts : schedules) {
            qb = QueryBuilder.start();
            qb = qb.and("agencyId").is(agencyId);
            qb = qb.and("tripId").is(ts.getTripId());

            List<AnnotatedTrip> annotatedTrips = (List) storage.getObjectsByQuery(
                    mongoRouterMapper.getMongoTemplateMap().get(router), qb.get(), Constants.ANNOTATED_TRIPS,
                    AnnotatedTrip.class, null, fb.get());
            if (!annotatedTrips.isEmpty()) {
                try {
                    List<String> times = (List) annotatedTrips.get(0).getTimes();
                    ts.setTimes(times.toArray(new String[times.size()]));
                    ts.setOrder(annotatedTrips.get(0).getOrder());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                System.err.println("Annotated trip not found for " + ts.getTripId());
                toRemove.add(ts);
            }

        }

        schedules.removeAll(toRemove);
    }
    Collections.sort(schedules);

    return schedules;
}

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

License:Apache License

public Object getObjectByFields(MongoTemplate template, Map<String, Object> map, String collectionName,
        Class destinationClass) {
    DBCollection collection = template.getCollection(collectionName);

    QueryBuilder qb = QueryBuilder.start();
    for (String key : map.keySet()) {
        qb = qb.and(key).is(map.get(key));
    }/*from   w  w  w .  j a  v  a  2 s.  co m*/

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

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

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

        return result;
    } else {
        return null;
    }
}

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

License:Apache License

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

    QueryBuilder qb = QueryBuilder.start();
    for (String key : map.keySet()) {
        qb = qb.and(key).is(map.get(key));
    }//from w ww  . j  av a  2s.  c  o m

    DBCursor cursor = collection.find(qb.get());
    if (orderBy != null) {
        BasicDBObject sb = new BasicDBObject();
        sb.put(orderBy, 1);
        cursor = cursor.sort(sb);
    }

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

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

    return result;
}

From source file:kina.examples.java.ReadingCellFromMongoDB.java

License:Apache License

public static void doMain(String[] args) {
    String job = "java:readingCellFromMongoDB";

    String host = "127.0.0.1:27017";

    String database = "test";
    String inputCollection = "input";

    // Creating the Kina Context where args are Spark Master and Job Name
    ContextProperties p = new ContextProperties(args);
    MongoKinaContext kinaContext = new MongoKinaContext(p.getCluster(), job, p.getSparkHome(), p.getJars());

    QueryBuilder query = QueryBuilder.start();
    query.and("number").greaterThan(27).lessThan(30);

    BSONObject bsonSort = new BasicBSONObject();
    bsonSort.put("number", 1);

    BSONObject bsonFields = new BasicBSONObject();
    bsonFields.put("number", 1);
    bsonFields.put("text", 1);
    bsonFields.put("_id", 0);

    MongoKinaConfig inputConfigEntity = MongoConfigFactory.createMongoDB().host(host).database(database)
            .collection(inputCollection).createInputSplit(false).filterQuery(query).sort(bsonSort)
            .fields(bsonFields).initialize();

    RDD inputRDDEntity = kinaContext.mongoRDD(inputConfigEntity);

    LOG.info("count : " + inputRDDEntity.count());
    LOG.info("prints first cell  : " + inputRDDEntity.first());

    kinaContext.stop();/*from   ww  w .j av a 2 s  .  co m*/
}

From source file:net.atos.entng.forum.services.impl.MongoDbCategoryService.java

License:Open Source License

@Override
public void list(UserInfos user, Handler<Either<String, JsonArray>> handler) {
    // Start/*from  w w w . j a v a2  s. c o  m*/
    QueryBuilder query = QueryBuilder.start();

    // Permissions Filter
    List<DBObject> groups = new ArrayList<>();
    groups.add(QueryBuilder.start("userId").is(user.getUserId()).get());
    for (String gpId : user.getProfilGroupsIds()) {
        groups.add(QueryBuilder.start("groupId").is(gpId).get());
    }
    query.or(QueryBuilder.start("owner.userId").is(user.getUserId()).get(), QueryBuilder.start("shared")
            .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get()).get());

    JsonObject sort = new JsonObject().putNumber("modified", -1);
    mongo.find(categories_collection, MongoQueryBuilder.build(query), sort, null, validResultsHandler(handler));
}

From source file:net.atos.entng.forum.services.impl.MongoDbMessageService.java

License:Open Source License

@Override
public void checkIsSharedOrMine(final String categoryId, final String subjectId, final String messageId,
        final UserInfos user, final String sharedMethod, final Handler<Boolean> handler) {
    // Prepare Category Query
    final QueryBuilder methodSharedQuery = QueryBuilder.start();
    prepareIsSharedMethodQuery(methodSharedQuery, user, categoryId, sharedMethod);

    // Check Category Sharing with method
    executeCountQuery(categories_collection, MongoQueryBuilder.build(methodSharedQuery), 1,
            new Handler<Boolean>() {
                @Override/*  w  w w.j a v  a  2  s .c o  m*/
                public void handle(Boolean event) {
                    if (event) {
                        handler.handle(true);
                    } else {
                        // Prepare Category Query
                        final QueryBuilder anySharedQuery = QueryBuilder.start();
                        prepareIsSharedAnyQuery(anySharedQuery, user, categoryId);

                        // Check Category Sharing with any method
                        executeCountQuery(categories_collection, MongoQueryBuilder.build(anySharedQuery), 1,
                                new Handler<Boolean>() {
                                    @Override
                                    public void handle(Boolean event) {
                                        if (event) {
                                            // Prepare Subject and Message query
                                            QueryBuilder query = QueryBuilder.start("_id").is(subjectId)
                                                    .put("category").is(categoryId);

                                            DBObject messageMatch = new BasicDBObject();
                                            messageMatch.put("_id", messageId);
                                            messageMatch.put("owner.userId", user.getUserId());
                                            query.put("messages").elemMatch(messageMatch);

                                            // Check Message is mine
                                            executeCountQuery(subjects_collection,
                                                    MongoQueryBuilder.build(query), 1, handler);
                                        } else {
                                            handler.handle(false);
                                        }
                                    }
                                });
                    }
                }
            });
}

From source file:org.alfresco.bm.event.mongo.MongoResultService.java

License:Open Source License

@Override
public List<EventRecord> getResults(String eventName, int skip, int limit) {
    DBObject queryObj = QueryBuilder.start().get();
    if (eventName != null) {
        queryObj.put(EventRecord.FIELD_EVENT_NAME, eventName);
    }//from w  w w . j av a 2  s .c  o  m
    DBObject sortObj = BasicDBObjectBuilder.start().add(EventRecord.FIELD_START_TIME, Integer.valueOf(1)).get();

    DBCursor cursor = collection.find(queryObj);
    cursor.sort(sortObj);
    cursor.skip(skip);
    cursor.limit(limit);

    // Get all the results and convert them
    int size = cursor.size();
    List<EventRecord> results = new ArrayList<EventRecord>(size);
    try {
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            EventRecord eventRecord = convertToEventRecord(obj);
            results.add(eventRecord);
        }
    } finally {
        cursor.close();
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug(
                "\n" + "Found results: \n" + "   Query:          " + queryObj + "\n" + "   Skip:           "
                        + skip + "\n" + "   Limit:          " + limit + "\n" + "   Results:        " + size);
    }
    return results;
}