Java Code Examples for org.mongodb.morphia.Datastore

The following are top voted examples for showing how to use org.mongodb.morphia.Datastore. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: morphia   File: TestEmbeddedValidation.java   View source code 7 votes vote down vote up
@Test
public void testDottedNames() {
    ParentType parentType = new ParentType();
    EmbeddedSubtype embedded = new EmbeddedSubtype();
    embedded.setText("text");
    embedded.setNumber(42L);
    embedded.setFlag(true);
    parentType.setEmbedded(embedded);

    Datastore ds = getDs();
    ds.save(parentType);

    Query<ParentType> query = ds.find(ParentType.class)
                                .disableValidation()
                                .field("embedded.flag").equal(true);

    Assert.assertEquals(parentType, query.get());
}
 
Example 2
Project: morphia-spring-boot-starter   File: MorphiaAutoConfiguration.java   View source code 6 votes vote down vote up
@Bean
public Datastore datastore(Morphia morphia) throws ClassNotFoundException, IOException {

    List<String> packageNamesFromApplication = MorphiaUtils.getApplicationPackageName(applicationContext);

    Set<Class<?>> classes = packageNamesFromApplication
            .parallelStream()
            .flatMap(packageName -> MorphiaUtils.getClasses(packageName).parallelStream())
            .collect(Collectors.toSet());

    classes.parallelStream()
            .filter(clazz -> Objects.nonNull(clazz.getAnnotation(Entity.class)))
            .forEach( clazz ->morphia.map(clazz));

    Datastore dataStore = morphia.createDatastore(mongoClient, mongoTemplate.getDb().getName());
    dataStore.ensureIndexes();
    return dataStore;
}
 
Example 3
Project: thatsapp   File: GlobalStatistics.java   View source code 6 votes vote down vote up
/**
 * Saves the whole object graph.
 * TODO: make a generic version for non circular graphs
 * @param ds
 */
public void saveObjectGraph(Datastore ds){
    long startTime = System.nanoTime();

    for (Person e : conversation.getParticipants()){
        ds.save(e.getStatistics());
        ds.save(e);
    }

    ds.save(conversation);
    ds.save(statistics);
    ds.save(this);
    long endTime = System.nanoTime();
    long duration = (endTime - startTime);  //divide by 1000000 to get milliseconds.
    logger.info("Time to save GlobalStatistics object: " + duration / 1000000 + "ms");
}
 
Example 4
Project: elastic-match   File: ConnectionFactory.java   View source code 6 votes vote down vote up
public static synchronized  Datastore getDatastore() {
    if (Objects.isNull(datastore)) {
        Morphia morphia = new Morphia();
        morphia.mapPackage("com.ftt.elastic.match.beans");
        MongoClient mongoClient = new MongoClient(PropertiesRepo.get(Constants.Settings.MONGODB_HOST), PropertiesRepo.getInt(Constants.Settings.MONGODB_PORT));
        datastore = morphia.createDatastore(mongoClient, PropertiesRepo.get(Constants.Settings.MONGODB_SCHEMANAME));
    }
    return datastore;
}
 
Example 5
Project: dropwizard-morphia   File: AbstractMongoConfiguration.java   View source code 6 votes vote down vote up
@JsonIgnore
@Override
public Datastore buildDatastore() {
    MongoClient client = buildClient();

    MapperOptions options = morphia.getMapper().getOptions();
    options.setStoreNulls(getStoreNulls());
    options.setStoreEmpties(getStoreEmpties());
    options.setIgnoreFinals(getIgnoreFinals());
    options.setUseLowerCaseCollectionNames(getUseLowerCaseCollectionNames());

    if (getEnableValidationExtension()) {
        new ValidationExtension(morphia);
    }

    return morphia.createDatastore(client, checkNotNull(getDbName()));
}
 
