List of usage examples for com.mongodb QueryBuilder get
public DBObject get()
From source file:org.opencb.opencga.storage.mongodb.variant.VariantSourceMongoDBAdaptor.java
License:Apache License
@Override public QueryResult getAllSourcesByStudyIds(List<String> studyIds, QueryOptions options) { MongoDBCollection coll = db.getCollection(collectionName); QueryBuilder qb = QueryBuilder.start(); // getStudyIdFilter(studyIds, qb); options.put("studyId", studyIds); parseQueryOptions(options, qb);//from www . j av a 2 s . c om return coll.find(qb.get(), null, variantSourceConverter, options); }
From source file:org.openmhealth.reference.data.mongodb.MongoAuthenticationTokenBin.java
License:Apache License
@Override public AuthenticationToken getToken(final String token) throws OmhException { // Get the connection to the authentication token bin with the Jackson // wrapper.//from w w w .jav a2s . c om JacksonDBCollection<MongoAuthenticationToken, Object> collection = JacksonDBCollection .wrap(MongoDao.getInstance().getDb().getCollection(DB_NAME), MongoAuthenticationToken.class); // Build the query. QueryBuilder queryBuilder = QueryBuilder.start(); // Add the authentication token to the query. queryBuilder.and(AuthenticationToken.JSON_KEY_TOKEN).is(token); // Add the expiration timer to ensure that this token has not expired. queryBuilder.and(MongoAuthenticationToken.JSON_KEY_EXPIRES).greaterThan(System.currentTimeMillis()); // Execute query. DBCursor<MongoAuthenticationToken> result = collection.find(queryBuilder.get()); // If multiple authentication tokens were returned, that is a violation // of the system. if (result.count() > 1) { throw new OmhException("Multiple copies of the same authentication token " + "exist: " + token); } // If no tokens were returned, then return null. if (result.count() == 0) { return null; } else { return result.next(); } }
From source file:org.openmhealth.reference.data.mongodb.MongoDataSet.java
License:Apache License
@Override public MultiValueResult<Data> getData(final String owner, final String schemaId, final long version, final ColumnList columnList, final long numToSkip, final long numToReturn) { // Get the connection to the database. DB db = MongoDao.getInstance().getDb(); // Get the connection to the data with the Jackson wrapper. JacksonDBCollection<MongoData, Object> collection = JacksonDBCollection.wrap(db.getCollection(DB_NAME), MongoData.class); // Build the query. QueryBuilder queryBuilder = QueryBuilder.start(); // Only select data for a single user. queryBuilder.and(Data.JSON_KEY_OWNER).is(owner); // Only select data for a given schema. queryBuilder.and(Schema.JSON_KEY_ID).is(schemaId); // Only select data for a given version of the the given schema. queryBuilder.and(Schema.JSON_KEY_VERSION).is(version); // Create the projection. DBObject projection = new BasicDBObject(); // Add the owner field. projection.put(Data.JSON_KEY_OWNER, 1); // Add the schema ID field. projection.put(Schema.JSON_KEY_ID, 1); // Add the schema version. projection.put(Schema.JSON_KEY_VERSION, 1); // Add the meta-data field. projection.put(Data.JSON_KEY_METADATA, 1); // Add all of the data or add only the specified columns if given. if (columnList.size() == 0) { projection.put(Data.JSON_KEY_DATA, 1); } else {//from w w w . j ava2s. c om if ((columnList != null) && (columnList.size() > 0)) { for (String column : columnList.toList()) { projection.put(Data.JSON_KEY_DATA + ColumnList.COLUMN_SEPARATOR + column, 1); } } } // Build the query. DBCursor<MongoData> dbResult = collection.find(queryBuilder.get(), projection); // Build the sort field by sorting in reverse chronological order. DBObject sort = new BasicDBObject(); sort.put(Data.JSON_KEY_METADATA + ColumnList.COLUMN_SEPARATOR + MetaData.JSON_KEY_TIMESTAMP, -1); dbResult.sort(sort); // Page the results and return the multi-value result. return new MongoMultiValueResultCursor<Data>( dbResult.skip((new Long(numToSkip)).intValue()).limit((new Long(numToReturn)).intValue())); }
From source file:org.openmhealth.reference.data.mongodb.MongoRegistry.java
License:Apache License
public Schema getSchema(final String schemaId, final long schemaVersion) { // Get the connection to the database. DB db = MongoDao.getInstance().getDb(); // Get the connection to the registry with the Jackson wrapper. JacksonDBCollection<MongoSchema, Object> collection = JacksonDBCollection.wrap(db.getCollection(DB_NAME), MongoSchema.class, Object.class, JSON_MAPPER); // Build the query QueryBuilder queryBuilder = QueryBuilder.start(); // Add the schema ID. queryBuilder.and(MongoSchema.JSON_KEY_ID).is(schemaId); // Add the schema version. queryBuilder.and(MongoSchema.JSON_KEY_VERSION).is(schemaVersion); // Execute query. DBCursor<MongoSchema> result = collection.find(queryBuilder.get()); // Return null or the schema based on what the query returned. if (result.count() == 0) { return null; } else {//from w w w.j a va 2 s . c o m return result.next(); } }
From source file:org.openmhealth.reference.data.mongodb.MongoUserBin.java
License:Apache License
@Override public User getUser(final String username) throws OmhException { // Validate the parameter. if (username == null) { throw new OmhException("The username is null."); }/* w ww . j a va 2s .com*/ // Get the authentication token collection. JacksonDBCollection<MongoUser, Object> collection = JacksonDBCollection.wrap( MongoDao.getInstance().getDb().getCollection(DB_NAME), MongoUser.class, Object.class, JSON_MAPPER); // Build the query. QueryBuilder queryBuilder = QueryBuilder.start(); // Add the authentication token to the query queryBuilder.and(MongoUser.JSON_KEY_USERNAME).is(username); // Execute query. DBCursor<MongoUser> result = collection.find(queryBuilder.get()); // If multiple authentication tokens were returned, that is a violation // of the system. if (result.count() > 1) { throw new OmhException("Multiple users exist with the same username: " + username); } // If no tokens were returned, then return null. if (result.count() == 0) { return null; } else { return result.next(); } }
From source file:org.openmhealth.reference.data.mongodb.MongoUserBin.java
License:Apache License
@Override public User getUserFromRegistrationId(final String registrationId) throws OmhException { // Validate the parameter. if (registrationId == null) { throw new OmhException("The registration ID is null."); }//from w w w. ja v a2s . c o m // Get the authentication token collection. JacksonDBCollection<MongoUser, Object> collection = JacksonDBCollection.wrap( MongoDao.getInstance().getDb().getCollection(DB_NAME), MongoUser.class, Object.class, JSON_MAPPER); // Build the query. QueryBuilder queryBuilder = QueryBuilder.start(); // Add the authentication token to the query queryBuilder.and(MongoUser.JSON_KEY_REGISTRATION_KEY).is(registrationId); // Execute query. DBCursor<MongoUser> result = collection.find(queryBuilder.get()); // If multiple authentication tokens were returned, that is a violation // of the system. if (result.count() > 1) { throw new OmhException("Multiple users exist with the same registration ID: " + registrationId); } // If no tokens were returned, then return null. if (result.count() == 0) { return null; } else { return result.next(); } }
From source file:org.ossmeter.platform.AbstractHistoricalMetricProvider.java
License:Open Source License
public List<Pongo> getHistoricalMeasurements(MetricProviderContext context, Project project, Date start, Date end) {/*from w w w . j a va 2 s . c o m*/ DB db = context.getProjectDB(project); DBCollection collection = db.getCollection(this.getCollectionName()); QueryBuilder builder = QueryBuilder.start(); if (start != null) { builder.and("__datetime").greaterThanEquals(start.toJavaDate()); } if (end != null) { builder.and("__datetime").lessThanEquals(end.toJavaDate()); } BasicDBObject query = (BasicDBObject) builder.get(); Iterator<DBObject> it = collection.find(query).iterator(); List<Pongo> pongoList = new ArrayList<Pongo>(); while (it.hasNext()) { DBObject dbObject = it.next(); pongoList.add(PongoFactory.getInstance().createPongo(dbObject)); } return pongoList; }
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 }/* w ww . j a va2s . c o m*/ 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 ww.j a v a 2 s . co 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 w w. j a va 2s . c o m 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); } }