org.mongodb.morphia.Datastore Java Examples

The following examples show how to use org.mongodb.morphia.Datastore. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DBMongoImpl.java    From heimdall with Apache License 2.0 6 votes vote down vote up
private <T> Query<T> prepareQuery(Object criteria, Datastore dataStore) {

          Query<T> query = (Query<T>) dataStore.createQuery(criteria.getClass());

          List<Field> fields = this.getAllModelFields(criteria.getClass());
          for (Field field : fields) {
               field.setAccessible(true);
               Object value = null;
               try {
                    value = field.get(criteria);
               } catch (IllegalArgumentException | IllegalAccessException e) {
                    log.error(e.getMessage(), e);
               }
               if (value != null) {
                    query.criteria(field.getName()).equal(value);
               }
          }

          return query;
     }
 
Example #2
Source File: DBMockImpl.java    From heimdall with Apache License 2.0 6 votes vote down vote up
private <T> Query<T> prepareQuery(Object criteria, Datastore dataStore) {

        Query<T> query = (Query<T>) dataStore.createQuery(criteria.getClass());

        List<Field> fields = this.getAllModelFields(criteria.getClass());
        for (Field field : fields) {
            field.setAccessible(true);
            Object value = null;
            try {
                value = field.get(criteria);
            } catch (IllegalArgumentException | IllegalAccessException ignored) {}

            if (value != null) {
                query.criteria(field.getName()).equal(value);
            }
        }

        return query;
    }
 
Example #3
Source File: MongoRepositoryTest.java    From DotCi with MIT License 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 #4
Source File: DBMockImpl.java    From heimdall with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T merge(T object) {

    try {
        Datastore ds = this.datastore();
        ds.merge(object);
        return findOne(object);
    } catch (Exception e) {
        return null;
    }

}
 