Example 6
Project: six-oval   File: MongoClientAuthTest.java   View source code 6 votes vote down vote up
@Test
    public void testAuth()
    		throws Exception
    {
	    //MongoDB 3.0//
        MongoCredential credential = MongoCredential.createScramSha1Credential( _DATABASE_, _USER_, _PASSWORD_.toCharArray() );
        MongoClient client = new MongoClient( new ServerAddress( _HOST_, _PORT_ ), Arrays.asList( credential ) );
        MongoDatabase db = client.getDatabase( _DATABASE_ );

        //MongoDB 2.6//
//      DB db = client.getDB( "opensec" );
//		db.authenticate( "opensec", "opensec".toCharArray() );

        db.getName();

		Morphia  morphia = new Morphia();
        Datastore ds = morphia.createDatastore( client, _DATABASE_ );
        ds.toString();

        // DefinitionDAO dao = new DefinitionDAO( ds );
        // long count = dao.count();
        // System.out.println( "# OVAL Definitions: " + count );
    }
 
Example 7
Project: GPMS   File: ChangePasswdAction.java   View source code 6 votes vote down vote up
@Override
public String execute() throws Exception {
	Datastore ds = MongoDBUtil.getDatastore();
	List<User> list = UserDAO.findUserList(session.getAttribute("username")
			.toString(), oldPassword);
	if (list.size() == 0) {
		return ERROR;
	} else {
		ds.updateFirst(
				ds.find(User.class, "password", oldPassword),
				ds.createUpdateOperations(User.class).set("password",
						password));
		message = "您已成功修改密码!";
		return SUCCESS;
	}
}
 
Example 8
Project: jooby   File: Issue569.java   View source code 6 votes vote down vote up
@Test
public void shouldSkipNullID() throws Exception {
  Object entity = new Object();
  new MockUnit(Datastore.class, DBObject.class, Mapper.class, MappedClass.class, Field.class,
      GeneratedValue.class)
          .expect(unit -> {

            MappedClass mclass = unit.get(MappedClass.class);
            expect(mclass.getIdField()).andReturn(null);
            Mapper mapper = unit.get(Mapper.class);
            expect(mapper.getMappedClass(entity)).andReturn(mclass);
          })
          .run(unit -> {
            new AutoIncID(unit.get(Datastore.class), IdGen.LOCAL)
                .prePersist(entity, unit.get(DBObject.class), unit.get(Mapper.class));
          });
}
 
Example 9
Project: jooby   File: MonphiaTest.java   View source code 6 votes vote down vote up
@Test
public void defaultsWithDatastoreCallback() throws Exception {
  new MockUnit(Env.class, Config.class, Binder.class)
      .expect(unit -> {
        Config config = unit.get(Config.class);
        expect(config.getConfig("mongodb")).andReturn($mongodb.getConfig("mongodb"));
        expect(config.hasPath("mongodb.db")).andReturn(false);
        expect(config.getString("db")).andReturn("mongodb://127.0.0.1/mydb");
      })
      .expect(serviceKey(new ServiceKey()))
      .expect(mongodb)
      .expect(morphia)
      .expect(unit -> {
        Datastore ds = unit.get(Datastore.class);
        ds.ensureIndexes();
      })
      .expect(objectFactory)
      .run(unit -> {
        new Monphia()
            .doWith(ds -> {
              ds.ensureIndexes();
            })
            .configure(unit.get(Env.class), unit.get(Config.class), unit.get(Binder.class));
      });
}
 
Example 10
Project: DotCi   File: MongoRepositoryTest.java   View source code 6 votes vote down vote up
@Test
@LocalData
public void should_save_mixed_type_lists() {
    MixedTypeListClass mixed = new MixedTypeListClass();
    Serializable[] mixedList = {1, "teststring", new DummySerialiazable()};
    mixed.mixedTypeList = mixedList;
    Datastore ds = SetupConfig.get().getInjector().getInstance(Datastore.class);
    ds.save(mixed);
    MixedTypeListClass restoredMixed = ds.createQuery(MixedTypeListClass.class).get();

    assertEquals(1, restoredMixed.mixedTypeList[0]);
    assertEquals("teststring", restoredMixed.mixedTypeList[1]);
    assertNotNull(restoredMixed.mixedTypeList[2]);
    assertTrue(restoredMixed.mixedTypeList[2] instanceof DummySerialiazable);
    DummySerialiazable dummy = (DummySerialiazable) restoredMixed.mixedTypeList[2];
    assertEquals("test", dummy.test);
}
 
