Example usage for com.mongodb QueryBuilder and

List of usage examples for com.mongodb QueryBuilder and

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public QueryBuilder and(final DBObject... ands) 

Source Link

Document

Equivalent to an $and operand

Usage

From source file:org.ossmeter.platform.client.api.MetricVisualisationResource.java

License:Open Source License

public Representation doRepresent() {
    String projectName = (String) getRequest().getAttributes().get("projectid");
    String metricId = (String) getRequest().getAttributes().get("metricid");

    String agg = getQueryValue("agg");
    String start = getQueryValue("startDate");
    String end = getQueryValue("endDate");

    QueryBuilder builder = QueryBuilder.start();
    if (agg != null && agg != "") {
        //         builder.... // TODO
    }/*from w  w w . ja v a 2  s  .  com*/
    try {
        if (start != null && start != "") {
            builder.and("__datetime").greaterThanEquals(new Date(start).toJavaDate());
        }
        if (end != null && end != "") {
            builder.and("__datetime").lessThanEquals(new Date(end).toJavaDate());
        }
    } catch (ParseException e) {
        return Util.generateErrorMessageRepresentation(generateRequestJson(projectName, metricId),
                "Invalid date. Format must be YYYYMMDD.");
    }

    BasicDBObject query = (BasicDBObject) builder.get();

    ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository();

    Project project = projectRepo.getProjects().findOneByShortName(projectName);
    if (project == null) {
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        return Util.generateErrorMessageRepresentation(generateRequestJson(projectName, metricId),
                "No project was found with the requested name.");
    }

    MetricVisualisationExtensionPointManager manager = MetricVisualisationExtensionPointManager.getInstance();
    manager.getRegisteredVisualisations();

    MetricVisualisation vis = manager.findVisualisationById(metricId);

    if (vis == null) {
        return Util.generateErrorMessageRepresentation(generateRequestJson(projectName, metricId),
                "No visualiser found with specified ID.");
    }

    DB db = platform.getMetricsRepository(project).getDb();
    JsonNode visualisation = vis.visualise(db, query);

    StringRepresentation resp = new StringRepresentation(visualisation.toString());
    resp.setMediaType(MediaType.APPLICATION_JSON);
    return resp;
}

From source file:org.ossmeter.platform.client.api.RawMetricResource.java

License:Open Source License

/**
 * TODO: Incomplete. [12th Sept, 2013]/*from w  w w  .  jav a  2 s .  c  o m*/
 * @return
 */