Example #5
Source File: DataStoreProvider.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
public static Datastore getDataStore(Config config) {

        String[] addresses = config.getParameter(ExtConfig.MONGO_ADDRESSES, new String[]{"127.0.0.1:27017"});
        String database = config.getParameter(ExtConfig.MONGO_DATABASE, "lts");
        String username = config.getParameter(ExtConfig.MONGO_USERNAME);
        String pwd = config.getParameter(ExtConfig.MONGO_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 #6
Source File: TestingModule.java    From DotCi with MIT License 5 votes vote down vote up
@Provides
@Singleton
Datastore provideDatastore(final Mongo mongo) {
    final String databaseName = SetupConfig.get().getDbName();

    final Mapper mapper = new JenkinsMapper();
    final Morphia morphia = new Morphia(mapper);
    return morphia.createDatastore(mongo, databaseName);

}
 
Example #7
Source File: DataStoreFactoryBean.java    From game-server with MIT License 5 votes vote down vote up
@Override
protected Datastore createInstance() throws Exception {
	// 这里的username和password可以为null,morphia对象会去处理
	MongoClientURI mongoClientURI = new MongoClientURI(uri);
	Datastore ds = morphia.createDatastore(new MongoClient(mongoClientURI), dbName);
	if (toEnsureIndexes) {
		ds.ensureIndexes();
	}
	if (toEnsureCaps) {
		ds.ensureCaps();
	}
	return ds;
}
 
Example #8
Source File: DBMongoImpl.java    From heimdall with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T merge(T object) {

     try {
          Datastore ds = this.datastore();
          ds.merge(object);
          return findOne(object);
     } catch (Exception e) {
          log.error(e.getMessage(), e);
          return null;
     }

}
 
Example #9
Source File: DynamicProjectRepository.java    From DotCi with MIT License 5 votes vote down vote up
public int assignNextBuildNumber(final DynamicProject project) {
    final Datastore datastore = getDatastore();
    BuildNumberCounter seq = datastore.findAndModify(
        datastore.find(BuildNumberCounter.class, "key = ", project.getFullName()), // query
        datastore.createUpdateOperations(BuildNumberCounter.class).inc("counter") // update
    );
    if (seq == null) {
        seq = new BuildNumberCounter(project.getFullName(), 1);
        datastore.save(seq);
    }

    return seq.getCounter();
}
 
Example #10
Source File: DotCiModule.java    From DotCi with MIT License 5 votes vote down vote up
@Provides
@Singleton
Datastore provideDatastore(final Mongo mongo) {
    final String databaseName = SetupConfig.get().getDbName();

    final Mapper mapper = new JenkinsMapper();
    final Morphia morphia = new Morphia(mapper);
    return morphia.createDatastore(mongo, databaseName);

}
 
Example #11
Source File: MongoRepository.java    From DotCi with MIT License 4 votes vote down vote up
@Inject
public MongoRepository(final Datastore datastore) {
    this.datastore = datastore;
}
 
Example #12
Source File: DynamicProjectRepository.java    From DotCi with MIT License 4 votes vote down vote up
@Inject
public DynamicProjectRepository(final Datastore datastore, final DynamicBuildRepository buildRepository) {
    this(datastore, new OrganizationContainerRepository(), buildRepository);
}
 
Example #13
Source File: MongoExperimentsCache.java    From alchemy with MIT License 4 votes vote down vote up
public MongoExperimentsCache(Datastore ds, RevisionManager revisionManager) {
    this.ds = ds;
    this.revisionManager = revisionManager;
}
 
Example #14
Source File: AbstractMongoRepository.java    From MineCloud with ISC License 4 votes vote down vote up
protected AbstractMongoRepository(Class<T> entity, Datastore datastore) {
    super(entity, datastore);
    collection = getCollection();
}
 
Example #15
Source File: MongoDatabase.java    From MineCloud with ISC License 4 votes vote down vote up
public Datastore datastore() {
    return datastore;
}
 
Example #16
Source File: PluginTypeRepository.java    From MineCloud with ISC License 4 votes vote down vote up
public static PluginTypeRepository create(Datastore ds) {
    return new PluginTypeRepository(ds);
}
 
Example #17
Source File: PluginTypeRepository.java    From MineCloud with ISC License 4 votes vote down vote up
private PluginTypeRepository(Datastore ds) {
    super(PluginType.class, ds);
}
 
Example #18
Source File: ServerTypeRepository.java    From MineCloud with ISC License 4 votes vote down vote up
public static ServerTypeRepository create(Datastore datastore) {
    return new ServerTypeRepository(datastore);
}
 
Example #19
Source File: MongoRepository.java    From DotCi with MIT License 4 votes vote down vote up
public Datastore getDatastore() {
    return this.datastore;
}
 
Example #20
Source File: GithubDeployKeyRepository.java    From DotCi with MIT License 4 votes vote down vote up
@Inject
public GithubDeployKeyRepository(final Datastore datastore) {
    super(datastore);
    this.encryptionService = new EncryptionService();
}
 
Example #21
Source File: GithubAccessTokenRepository.java    From DotCi with MIT License 4 votes vote down vote up
@Inject
public GithubAccessTokenRepository(final Datastore datastore) {
    super(datastore);
}
 
Example #22
Source File: ServerRepository.java    From MineCloud with ISC License 4 votes vote down vote up
private ServerRepository(Datastore datastore) {
    super(Server.class, datastore);
}
 
Example #23
Source File: DynamicProjectRepository.java    From DotCi with MIT License 4 votes vote down vote up
protected DynamicProjectRepository(final Datastore datastore, final OrganizationContainerRepository organizationRepository, final DynamicBuildRepository dynamicBuildRepository) {
    super(datastore);
    this.organizationRepository = organizationRepository;
    this.dynamicBuildRepository = dynamicBuildRepository;
}
 
Example #24
Source File: DynamicBuildRepository.java    From DotCi with MIT License 4 votes vote down vote up
@Inject
public DynamicBuildRepository(final Datastore datastore) {
    super(datastore);
}
 
Example #25
Source File: MongoDataLoadRule.java    From DotCi with MIT License 4 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            if (Jenkins.getInstance() == null
                || SetupConfig.get().getInjector() == null
                || SetupConfig.get().getInjector().getInstance(Datastore.class) == null) {
                throw new IllegalStateException("Requires configured Jenkins and Mongo configurations");
            }

            DB db = SetupConfig.get().getInjector().getInstance(Datastore.class).getDB();

            //Load mongo data
            File homedir = Jenkins.getInstance().getRootDir();

            for (File fileOfData : homedir.listFiles()) {
                if (!fileOfData.getName().endsWith(".json")) continue;

                String collectionName = fileOfData.getName().replaceAll("\\.json$", "");
                DBCollection collection = db.createCollection(collectionName, new BasicDBObject());

                String data = FileUtils.readFileToString(fileOfData);
                Object bsonObject = JSON.parse(data);
                if (bsonObject instanceof BasicDBList) {
                    BasicDBList basicDBList = (BasicDBList) bsonObject;
                    collection.insert(basicDBList.toArray(new DBObject[0]));
                } else {
                    collection.insert((DBObject) bsonObject);
                }

            }

            for (OrganizationContainer container : Jenkins.getInstance().getAllItems(OrganizationContainer.class)) {
                container.reloadItems();
            }

            base.evaluate();

            // Clean up mongo data
            for (String collectioName : db.getCollectionNames()) {
                db.getCollection(collectioName).drop();
            }
        }
    };
}
 