Example 11
Project: cpa   File: ConferenceServiceImpl.java   View source code 6 votes vote down vote up
/**
* {@inheritDoc}
*/
@Override
public Iterable<Conference> list() {
	Datastore ds = getDatastore();
	if (ds.find(getEntityClass()).countAll() == 0) {
		// TODO Remove
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
		ds.save(Arrays.asList(
				create("Test 1", "Description 1", f.parse("2013-01-01 00:00:00"), f.parse("2013-01-03 00:00:00")),
				create("Test 2", "Description 2", f.parse("2013-02-01 00:00:00"), f.parse("2013-02-03 00:00:00")),
				create("Test 3", "Description 3", f.parse("2013-03-01 00:00:00"), f.parse("2013-03-03 00:00:00")),
				create("Test 4", "Description 4", f.parse("2013-04-01 00:00:00"), f.parse("2013-04-03 00:00:00"))
		));
		}
		catch (ParseException e) {
			// Ignore
		}
	}
	
 return super.list();
}
 
Example 12
Project: Incorporate   File: Incorporate.java   View source code 6 votes vote down vote up
private void setupDatabase(MongoClient mongoCl, String dbName) {
	// Initialize Morphia
	Morphia morphia = new Morphia();
	morphia.map(Company.class).map(LinkedChest.class);

	// Setup datastore
	MapperOptions opts = new MapperOptions();
	opts.objectFactory = new CustomCreator(this.getClassLoader());
	Mapper mapper = new Mapper(opts);
	Datastore ds = new DatastoreImpl(mapper, mongoCl, dbName);

	// Setup DAOs
	companyDAO = new CompanyDAO(ds);
	companyDAO.ensureIndexes();
	linkedChestDAO = new LinkedChestDAO(ds);
	linkedChestDAO.ensureIndexes();
}
 
Example 13
Project: lakeside-java   File: MongoDataSource.java   View source code 6 votes vote down vote up
/**
 * get dataStore of the db.
 * @param dbName
 * @return
 */
private Datastore doGetDatastore(String dbName) {
    Datastore datastore = datastores.get(dbName);
    if (datastore == null) {
        synchronized (MongoDataSource.class) {
            datastore = datastores.get(dbName);
            if (datastore == null) {
                datastore = ds.createDatastore(m, dbName);
                if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)) {
                    DB db = datastore.getDB();
                    if (db != null) {
                        db.authenticate(userName,this.password.toCharArray());
                    }
                }
                datastores.put(dbName, datastore);
            }
        }
    }
    return datastore;
}
 
Example 14
Project: morphia   File: ReferenceMapper.java   View source code 6 votes vote down vote up
private void readSingle(final Datastore datastore, final Mapper mapper, final Object entity, final Class fieldType,
                        final Reference annotation, final EntityCache cache, final MappedField mf, final DBObject dbObject) {

    final Object ref = mf.getDbObjectValue(dbObject);
    if (ref != null) {
        Object resolvedObject;
        if (annotation.lazy() && LazyFeatureDependencies.assertDependencyFullFilled()) {
            resolvedObject = createOrReuseProxy(datastore, mapper, fieldType, ref, cache, annotation);
        } else {
            resolvedObject = resolveObject(datastore, mapper, cache, mf, annotation.idOnly(), ref);
        }

        if (resolvedObject != null) {
            mf.setFieldValue(entity, resolvedObject);
        }

    }
}
 
Example 15
Project: morphia   File: QueryImpl.java   View source code 6 votes vote down vote up
/**
 * Creates a Query for the given type and collection
 *
 * @param clazz the type to return
 * @param coll  the collection to query
 * @param ds    the Datastore to use
 */
public QueryImpl(final Class<T> clazz, final DBCollection coll, final Datastore ds) {
    super(CriteriaJoin.AND);

    setQuery(this);
    this.clazz = clazz;
    this.ds = ((org.mongodb.morphia.DatastoreImpl) ds);
    dbColl = coll;
    cache = this.ds.getMapper().createEntityCache();

    final MappedClass mc = this.ds.getMapper().getMappedClass(clazz);
    final Entity entAn = mc == null ? null : mc.getEntityAnnotation();
    if (entAn != null) {
        getOptions().readPreference(this.ds.getMapper().getMappedClass(clazz).getEntityAnnotation().queryNonPrimary()
                   ? ReadPreference.secondaryPreferred()
                   : null);
    }
}
 
