@ChangeSet(order = "03", author = "initiator", id = "03-addSocialUserConnection") public void addSocialUserConnection(DB db) { DBCollection socialUserConnectionCollection = db.getCollection("jhi_social_user_connection"); socialUserConnectionCollection.createIndex(BasicDBObjectBuilder .start("user_id", 1) .add("provider_id", 1) .add("provider_user_id", 1) .get(), "user-prov-provusr-idx", true); }
private DBObject createBetweenFilter(Object value) { JSONObject dateRange = parseDateRange(value); org.joda.time.format.DateTimeFormatter parser = ISODateTimeFormat.dateTime(); BasicDBObjectBuilder start = BasicDBObjectBuilder.start(); if (dateRange.get("startDate") != null) { DateTime startDate = parser.parseDateTime((String) dateRange.get("startDate")); start.add(QueryOperators.GTE, startDate.toDate()); } if (dateRange.get("endDate") != null) { DateTime endDate = parser.parseDateTime((String) dateRange.get("endDate")); start.add(QueryOperators.LTE, endDate.toDate()); } return start.get(); }
/** * Serializes {@link RyaDetails} to mongo {@link DBObject}. * @param details - The details to be serialized. * @return The mongo {@link DBObject}. */ public static BasicDBObject toDBObject(final RyaDetails details) { Preconditions.checkNotNull(details); final BasicDBObjectBuilder builder = BasicDBObjectBuilder.start() .add(INSTANCE_KEY, details.getRyaInstanceName()) .add(VERSION_KEY, details.getRyaVersion()) .add(ENTITY_DETAILS_KEY, details.getEntityCentricIndexDetails().isEnabled()) //RYA-215 .add(GEO_DETAILS_KEY, details.getGeoIndexDetails().isEnabled()) .add(PCJ_DETAILS_KEY, toDBObject(details.getPCJIndexDetails())) .add(TEMPORAL_DETAILS_KEY, details.getTemporalIndexDetails().isEnabled()) .add(FREETEXT_DETAILS_KEY, details.getFreeTextIndexDetails().isEnabled()); if(details.getProspectorDetails().getLastUpdated().isPresent()) { builder.add(PROSPECTOR_DETAILS_KEY, details.getProspectorDetails().getLastUpdated().get()); } if(details.getJoinSelectivityDetails().getLastUpdated().isPresent()) { builder.add(JOIN_SELECTIVITY_DETAILS_KEY, details.getJoinSelectivityDetails().getLastUpdated().get()); } return (BasicDBObject) builder.get(); }
private static DBObject toDBObject(final PCJIndexDetails pcjIndexDetails) { requireNonNull(pcjIndexDetails); final BasicDBObjectBuilder builder = BasicDBObjectBuilder.start(); // Is Enabled builder.add(PCJ_ENABLED_KEY, pcjIndexDetails.isEnabled()); // Add the PCJDetail objects. final List<DBObject> pcjDetailsList = new ArrayList<>(); for(final PCJDetails pcjDetails : pcjIndexDetails.getPCJDetails().values()) { pcjDetailsList.add( toDBObject( pcjDetails ) ); } builder.add(PCJ_PCJS_KEY, pcjDetailsList.toArray()); return builder.get(); }
static DBObject toDBObject(final PCJDetails pcjDetails) { requireNonNull(pcjDetails); final BasicDBObjectBuilder builder = BasicDBObjectBuilder.start(); // PCJ ID builder.add(PCJ_ID_KEY, pcjDetails.getId()); // PCJ Update Strategy if present. if(pcjDetails.getUpdateStrategy().isPresent()) { builder.add(PCJ_UPDATE_STRAT_KEY, pcjDetails.getUpdateStrategy().get().name()); } // Last Update Time if present. if(pcjDetails.getLastUpdateTime().isPresent()) { builder.add(PCJ_LAST_UPDATE_KEY, pcjDetails.getLastUpdateTime().get()); } return builder.get(); }
/** * Serializes a {@link DocumentVisibility} to a MongoDB {@link DBObject}. * @param documentVisibility the {@link DocumentVisibility} to be * serialized. * @return The MongoDB {@link DBObject}. */ public static BasicDBObject toDBObject(final DocumentVisibility documentVisibility) { DocumentVisibility dv; if (documentVisibility == null) { dv = MongoDbRdfConstants.EMPTY_DV; } else { dv = documentVisibility; } Object[] dvArray = null; try { dvArray = DocumentVisibilityUtil.toMultidimensionalArray(dv); } catch (final DocumentVisibilityConversionException e) { log.error("Unable to convert document visibility"); } final BasicDBObjectBuilder builder = BasicDBObjectBuilder.start(); builder.add(DOCUMENT_VISIBILITY_KEY, dvArray); return (BasicDBObject) builder.get(); }
@Override public DBObject serialize(final RyaStatement ryaStatement) { final BasicDBObjectBuilder builder = BasicDBObjectBuilder.start("_id", ryaStatement.getSubject().hashCode()); final URI obj = ryaStatement.getObject().getDataType(); if(obj.equals(GeoConstants.GEO_AS_WKT) || obj.equals(GeoConstants.GEO_AS_GML) || obj.equals(GeoConstants.XMLSCHEMA_OGC_GML) || obj.equals(GeoConstants.XMLSCHEMA_OGC_WKT)) { try { final Statement statement = RyaToRdfConversions.convertStatement(ryaStatement); final Geometry geo = GeoParseUtils.getGeometry(statement, new GmlParser()); if (geo.getNumPoints() > 1) { builder.add(GEO_KEY, geoStrategy.getCorrespondingPoints(geo)); } else { builder.add(GEO_KEY, geoStrategy.getDBPoint(geo)); } } catch (final ParseException e) { LOG.error("Could not create geometry for statement " + ryaStatement, e); return null; } } else { builder.add(TIME_KEY, temporalStrategy.getTimeValue(ryaStatement.getObject().getData())); } return builder.get(); }
@Test public void deserializeTest() { final DBObject dbo = BasicDBObjectBuilder.start() .add(RYANAME_KEY, TEST_INSTANCE) .add(TIMESTAMP_KEY, TEST_TIMESTAMP) .add(FILTER_TIMESTAMP_KEY, TEST_FILTER_TIMESTAMP) .add(PARENT_TIME_OFFSET_KEY, TEST_TIME_OFFSET) .get(); final MergeParentMetadata expected = new MergeParentMetadata.Builder() .setRyaInstanceName(TEST_INSTANCE) .setTimestamp(TEST_TIMESTAMP) .setFilterTimestmap(TEST_FILTER_TIMESTAMP) .setParentTimeOffset(TEST_TIME_OFFSET) .build(); final MergeParentMetadata actual = adapter.deserialize(dbo); assertEquals(expected, actual); }
@Test public void serializeTest() { final MergeParentMetadata merge = new MergeParentMetadata.Builder() .setRyaInstanceName(TEST_INSTANCE) .setTimestamp(TEST_TIMESTAMP) .setFilterTimestmap(TEST_FILTER_TIMESTAMP) .setParentTimeOffset(TEST_TIME_OFFSET) .build(); final DBObject expected = BasicDBObjectBuilder.start() .add(RYANAME_KEY, TEST_INSTANCE) .add(TIMESTAMP_KEY, TEST_TIMESTAMP) .add(FILTER_TIMESTAMP_KEY, TEST_FILTER_TIMESTAMP) .add(PARENT_TIME_OFFSET_KEY, TEST_TIME_OFFSET) .get(); final DBObject actual = adapter.serialize(merge); assertEquals(expected, actual); }
/** {@inheritDoc} */ @Override public void initialize() { // Make sure the fields we want to query are indexed DBCollection assets = db.getCollection(ASSETS_COLLECTION); DBCollection attachments = db.getCollection(ATTACHMENTS_COLLECTION); // Add text index BasicDBObjectBuilder textIndex = BasicDBObjectBuilder.start(); for (String indexField : searchIndexFields) { textIndex.add(indexField, "text"); } assets.ensureIndex(textIndex.get()); // Add Attachment(assetId) index attachments.ensureIndex(new BasicDBObject("assetId", 1)); }
public ObjectListPresentation mapReduce(String map, String reduce, Bindings options) { BasicDBObjectBuilder command = new BasicDBObjectBuilder(); command.add("mapReduce", name); command.add("map", map); command.add("reduce", reduce); putObject("query", options, command); putObject("out", options, command); putObject("scope", options, command); putSimpleField("field", options, command); putSimpleField("jsMode", options, command); putSimpleField("finilize", options, command); putSimpleField("verbose", options, command); return singletonIter(mongoDatabase.getMongoDb().runCommand((Bson)command.get())); }
public java.util.List<String> getUserNames() throws Exception { List<String> result = new LinkedList<String>(); DBCollection users = getDB().getCollection( configuration.getUserCollectionName()); DBObject userProjection = new BasicDBObjectBuilder().add("_id", 0) .add("username", 1).get(); DBCursor uc = users.find(null, userProjection); while (uc.hasNext()) { DBObject group = uc.next(); result.add((String) group.get("username")); } uc.close(); return result; }
/** * Creates a GridFS instance for the specified bucket * in the given database. Set the preferred WriteConcern on the give DB with DB.setWriteConcern * * @see com.mongodb.WriteConcern * @param db database to work with * @param bucket bucket to use in the given database * @throws MongoException */ public GridFS(DB db, String bucket) { _db = db; _bucketName = bucket; _filesCollection = _db.getCollection( _bucketName + ".files" ); _chunkCollection = _db.getCollection( _bucketName + ".chunks" ); // ensure standard indexes as long as collections are small try { if (_filesCollection.count() < 1000) { _filesCollection.ensureIndex( BasicDBObjectBuilder.start().add( "filename" , 1 ).add( "uploadDate" , 1 ).get() ); } if (_chunkCollection.count() < 1000) { _chunkCollection.ensureIndex( BasicDBObjectBuilder.start().add( "files_id" , 1 ).add( "n" , 1 ).get() , BasicDBObjectBuilder.start().add( "unique" , true ).get() ); } } catch (MongoException e) { LOGGER.info(String.format("Unable to ensure indices on GridFS collections in database %s", db.getName())); } _filesCollection.setObjectClass( GridFSDBFile.class ); }
public DBObject validateLogin(String username, String password) { DBObject user = null; // XXX look in the user collection for a user that has this username // assign the result to the user variable. user = usersCollection.findOne(new BasicDBObjectBuilder().add("_id", username).get()); if (user == null) { System.out.println("User not in database"); return null; } String hashedAndSalted = user.get("password").toString(); String salt = hashedAndSalted.split(",")[1]; if (!hashedAndSalted.equals(makePasswordHash(password, salt))) { System.out.println("Submitted password is not a match"); return null; } return user; }
@Override public void reduce(final IntWritable key, final Iterable<DoubleWritable> values, final Context context) throws IOException, InterruptedException { DescriptiveStatistics stats = new DescriptiveStatistics(); for(DoubleWritable rating : values) { stats.addValue(rating.get()); } DBObject builder = new BasicDBObjectBuilder().start() .add("movieid", key.get()) .add("mean", stats.getMean()) .add("median", stats.getPercentile(50)) .add("std", stats.getStandardDeviation()) .add("count", stats.getN()) .add("total", stats.getSum()) .get(); BSONWritable doc = new BSONWritable(builder); context.write(NullWritable.get(), doc); }
@Override public void reduce(final IntWritable key, final Iterable<DoubleWritable> values, final Context context) throws IOException, InterruptedException { DescriptiveStatistics stats = new DescriptiveStatistics(); for(DoubleWritable rating : values) { stats.addValue(rating.get()); } BasicBSONObject query = new BasicBSONObject("movieid", key.get()); DBObject statValues = new BasicDBObjectBuilder().start() .add("mean", stats.getMean()) .add("median", stats.getPercentile(50)) .add("std", stats.getStandardDeviation()) .add("count", stats.getN()) .add("total", stats.getSum()) .get(); BasicBSONObject movieStats = new BasicBSONObject("stats", statValues); BasicBSONObject update = new BasicBSONObject("$set", movieStats); context.write(NullWritable.get(), new MongoUpdateWritable(query, update)); }
@Test public void should_get_cause_from_dbObject() throws Exception { BasicDBObject cause1DbObject = new BasicDBObject("cause1", "cause1"); DBObject causes = new BasicDBObjectBuilder().add("causes", Arrays.asList(cause1DbObject)).get(); Mapper mapper = Mockito.mock(Mapper.class); Cause cause1 = new NullBuildCause(); when(mapper.fromDBObject(null, cause1DbObject, null)).thenReturn(cause1); CauseActionConverter converter = new CauseActionConverter(); converter.setMapper(mapper); CauseAction action = converter.decode(CauseAction.class, causes, Mockito.mock(MappedField.class)); Assert.assertEquals(1, action.getCauses().size()); Assert.assertEquals(cause1, action.getCauses().get(0)); }
@Override public void start() throws Exception { // Initialize indexes DBObject idx_NEXT_AVAILABLE_EVENT_V2 = BasicDBObjectBuilder .start(Event.FIELD_SCHEDULED_TIME, Integer.valueOf(-1)) .add(Event.FIELD_LOCK_OWNER, Integer.valueOf(1)) .add(Event.FIELD_DATA_OWNER, Integer.valueOf(1)) .add(Event.FIELD_DRIVER, Integer.valueOf(1)) .get(); DBObject opt_NEXT_AVAILABLE_EVENT_V2 = BasicDBObjectBuilder .start("name", "IDX_NEXT_AVAILABLE_EVENT_V2") .add("unique", Boolean.FALSE) .get(); collection.createIndex(idx_NEXT_AVAILABLE_EVENT_V2, opt_NEXT_AVAILABLE_EVENT_V2); DBObject idx_NAME = BasicDBObjectBuilder .start(Event.FIELD_NAME, Integer.valueOf(1)) .get(); DBObject opt_NAME = BasicDBObjectBuilder .start("name", "IDX_NAME") .add("unique", Boolean.FALSE) .get(); collection.createIndex(idx_NAME, opt_NAME); }
private Measurements getMongo(MeasurementFilter request) { BasicDBObjectBuilder q = new BasicDBObjectBuilder(); if (request.hasSpatialFilter()) { SpatialFilter sf = request.getSpatialFilter(); try { q.add(MongoMeasurement.GEOMETRY, MongoUtils.spatialFilter(sf, geometryConverter)); } catch (GeometryConverterException e) { log.error("Error while applying spatial filter: " + e .getLocalizedMessage()); } } if (request.hasTrack()) { q.add(MongoMeasurement.TRACK, ref(request.getTrack())); } if (request.hasUser()) { q.add(MongoMeasurement.USER, ref(request.getUser())); } if (request.hasTemporalFilter()) { q.add(MongoMeasurement.TIME, MongoUtils.temporalFilter(request.getTemporalFilter())); } return query(q.get(), request.getPagination()); }
/** * Converts {@link SiteMemberData} to {@link DBObject}. */ public static DBObject convertSiteMember(SiteMemberData siteMember) { if (siteMember == null) { throw new IllegalArgumentException("'siteMember' may not be null."); } return BasicDBObjectBuilder.start() .append(SiteMemberData.FIELD_USERNAME, siteMember.getUsername()) .append(SiteMemberData.FIELD_SITE_ID, siteMember.getSiteId()) .append(SiteMemberData.FIELD_ROLE, siteMember.getRole()) .append(SiteMemberData.FIELD_CREATION_STATE, siteMember.getCreationState().toString()) .append(SiteMemberData.FIELD_RANDOMIZER, siteMember.getRandomizer()) .get(); }
@Override public UserData getRandomUserFromDomains(List<String> domains) { Range range = getRandomizerRange(domains); int upper = range.getMax(); int lower = range.getMin(); int random = lower + (int) (Math.random() * (double) (upper - lower)); BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start() .add(FIELD_CREATION_STATE, DataCreationState.Created.toString()) .push(FIELD_RANDOMIZER) .add("$gte", random) .pop(); if (domains.size() > 0) { queryObjBuilder .push(FIELD_DOMAIN) .add("$in", domains) .pop(); } DBObject queryObj = queryObjBuilder.get(); DBObject userDataObj = collection.findOne(queryObj); return fromDBObject(userDataObj); }
/** * Derigister a driver from a test run * * @param runObjId * the ID of the test run * @param driverId * the ID of the driver to remove */ public void removeTestRunDriver(ObjectId runObjId, String driverId) { // Find the test run DBObject queryObj = QueryBuilder .start() .and(FIELD_ID).is(runObjId) .get(); DBObject updateObj = BasicDBObjectBuilder.start() .push("$pull") .add(FIELD_DRIVERS, driverId) .pop() .get(); DBObject runObj = testRuns.findAndModify(queryObj, null, null, false, updateObj, true, false); // Done if (logger.isDebugEnabled()) { logger.debug( "Removed driver ID from run drivers: \n" + " Run ID: " + runObjId + "\n" + " Driver: " + driverId + "\n" + " Drivers: " + runObj.get(FIELD_DRIVERS)); } }
@Override public boolean update(JID jid, String affiliation) { try { // {"affiliations.$.affiliation":Xxx} BasicDBObjectBuilder entity = BasicDBObjectBuilder.start().add(Dictionary.FIELD_AFFILIATIONS + ".$." + Dictionary.FIELD_AFFILIATION, affiliation); if (ItemAffiliation.OWNER.equals(affiliation)) { // {"creator":jid.bare} // 如果为Owner则同时更新创建者 entity.add(Dictionary.FIELD_CREATOR, jid.asStringWithBare()); } // {"jid":group.bare,"affiliations.jid":jid.bare"},{"$set":...entity...} return MongoUtils.success(MongoAffiliationBuilder.this.config.collection().update(BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, this.group.asStringWithBare()).add(Dictionary.FIELD_AFFILIATIONS + "." + Dictionary.FIELD_JID, jid.asStringWithBare()).get(), BasicDBObjectBuilder.start().add("$set", entity.get()).get(), true, false, WriteConcern.SAFE)); } catch (MongoException e) { // {"jid":group.bare},{"$addToSet":{"affiliations":{"jid":Xxx,"affiliation":Xxx}}} return MongoUtils.success(MongoAffiliationBuilder.this.config.collection().update(BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, this.group.asStringWithBare()).get(), BasicDBObjectBuilder.start("$addToSet", BasicDBObjectBuilder.start(Dictionary.FIELD_AFFILIATIONS, BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, jid.asStringWithBare()).add(Dictionary.FIELD_AFFILIATION, affiliation).get()).get()).get(), true, false, WriteConcern.SAFE)); } }
@Override public FileData findFile(String fileset, String remoteName) { DBObject queryObj = BasicDBObjectBuilder.start() .add(FIELD_FILESET, fileset) .add(FIELD_REMOTE_NAME, remoteName) .get(); DBObject resultObj = collection.findOne(queryObj); if (resultObj == null) { if (logger.isDebugEnabled()) { logger.debug("Did not find file '" + remoteName + "' in " + fileset); } return null; } else { if (logger.isDebugEnabled()) { logger.debug("Found file '" + remoteName + "' in " + fileset + ": " + resultObj); } return fromDBObject(resultObj); } }
/** * {@inheritDoc} */ @Override public void setUserPassword(String username, String password) { DBObject queryObj = BasicDBObjectBuilder.start() .add(FIELD_USERNAME, username) .get(); DBObject updateObj = BasicDBObjectBuilder.start() .push("$set") .add(FIELD_PASSWORD, password) .pop() .get(); WriteResult result = collection.update(queryObj, updateObj); if (result.getN() != 1) { throw new RuntimeException( "Failed to update user ticket: \n" + " Username: " + username + "\n" + " Password: " + password + "\n" + " Result: " + result); } }
/** * Ensure that the necessary indexes are in place for the Mongo collections */ protected void initCollections(DB db) { aspects = db.getCollection(COLLECTION_ASPECTS); // @since 2.0 DBObject ASPECTS_NODE_QNAME = BasicDBObjectBuilder .start(FIELD_NODE_ID, 1) .add(FIELD_QNAME, 1) .get(); aspects.ensureIndex(ASPECTS_NODE_QNAME, "ASPECTS_NODE_QNAME", true); // @since 2.0 DBObject ASPECTS_NODE_TXN_QNAME = BasicDBObjectBuilder .start(FIELD_NODE_ID, 1) .add(FIELD_TXN_ID, 1) .add(FIELD_QNAME, 1) .get(); aspects.ensureIndex(ASPECTS_NODE_TXN_QNAME, "ASPECTS_NODE_TXN_QNAME", false); properties = db.getCollection(COLLECTION_PROPERTIES); }
@Override public void setSiteMemberCreationState(String siteId, String userId, DataCreationState state) { DBObject findObj = new BasicDBObject() .append(SiteMemberData.FIELD_USERNAME, userId) .append(SiteMemberData.FIELD_SITE_ID, siteId); DBObject updateObj = BasicDBObjectBuilder .start() .push("$set") .add(SiteMemberData.FIELD_CREATION_STATE, state.toString()) .pop() .get(); siteMembersCollection.findAndModify(findObj, null, null, false, updateObj, false, false); }
/** * Fetch masked property names (passwords) by test name. * * @param testName * (String, mandatory) test name * * @return (Set<String>) or exception * * @throws ObjectNotFoundException * @since 2.1.2 */ public Set<String> getMaskedProperyNames(String testName) throws ObjectNotFoundException { ArgumentCheck.checkMandatoryString(testName, "testName"); DBObject queryObj = QueryBuilder .start() .and(FIELD_NAME).is(testName) .get(); BasicDBObjectBuilder fieldsObjBuilder = BasicDBObjectBuilder .start(FIELD_RELEASE, true) .add(FIELD_SCHEMA, true); DBObject testObj = tests.findOne(queryObj, fieldsObjBuilder.get()); ObjectNotFoundException.checkObject(testObj, testName); return getMaskedProperyNames((String) testObj.get(FIELD_RELEASE), (Integer) testObj.get(FIELD_SCHEMA)); }
@Test public void testDeleteEntityAndContainerDoc() { ContainerDocumentAccessor cda = Mockito.spy(testAccessor); Map<String, Object> updateDocCriteria = new HashMap<String, Object>(); updateDocCriteria.put("event", "Tardy"); DBObject pullObject = BasicDBObjectBuilder.start().push("$pull").add("body.attendanceEvent", updateDocCriteria).get(); DBObject resultingAttendanceEvent = createResultAttendance(null); NeutralSchema attendanceSchema = createMockAttendanceSchema(); when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection); when(mockCollection.findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(), Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false))).thenReturn(resultingAttendanceEvent); when(mongoTemplate.findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE))).thenReturn(entity); // just return something non-null when(schemaRepo.getSchema(EntityNames.ATTENDANCE)).thenReturn(attendanceSchema); boolean result = cda.deleteContainerNonSubDocs(entity); Mockito.verify(mockCollection, Mockito.times(1)).findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(), Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false)); Mockito.verify(mongoTemplate, Mockito.times(1)).findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE)); assertTrue(result); }
@Override public Delegation push(Exchanger exchanger) { // {"host":Xxx} Map<String, Object> peek = this.persistent.peek(MongoUtils.asMap(BasicDBObjectBuilder.start(Dictionary.FIELD_HOST, exchanger.host()).get())); ByteTransferBuffer buffer = null; try { buffer = new ByteTransferBuffer(new BufferedInputStream(new FileInputStream(new File(FSDelegation.this.dir, peek.get(Dictionary.FIELD_SID).toString()))), Long.valueOf(peek.get(Dictionary.FIELD_SIZE).toString())).write(exchanger); return this; } catch (Exception e) { this.log.warn(e.toString()); Trace.trace(this.log, e); throw new RuntimeException(e); } finally { IOUtil.closeQuietly(buffer); } }
@SuppressWarnings("unchecked") @Test public void testCreateCalculatedValue() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Map<String, Object> body = new HashMap<String, Object>(); Map<String, Object> calcValue = new HashMap<String, Object>(); Map<String, Object> assessments = new HashMap<String, Object>(); Map<String, Object> mathTest = new HashMap<String, Object>(); Map<String, Object> highestEver = new HashMap<String, Object>(); highestEver.put("ScaleScore", "28.0"); mathTest.put("HighestEver", highestEver); assessments.put("ACT", mathTest); calcValue.put("assessments", assessments); DBObject dbObject = new BasicDBObjectBuilder().add("_id", "42").add("body", body) .add("calculatedValues", calcValue).get(); CalculatedData<String> data = MongoEntity.fromDBObject(dbObject).getCalculatedValues(); assertEquals( Arrays.asList(new CalculatedDatum<String>("assessments", "HighestEver", "ACT", "ScaleScore", "28.0")), data.getCalculatedValues()); }
/** * Create a new process * * @return <tt>true</tt> if the insert was successful */ public boolean createProcess(String processName) { DBObject insertObj = BasicDBObjectBuilder .start() .add(ProcessData.FIELD_NAME, processName) .add(ProcessData.FIELD_STATE, DataCreationState.NotScheduled.toString()) .get(); try { collection.insert(insertObj); return true; } catch (MongoException e) { // Log and rethrow return false; } }
/** * Find a process by unique name * * @param processName the name of the process to find * @return Returns the data or <tt>null</tt> if not found */ public ProcessData findProcessByName(String processName) { DBObject queryObj = BasicDBObjectBuilder .start() .add(ProcessData.FIELD_NAME, processName) .get(); DBObject resultObj = collection.findOne(queryObj); if (resultObj == null) { return null; } else { ProcessData result = new ProcessData(); String stateStr = (String) resultObj.get(ProcessData.FIELD_STATE); DataCreationState state = DataCreationState.valueOf(stateStr); result.setState(state); result.setName( (String) resultObj.get(ProcessData.FIELD_NAME)); return result; } }
@Override protected void updateSessionEndTime(String sessionId, long endTime) { DBObject queryObj = BasicDBObjectBuilder.start() .add(FIELD_ID, new ObjectId(sessionId)) .get(); DBObject updateObj = BasicDBObjectBuilder.start() .push("$set") .add(FIELD_END_TIME, endTime) .pop() .get(); try { collection.update(queryObj, updateObj); } catch (MongoException e) { throw new RuntimeException( "Failed to update session end time: \n" + " Session: " + sessionId + "\n" + " End Time: " + endTime, e); } }
@Override protected boolean updateSessionData(String sessionId, DBObject data) { DBObject queryObj = BasicDBObjectBuilder.start() .add(FIELD_ID, new ObjectId(sessionId)) .get(); DBObject updateObj = BasicDBObjectBuilder.start() .push("$set") .add(FIELD_DATA, data) .pop() .get(); try { WriteResult wr = collection.update(queryObj, updateObj); return wr.getN() > 0; } catch (MongoException e) { throw new RuntimeException( "Failed to update session data: \n" + " Session: " + sessionId + "\n" + " Data: " + data, e); } }
@Override public void createNewFileData(FileData fileData) { DBObject fileDataObj = BasicDBObjectBuilder.start() .add(FIELD_FILESET, fileData.getFileset()) .add(FIELD_REMOTE_NAME, fileData.getRemoteName()) .add(FIELD_LOCAL_NAME, fileData.getLocalName()) .add(FIELD_EXTENSION, fileData.getExtension()) .add(FIELD_ENCODING, fileData.getEncoding()) .add(FIELD_LOCALE, fileData.getLocale()) .add(FIELD_SIZE, fileData.getSize()) .add(FIELD_RANDOMIZER, fileData.getRandomizer()) .get(); WriteResult result = collection.insert(fileDataObj); if (logger.isDebugEnabled()) { logger.debug( "Wrote FileData to collection: \n" + " " + fileData + "\n" + " Result: " + result); } }
@Override public void setSiteCreationState(String siteId, String guid, DataCreationState state) { DBObject findObj = new BasicDBObject(SiteData.FIELD_SITE_ID, siteId); DBObject updateObj = BasicDBObjectBuilder .start() .push("$set") .add(SiteData.FIELD_CREATION_STATE, state.toString()) .add(SiteData.FIELD_GUID, guid) .pop() .get(); DBObject newObj = sitesCollection.findAndModify(findObj, null, null, false, updateObj, true, false); // Done if (logger.isDebugEnabled()) { logger.debug("Updated site: " + newObj); } }
@Override public long countUsers(String domain, DataCreationState creationState) { BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start(); if (domain != null) { queryObjBuilder.add(FIELD_DOMAIN, domain); } if (creationState != null) { queryObjBuilder.add(FIELD_CREATION_STATE, creationState.toString()); } DBObject queryObj = queryObjBuilder.get(); return collection.count(queryObj); }
/** * Refresh the expiry time of a driver * * @param id * the driver id * @param expiryTime * the new expiry time */ public void refreshDriver(String id, long expiryTime) { DBObject queryObj = QueryBuilder .start() .and(FIELD_ID).is(new ObjectId(id)) .get(); DBObject updateObj = BasicDBObjectBuilder .start() .push("$set") .add(FIELD_PING + "." + FIELD_EXPIRES, new Date(expiryTime)) .pop() .get(); testDrivers.findAndModify(queryObj, null, null, false, updateObj, false, false); // Done if (logger.isDebugEnabled()) { logger.debug( "Updated test driver expiry: \n" + " ID: " + id + "\n" + " New: " + expiryTime); } }