Example #26
Source File: DatastoreFactory.java    From acmeair with Apache License 2.0 4 votes vote down vote up
public static Datastore getDatastore(Datastore ds)
{
	Datastore result =ds;
	
	if (mongourl!=null)
	{
		try{
			Properties prop = new Properties();
			prop.load(DatastoreFactory.class.getResource("/acmeair-mongo.properties").openStream());
			boolean fsync = new Boolean(prop.getProperty("mongo.fsync"));
			int w = new Integer(prop.getProperty("mongo.w"));
			int connectionsPerHost = new Integer(prop.getProperty("mongo.connectionsPerHost"));
			int threadsAllowedToBlockForConnectionMultiplier = new Integer(prop.getProperty("mongo.threadsAllowedToBlockForConnectionMultiplier"));
			
			// To match the local options
			MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
				.writeConcern(new WriteConcern(w, 0, fsync))
				.connectionsPerHost(connectionsPerHost)
				.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
		
			MongoClientURI mongoURI = new MongoClientURI(mongourl, builder);
			MongoClient mongo = new MongoClient(mongoURI);
			Morphia morphia = new Morphia();				
			result = morphia.createDatastore( mongo ,mongoURI.getDatabase());
			System.out.println("create mongo datastore with options:"+result.getMongo().getMongoClientOptions());
		}catch (Exception e)
		{
			e.printStackTrace();
		}
	}
   	// The converter is added for handing JDK 7 issue
//	result.getMapper().getConverters().addConverter(new BigDecimalConverter());		
   //	result.getMapper().getConverters().addConverter(new BigIntegerConverter());
   	
	// Enable index
	result.ensureIndex(Booking.class, "pkey.customerId");
	result.ensureIndex(Flight.class, "pkey.flightSegmentId,scheduledDepartureTime");
	result.ensureIndex(FlightSegment.class, "originPort,destPort");

   	return result;
}
 
Example #27
Source File: MongoConnectionManager.java    From acmeair with Apache License 2.0 4 votes vote down vote up
public Datastore getDatastore(){
	return datastore;
}
 
Example #28
Source File: ServerRepository.java    From MineCloud with ISC License 4 votes vote down vote up
public static ServerRepository create(Datastore datastore) {
    return new ServerRepository(datastore);
}
 
Example #29
Source File: MongoBaseService.java    From game-server with MIT License 4 votes vote down vote up
public Datastore getDatastore() {
	return baseDao.getDatastore();
}
 
Example #30
Source File: DataStoreFactoryBean.java    From game-server with MIT License 4 votes vote down vote up
@Override
public Class<?> getObjectType() {
	return Datastore.class;
}