Example 16
Project: morphia   File: KeyMappingTest.java   View source code 6 votes vote down vote up
private void insertData() {
    final Datastore datastore = getDs();

    Channel sportChannel = new Channel("Sport channel");
    datastore.save(sportChannel);

    datastore.save(new Channel("Art channel"));

    Channel fitnessChannel = new Channel("Fitness channel");
    datastore.save(fitnessChannel);

    final List<Key<Channel>> followedChannels = new ArrayList<Key<Channel>>();
    followedChannels.add(datastore.getKey(sportChannel));
    followedChannels.add(datastore.getKey(fitnessChannel));

    datastore.save(new User("Roberto", datastore.getKey(sportChannel), followedChannels));
}
 
Example 17
Project: morphia   File: ReferenceTest.java   View source code 6 votes vote down vote up
@Test
public void testReferencesWithoutMapping() {
    Child child1 = new Child();
    getDs().save(child1);

    Parent parent1 = new Parent();
    parent1.children.add(child1);
    getDs().save(parent1);

    List<Parent> parentList = getDs().find(Parent.class).asList();
    Assert.assertEquals(1, parentList.size());

    // reset Datastore to reset internal Mapper cache, so Child class
    // already cached by previous save is cleared
    Datastore localDs = getMorphia().createDatastore(getMongoClient(), new Mapper(), getDb().getName());

    parentList = localDs.find(Parent.class).asList();
    Assert.assertEquals(1, parentList.size());
}
 
Example 18
Project: morphia   File: GeoQueriesTest.java   View source code 6 votes vote down vote up
@Test
public void shouldFindCitiesCloseToAGivenPointWithinARadiusOfMeters() {
    // given
    double latitude = 51.5286416;
    double longitude = -0.1015987;
    Datastore datastore = getDs();
    City london = new City("London", point(latitude, longitude));
    datastore.save(london);
    City manchester = new City("Manchester", point(53.4722454, -2.2235922));
    datastore.save(manchester);
    City sevilla = new City("Sevilla", point(37.3753708, -5.9550582));
    datastore.save(sevilla);

    getDs().ensureIndexes();

    // when
    List<City> citiesOrderedByDistanceFromLondon = datastore.find(City.class)
                                                            .field("location")
                                                            .near(pointBuilder().latitude(latitude)
                                                                                .longitude(longitude).build(), 200000)
                                                            .asList();

    // then
    assertThat(citiesOrderedByDistanceFromLondon.size(), is(1));
    assertThat(citiesOrderedByDistanceFromLondon.get(0), is(london));
}
 
Example 19
Project: morphia   File: GeoNearQueriesTest.java   View source code 6 votes vote down vote up
@Test
public void shouldFindCitiesCloseToAGivenPointWithinARadiusOfMeters() {
    // given
    double latitude = 51.5286416;
    double longitude = -0.1015987;
    Datastore datastore = getDs();
    City london = new City("London", point(latitude, longitude));
    datastore.save(london);
    City manchester = new City("Manchester", point(53.4722454, -2.2235922));
    datastore.save(manchester);
    City sevilla = new City("Sevilla", point(37.3753708, -5.9550582));
    datastore.save(sevilla);

    getDs().ensureIndexes();

    // when
    List<City> citiesOrderedByDistanceFromLondon = datastore.find(City.class)
                                                            .field("location")
                                                            .near(GeoJson.point(latitude, longitude), 200000)
                                                            .asList();

    // then
    assertThat(citiesOrderedByDistanceFromLondon.size(), is(1));
    assertThat(citiesOrderedByDistanceFromLondon.get(0), is(london));
}
 
Example 20
Project: morphia   File: TestMaxMin.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testMax() {
    final IndexedEntity a = new IndexedEntity("a");
    final IndexedEntity b = new IndexedEntity("b");
    final IndexedEntity c = new IndexedEntity("c");

    Datastore ds = getDs();

    ds.save(a);
    ds.save(b);
    ds.save(c);

    Assert.assertEquals("last", b.id, ds.find(IndexedEntity.class)
                                        .order("-id")
                                        .upperIndexBound(new BasicDBObject("testField", "c"))
                                        .get()
        .id);
    Assert.assertEquals("last", b.id, ds.find(IndexedEntity.class)
                                        .order("-id")
                                        .get(new FindOptions()
                                                 .modifier("$max", new BasicDBObject("testField", "c")))
        .id);
}
 