public Representation doRepresent() {
    String projectId = (String) getRequest().getAttributes().get("projectid");
    String metricId = (String) getRequest().getAttributes().get("metricid");

    // FIXME: This and MetricVisualisationResource.java are EXACTLY the same.
    String agg = getQueryValue("agg");
    String start = getQueryValue("startDate");
    String end = getQueryValue("endDate");

    QueryBuilder builder = QueryBuilder.start();
    if (agg != null && agg != "") {
        //         builder.... // TODO
    }
    try {
        if (start != null && start != "") {
            builder.and("__datetime").greaterThanEquals(new Date(start).toJavaDate());
        }
        if (end != null && end != "") {
            builder.and("__datetime").lessThanEquals(new Date(end).toJavaDate());
        }
    } catch (ParseException e) {
        return Util.generateErrorMessageRepresentation(generateRequestJson(projectId, metricId),
                "Invalid date. Format must be YYYYMMDD.");
    }

    BasicDBObject query = (BasicDBObject) builder.get();

    ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository();

    Project project = projectRepo.getProjects().findOneByShortName(projectId);
    if (project == null) {
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        return Util.generateErrorMessageRepresentation(generateRequestJson(projectId, metricId),
                "No project was found with the requested name.");
    }

    // Get collection from DB
    DB projectDB = platform.getMetricsRepository(project).getDb();

    MetricVisualisationExtensionPointManager manager = MetricVisualisationExtensionPointManager.getInstance();
    manager.getRegisteredVisualisations();
    MetricVisualisation vis = manager.findVisualisationById(metricId);

    if (vis == null) {
        return Util.generateErrorMessageRepresentation(generateRequestJson(projectId, metricId),
                "No visualiser found with specified ID.");
    }

    // TODO: okay, so we only allow people to get raw HISTORIC metrics? How would we
    //        return multiple collections???
    // TODO: Can we stream it? Page it? Filter and agg?

    DBCursor cursor = projectDB.getCollection(vis.getMetricId()).find(query);
    ArrayNode results = mapper.createArrayNode();

    while (cursor.hasNext()) {
        try {
            results.add(mapper.readTree(cursor.next().toString()));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    cursor.close();

    return Util.createJsonRepresentation(results);
}

From source file:org.ossmeter.platform.client.api.SparkResource.java

License:Open Source License

public Representation doRepresent() {
    // Check cache
    String sd = SparkCache.getSparkCache().getSparkData(getRequest().getResourceRef().toString());

    if (sd != null) {
        JsonNode obj;//from   w  ww  .j av a  2 s.  c  om
        try {
            System.out.println("SD: " + sd);
            obj = mapper.readTree(sd);
            return Util.createJsonRepresentation(obj);
        } catch (Exception e) {
            e.printStackTrace(); // FIXME
            getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
            ObjectNode node = mapper.createObjectNode();
            node.put("status", "error");
            node.put("msg", "Error whilst retrieving sparkline.");
            return Util.createJsonRepresentation(node);
        }
    }

    // Miss. Hit database.
    String projectId = (String) getRequest().getAttributes().get("projectid");
    String metric = (String) getRequest().getAttributes().get("metricid");

    String[] metrics = metric.split("\\+");
    System.err.println("metrics to get: " + metrics);
    ArrayNode sparks = mapper.createArrayNode();
    for (String metricId : metrics) {

        String agg = getQueryValue("agg");
        String start = getQueryValue("startDate");
        String end = getQueryValue("endDate");

        QueryBuilder builder = QueryBuilder.start();
        if (agg != null && agg != "") {
            //         builder.... // TODO
        }
        try {
            if (start != null && start != "") {
                builder.and("__datetime").greaterThanEquals(new Date(start).toJavaDate());
            }
            if (end != null && end != "") {
                builder.and("__datetime").lessThanEquals(new Date(end).toJavaDate());
            }
        } catch (ParseException e) {
            getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            ObjectNode node = mapper.createObjectNode();
            node.put("status", "error");
            node.put("msg", "Invalid date. Format must be YYYYMMDD.");
            node.put("request", generateRequestJson(projectId, metricId));
            return Util.createJsonRepresentation(node);
        }

        BasicDBObject query = (BasicDBObject) builder.get();

        ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository();
        Project project = projectRepo.getProjects().findOneByShortName(projectId);
        if (project == null) {
            getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            return Util.createJsonRepresentation(
                    generateErrorMessage(mapper, "No project matched that requested.", projectId, metricId));

        }

        MetricVisualisationExtensionPointManager manager = MetricVisualisationExtensionPointManager
                .getInstance();
        Map<String, MetricVisualisation> registeredVisualisations = manager.getRegisteredVisualisations();
        System.out.println("registered visualisations: " + registeredVisualisations.keySet());
        MetricVisualisation vis = manager.findVisualisationById(metricId);

        if (vis == null) {
            getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            return Util.createJsonRepresentation(generateErrorMessage(mapper,
                    "No visualiser found with specified ID.", projectId, metricId));
        }

        DB db = platform.getMetricsRepository(project).getDb();

        System.setProperty("java.awt.headless", "true");

        byte[] sparky;
        try {
            sparky = vis.getSparky(db, query);
            ObjectNode sparkData = vis.getSparkData();

            if (sparky != null) {
                String uuid = UUID.randomUUID().toString();
                SparkCache.getSparkCache().putSpark(uuid, sparky);
                sparkData.put("spark", "/spark/" + uuid);
            }
            sparkData.put("metricId", metricId);
            sparkData.put("projectId", projectId);

            // And add to the return list
            sparks.add(sparkData);
        } catch (ParseException e) {
            //            getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
            // TODO Log this as series - needs investigating by admin
            sparks.add(generateErrorMessage(mapper, "Error whilst generating sparkle. Unable to parse data.",
                    projectId, metricId));
        } catch (UnsparkableVisualisationException e) {
            //            getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
            sparks.add(generateErrorMessage(mapper,
                    "Visualisation not sparkable. Metrics must be time series in order to be sparkable.",
                    projectId, metricId));
        } catch (IOException e) {
            e.printStackTrace(); // FIXME
            //            getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
            sparks.add(generateErrorMessage(mapper, "Error whilst generating sparkle.", projectId, metricId));
        }
    }

    // Put in the cache

    if (sparks.size() == 1) {
        SparkCache.getSparkCache().putSparkData(getRequest().getResourceRef().toString(),
                (ObjectNode) sparks.get(0));
        return Util.createJsonRepresentation(sparks.get(0));
    } else {
        SparkCache.getSparkCache().putSparkData(getRequest().getResourceRef().toString(), sparks);
        return Util.createJsonRepresentation(sparks);
    }
}

From source file:org.sglover.entities.dao.mongo.MongoEntitiesDAO.java

License:Open Source License

@Override
public Entities getEntities(Node node) {
    String nodeId = node.getNodeId();
    String nodeVersion = node.getVersionLabel();

    Entities entities = Entities.empty(nodeId, nodeVersion);

    QueryBuilder queryBuilder = QueryBuilder.start("n").is(nodeId).and("v").is(nodeVersion);

    Set<String> types = new HashSet<>();
    types.add("names");
    types.add("orgs");
    queryBuilder.and("t").in(types);

    DBObject query = queryBuilder.get();

    DBCursor cursor = entitiesData.find(query);
    try {/*ww w  .  java2 s .c  om*/
        for (DBObject dbObject : cursor) {
            Entity<String> entity = getEntity(dbObject);
            entities.addEntity(entity);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return entities;
}

From source file:org.wrml.contrib.runtime.service.mongo.MongoService.java

License:Apache License

private DBObject createMongoQuery(final SearchCriteria searchCriteria) {

    QueryBuilder queryBuilder = null;

    final List<SearchCriterion> and = searchCriteria.getAnd();
    if (and != null && !and.isEmpty()) {

        queryBuilder = new QueryBuilder();

        for (final SearchCriterion searchCriterion : and) {

            final String referenceSlot = searchCriterion.getReferenceSlot();
            queryBuilder.and(referenceSlot);
            addQueryCriterion(searchCriterion, queryBuilder);

        }//from   w  w w.j  ava2 s.com

    }

    final List<SearchCriterion> or = searchCriteria.getOr();
    if (or != null && !or.isEmpty()) {

        final DBObject[] orQueryCriterionArray = new DBObject[or.size()];
        for (int i = 0; i < or.size(); i++) {
            final SearchCriterion searchCriterion = or.get(i);
            final String referenceSlot = searchCriterion.getReferenceSlot();
            final QueryBuilder orQueryCriterionBuilder = QueryBuilder.start(referenceSlot);
            addQueryCriterion(searchCriterion, orQueryCriterionBuilder);
            orQueryCriterionArray[i] = orQueryCriterionBuilder.get();
        }

        final QueryBuilder orQueryBuilder = new QueryBuilder();
        orQueryBuilder.or(orQueryCriterionArray);

        if (queryBuilder != null) {
            // AND the OR clause together with the AND query
            queryBuilder.and(orQueryBuilder.get());
        } else {
            queryBuilder = orQueryBuilder;
        }
    }

    if (queryBuilder == null) {
        return null;
    }

    final DBObject mongoQuery = queryBuilder.get();
    return mongoQuery;
}