Example 21
Project: morphia   File: TestMaxMin.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testMin() {
    final IndexedEntity a = new IndexedEntity("a");
    final IndexedEntity b = new IndexedEntity("b");
    final IndexedEntity c = new IndexedEntity("c");

    Datastore ds = getDs();

    ds.save(a);
    ds.save(b);
    ds.save(c);

    Assert.assertEquals("last", b.id, ds.find(IndexedEntity.class).order("id")
                                        .lowerIndexBound(new BasicDBObject("testField", "b")).get().id);

    Assert.assertEquals("last", b.id, ds.find(IndexedEntity.class).order("id")
                                        .get(new FindOptions().modifier("$min", new BasicDBObject("testField", "b")))
        .id);
}
 
Example 22
Project: morphia   File: VersionTest.java   View source code 6 votes vote down vote up
@Test
public void testVersionsWithUpdate() {
    final ALongPrimitive initial = new ALongPrimitive();
    Datastore ds = getDs();
    ds.save(initial);

    Query<ALongPrimitive> query = ds.find(ALongPrimitive.class)
                                 .field("id").equal(initial.getId());
    UpdateOperations<ALongPrimitive> update = ds.createUpdateOperations(ALongPrimitive.class)
                                                .set("text", "some new value");
    UpdateResults results = ds.update(query, update);
    assertEquals(1, results.getUpdatedCount());
    ALongPrimitive postUpdate = ds.get(ALongPrimitive.class, initial.getId());

    Assert.assertEquals(initial.version + 1, postUpdate.version);
}
 
Example 23
Project: thatsapp   File: ParserWorker.java   View source code 5 votes vote down vote up
public ParserWorker(InputStream inputStream,
                    List<TimeFormat> timeFormats,
                    Datastore ds) {
    this.inputStream = inputStream;
    this.timeFormats = timeFormats;
    this.conversation = new Conversation();
    this.ds = ds;
}
 
Example 24
Project: thatsapp   File: DataStoreProvider.java   View source code 5 votes vote down vote up
@Override
public Datastore get() {
    if (ds == null){
        MongoClient mc = new MongoClient(hostname, MongoClientOptions.builder()
                .writeConcern(WriteConcern.ACKNOWLEDGED)
                .build());
        ds = morphia.createDatastore(mc, database);
    }
    return ds;
}
 
Example 25
Project: thatsapp   File: EnvironmentTests.java   View source code 5 votes vote down vote up
@Test
public void testCRUD(){
    // CREATE
    Datastore ds = new Morphia().createDatastore(new MongoClient(globalProperties.getProperty("mongoClientHostname")), globalProperties.getProperty("dbTestName"));
    Conversation conversation = new Conversation();
    conversation.addMessage(new Message().fillWithRandom());
    conversation.addMessage(new Message().fillWithRandom());
    conversation.addMessage(new Message().fillWithRandom());

    GlobalStatistics globalStatistics = new GlobalStatistics(conversation);
    globalStatistics.getStatistics().fillWithRandom();

    for (Message message : conversation.getMessages()){
        message.getSender().getStatistics().fillWithRandom();
    }

    globalStatistics.saveObjectGraph(ds);
    assertNotNull(conversation.getId());

    // UPDATE and READ
    ObjectId convId = conversation.getId();
    conversation.addMessage(new Message().fillWithRandom());

    conversation.getParticipants().stream()
            .forEach(e -> {
                        ds.save(e.getStatistics());
                        ds.save(e);
                    }
            );

    ds.save(conversation);

    Conversation retrievedConv = ds.find(Conversation.class, "id", convId).get();

    assertEquals(retrievedConv.getMessages().size(), 4);

    // DELETE
    ds.findAndDelete(ds.createQuery(Conversation.class).filter("id", convId));
    assertEquals(ds.find(Conversation.class, "id", convId).asList().size(), 0);
}
 
Example 26
Project: restler   File: MongoServiceDao.java   View source code 5 votes vote down vote up
public MongoServiceDao(Datastore datastore, Class<V> entityClazz, StatsReporter statsReporter) {
    this.morphiaDao = new BasicDAO<>(entityClazz, datastore);
    this.entityClazz = entityClazz;
    this.entityInfo = EntityInfo.get(entityClazz);
    this.entityIndexInfo = new EntityIndexInfo<>(entityClazz, morphiaDao.getCollection().getIndexInfo());
    this.collectionName = morphiaDao.getCollection().getName();
    this.statsReporter = statsReporter;
}
 
Example 27
Project: spongeblog   File: DataStoreFactory.java   View source code 5 votes vote down vote up
public static synchronized Datastore get() {

		if (dataStore == null) {
			morphia = new Morphia();
			new ValidationExtension(morphia);
			Config config = ConfigFactory.defaultApplication();
			MongoClient client = new MongoClient(new MongoClientURI(config.getString("morphia.db.uri")));;
			dataStore = morphia.createDatastore(client, config.getString("morphia.db.name"));
		}
		return dataStore;
	}
 
Example 28
Project: spring-morphia   File: MorphiaConfiguration.java   View source code 5 votes vote down vote up
@Bean
public Datastore dataStore(final Morphia morphia,
                           final MongoClient mongoClient,
                           final MongoSettings mongoSettings) {
    final Datastore datastore = morphia.createDatastore(mongoClient, mongoSettings.getDatabase());
    datastore.ensureIndexes();
    return datastore;
}
 
Example 29
Project: light-task-scheduler   File: DataStoreProvider.java   View source code 5 votes vote down vote up
public static Datastore getDataStore(Config config) {

        String[] addresses = config.getParameter(ADDRESSES_KEY, new String[]{DEFAULT_ADDRESSES});
        String database = config.getParameter(DATABASE_KEY, DEFAULT_DATABASE);
        String username = config.getParameter(USERNAME);
        String pwd = config.getParameter(PASSWORD);

        String cachedKey = StringUtils.concat(StringUtils.concat(addresses), database, username, pwd);

        Datastore datastore = DATA_STORE_MAP.get(cachedKey);
        if (datastore == null) {
            try {
                synchronized (lock) {
                    datastore = DATA_STORE_MAP.get(cachedKey);
                    if (datastore != null) {
                        return datastore;
                    }
                    Morphia morphia = new Morphia();
                    MongoFactoryBean mongoFactoryBean = new MongoFactoryBean(addresses, username, database, pwd);
                    MongoClient mongo = mongoFactoryBean.createInstance();
                    datastore = morphia.createDatastore(mongo, database);
                    DATA_STORE_MAP.put(cachedKey, datastore);
                }
            } catch (Exception e) {
                throw new IllegalStateException(
                        StringUtils.format("connect mongo failed! addresses: {}, database: {}",
                                addresses, database), e);
            }
        }
        return datastore;
    }
 
Example 30
Project: elastic-match   File: EntityDaoTest.java   View source code 5 votes vote down vote up
public void shouldCreateNewObjectInEmbeddedMongoDb() throws IOException {
    Morphia morphia = new Morphia();
    morphia.mapPackage("com.ftt.elastic.match.beans");
    MongoClient mongoClient = new MongoClient(host, port);
    Datastore datastore = morphia.createDatastore(mongoClient, DATABASE_NAME);

    EntityDAO<ARecord> entityDAO = new EntityDAO(datastore, ARecord.class);
    ARecord record = new ARecord();
    record.setDisplayId("myrecord");
    String id = (String) entityDAO.create(record);

    ARecord recordActual = entityDAO.getOne(id);
    Assert.assertEquals(recordActual.getDisplayId(), record.getDisplayId());
}
 
Example 31
Project: dropwizard-morphia   File: MorphiaBundleTest.java   View source code 5 votes vote down vote up
@Test
public void runBundle() throws Exception {
    morphiaBundle.run(mockConfiguration, mockEnvironment);

    verify(mockEnvironment.healthChecks(), times(1)).register(eq("mongo"), any(MongoHealthCheck.class));

    assertThat(morphiaBundle.getMorphia().isMapped(DummyEntity.class)).isTrue();

    Datastore datastore = morphiaBundle.getDatastore();
    assertThat(datastore.getDB().getStats().ok()).isTrue();
}
 
Example 32
Project: dropwizard-morphia   File: MongoHealthCheckTest.java   View source code 5 votes vote down vote up
@Test
public void checkUnhealthyResult() throws Exception {
    Datastore spy = spy(datastore);
    when(spy.getDB()).thenThrow(new MongoException("error"));

    MongoHealthCheck healthCheck = new MongoHealthCheck(spy);
    HealthCheck.Result result = healthCheck.check();
    assertThat(result.isHealthy()).isFalse();
    assertThat(result.getMessage()).isNotEmpty().isEqualTo("error");
}
 
Example 33
Project: dropwizard-morphia   File: MorphiaPackageBundleTest.java   View source code 5 votes vote down vote up
@Test
public void runBundle() throws Exception {
    morphiaBundle.run(mockConfiguration, mockEnvironment);

    verify(mockEnvironment.healthChecks(), times(1)).register(eq("mongo"), any(MongoHealthCheck.class));

    assertThat(morphiaBundle.getMorphia().isMapped(DummyEntity.class)).isTrue();

    Datastore datastore = morphiaBundle.getDatastore();
    assertThat(datastore.getDB().getStats().ok()).isTrue();
}
 
Example 34
Project: zucchini-ui   File: MorphiaDatastoreBuilder.java   View source code 5 votes vote down vote up
public Datastore build(final String name) {
    if (uri == null) {
        throw new IllegalStateException("URI is undefined");
    }

    // Init client options
    final MongoClientOptions activeOptions = options.orElseGet(() -> MongoClientOptions.builder().build());
    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder(activeOptions);
    if (activeOptions.getDescription() == null) {
        optionsBuilder = optionsBuilder.description(name);
    }

    // Create client
    final MongoClientURI clientURI = new MongoClientURI(uri, optionsBuilder);
    final MongoClient mongoClient = new MongoClient(clientURI);
    environment.lifecycle().manage(new AutoCloseableManagedAdapter(mongoClient));

    // Create datastore
    final Morphia activeMorphia = morphia.orElseGet(this::createMorphia);
    final Datastore datastore = activeMorphia.createDatastore(mongoClient, clientURI.getDatabase());

    // Add healthcheck
    final DB db = datastore.getDB();
    final String activeHealthcheckName = healthcheckName.orElse(name);
    environment.healthChecks().register(activeHealthcheckName, new MongoHealthCheck(db));

    return datastore;
}
 
Example 35
Project: avanto   File: AuthorDAO.java   View source code 5 votes vote down vote up
public Author findById(String id) {

		Datastore ds = getDatastore();
		Query<Author> query = ds.createQuery(Author.class).field("_id")
				.equal(id);

		return query.get();
	}
 
Example 36
Project: avanto   File: WebAppUserDAO.java   View source code 5 votes vote down vote up
public WebAppUser findByEmail(String email) {
	Datastore ds = getDatastore();
	Query<WebAppUser> query = ds.createQuery(WebAppUser.class)
			.field("email").equal(email);

	return query.get();

}
 
Example 37
Project: avanto   File: PostDAO.java   View source code 5 votes vote down vote up
public Post findIndividualByIdentifier(String identifier) {

		Datastore ds = getDatastore();
		Query<Post> query = ds.createQuery(Post.class).field("identificator")
				.equal(identifier);

		return query.get();
	}
 
Example 38
Project: avanto   File: PostDAO.java   View source code 5 votes vote down vote up
public void deleteAuthorReferences(Author author) {

		Datastore ds = getDatastore();

		UpdateOperations<Post> ops = ds.createUpdateOperations(Post.class)
				.unset("author");
		ds.update(ds.createQuery(Post.class).field("author").equal(author), ops);
	}
 
Example 39
Project: avanto   File: ParameterDAO.java   View source code 5 votes vote down vote up
public Parameter findById(String id) {

		Datastore ds = getDatastore();
		Query<Parameter> query = ds.createQuery(Parameter.class).field("_id")
				.equal(id);

		return query.get();
	}
 
Example 40
Project: simmo   File: MorphiaManager.java   View source code 5 votes vote down vote up
public static MongoDatabase getDB(String dbName) {
    if (!dbases.containsKey(dbName)) {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        dbases.put(dbName, db);
        Datastore ds = morphia.createDatastore(mongoClient, db.getName());
        morphia.mapPackage("gr.iti.mklab.simmo.core");
        ds.ensureCaps();
        ds.ensureIndexes();
    }
    return dbases.get(dbName);
}