当前位置: 首页>>代码示例>>Java>>正文


Java DB类代码示例

本文整理汇总了Java中com.mongodb.DB的典型用法代码示例。如果您正苦于以下问题:Java DB类的具体用法?Java DB怎么用?Java DB使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


DB类属于com.mongodb包,在下文中一共展示了DB类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: generateFile

import com.mongodb.DB; //导入依赖的package包/类
public void generateFile(String filename) {
    DB db = MongoHelper.mongoMerchantDB();

    DBCollection col = db.getCollection(COLLECTION_SYNONYMS);
    DBCursor cursor = col.find();
    try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)))) {
        while (cursor.hasNext()) {
            DBObject doc = cursor.next();
            String word = doc.get(FIELD_KEY_WORLD) != null ? doc.get(FIELD_KEY_WORLD).toString() : null;
            String synonyms = doc.get(FIELD_KEY_WORLD) != null
                ? StringUtils.join((BasicDBList) doc.get(FIELD_KEY_SYNONYMS), ",") : null;
            if (word != null && synonyms != null) {
                out.println(createLine(word, synonyms));
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("IOException: Current db cursor with id: " + cursor.curr().get("_id"), e);
    }
}
 
开发者ID:geetools,项目名称:geeCommerce-Java-Shop-Software-and-PIM,代码行数:20,代码来源:SynonymsGenerator.java

示例2: addUsers

import com.mongodb.DB; //导入依赖的package包/类
@ChangeSet(order = "01",
           author = "developer",
           id = "01-addUsers")
public void addUsers(final DB db) {
    final DBCollection userCollection = db.getCollection(User.COLLECTION_NAME);

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c3f"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "One")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c40"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "Two")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());
}
 
开发者ID:karlkyck,项目名称:spring-boot-completablefuture,代码行数:23,代码来源:InitialSetupMigration.java

示例3: createDatabase

import com.mongodb.DB; //导入依赖的package包/类
public DB createDatabase(String databaseName) throws MongoServiceException {
		try {
			DB db = client.getDB(databaseName);
			
			// save into a collection to force DB creation.
			DBCollection col = db.createCollection("foo", null);
			BasicDBObject obj = new BasicDBObject();
			obj.put("foo", "bar");
			col.insert(obj);
			// drop the collection so the db is empty
//			col.drop();
			
			return db; 
		} catch (MongoException e) {
			// try to clean up and fail
			try {
				deleteDatabase(databaseName);
			} catch (MongoServiceException ignore) {}
			throw handleException(e);
		}
	}
 
开发者ID:cf-platform-eng,项目名称:mongodb-broker,代码行数:22,代码来源:MongoAdminService.java

示例4: createServiceInstance

import com.mongodb.DB; //导入依赖的package包/类
@Override
public CreateServiceInstanceResponse createServiceInstance(CreateServiceInstanceRequest request) {
	// TODO MongoDB dashboard
	ServiceInstance instance = repository.findOne(request.getServiceInstanceId());
	if (instance != null) {
		throw new ServiceInstanceExistsException(request.getServiceInstanceId(), request.getServiceDefinitionId());
	}

	instance = new ServiceInstance(request);

	if (mongo.databaseExists(instance.getServiceInstanceId())) {
		// ensure the instance is empty
		mongo.deleteDatabase(instance.getServiceInstanceId());
	}

	DB db = mongo.createDatabase(instance.getServiceInstanceId());
	if (db == null) {
		throw new ServiceBrokerException("Failed to create new DB instance: " + instance.getServiceInstanceId());
	}
	repository.save(instance);

	return new CreateServiceInstanceResponse();
}
 
开发者ID:cf-platform-eng,项目名称:mongodb-broker,代码行数:24,代码来源:MongoServiceInstanceService.java

示例5: addSocialUserConnection

import com.mongodb.DB; //导入依赖的package包/类
@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);
}
 
开发者ID:quanticc,项目名称:sentry,代码行数:11,代码来源:InitialSetupMigration.java

示例6: calcularLocalizaciones

import com.mongodb.DB; //导入依赖的package包/类
/**
 * Map reduce.
 *
 * @param mongoOperation
 *            the mongo operation
 * @param a
 *            the a
 * @param b
 *            the b
 * @param c
 *            the c
 * @param d
 *            the d
 * @throws UnknownHostException
 */
static void calcularLocalizaciones() throws UnknownHostException {

	String map = "function () { emit(this.localizacion, {count: 1}); }";
	String reduce = " function(key, values) { var result = 0; values.forEach(function(value){ result++ }); "
			+ "return result; }";

	MongoClient mongoClient = new MongoClient("localhost", 27017);
	DB db = mongoClient.getDB("craulerdb");
	DBCollection ofertas = db.getCollection("ofertas");

	MapReduceCommand cmd = new MapReduceCommand(ofertas, map, reduce, null, MapReduceCommand.OutputType.INLINE,
			null);
	MapReduceOutput out = ofertas.mapReduce(cmd);

	for (DBObject o : out.results()) {
		System.out.println(o.toString());
	}
}
 
开发者ID:acardoco,项目名称:crauler_ISI,代码行数:34,代码来源:MongoFunctions.java

示例7: initialize

import com.mongodb.DB; //导入依赖的package包/类
@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
  super.initialize(aContext);

  String mongoServer = (String) aContext.getConfigParameterValue(PARAM_MONGO_SERVER);
  int mongoPort = (Integer) aContext.getConfigParameterValue(PARAM_MONGO_PORT);
  String mongoDbName = (String) aContext.getConfigParameterValue(PARAM_MONGO_DB_NAME);

  try {
    mongoClient = new MongoClient(mongoServer, mongoPort);
  } catch (UnknownHostException e) {
    throw new ResourceInitializationException(e);
  }

  DB db = mongoClient.getDB(mongoDbName);

  gridFS = new GridFS(db);
}
 
开发者ID:nlpie,项目名称:biomedicus,代码行数:19,代码来源:MongoDbXmiWriter.java

示例8: getDB

import com.mongodb.DB; //导入依赖的package包/类
public DB getDB(String database, String username, String password) {

        if(log.isDebugEnabled()) {
            log.debug("username: " + username+", password: " + password+", database: " + database);
        }
        DB db = mongo.getDB(database);
        boolean authenticated = db.isAuthenticated();

        if(!authenticated) {
            if(username != null && password != null && username.length() > 0 && password.length() > 0) {
                authenticated = db.authenticate(username, password.toCharArray());
            }
        }
        if(log.isDebugEnabled()) {
            log.debug("authenticated: " + authenticated);
        }
        return db;
    }
 
开发者ID:johrstrom,项目名称:cloud-meter,代码行数:19,代码来源:MongoDB.java

示例9: evaluate

import com.mongodb.DB; //导入依赖的package包/类
/**
 * Evaluate a script on the database
 *
 * @param db
 *            database connection to use
 * @param script
 *            script to evaluate on the database
 * @return result of evaluation on the database
 * @throws Exception
 *             when evaluation on the database fails
 */
public Object evaluate(DB db, String script)
    throws Exception {

    if(log.isDebugEnabled()) {
        log.debug("database: " + db.getName()+", script: " + script);
    }

    db.requestStart();
    try {
        db.requestEnsureConnection();

        Object result = db.eval(script);

        if(log.isDebugEnabled()) {
            log.debug("Result : " + result);
        }
        return result;
    } finally {
        db.requestDone();
    }
}
 
开发者ID:johrstrom,项目名称:cloud-meter,代码行数:33,代码来源:MongoScriptRunner.java

示例10: main

import com.mongodb.DB; //导入依赖的package包/类
public static void main(String[] args) throws IOException {
	MongoClient mongoClient = new MongoClient("localhost", 27017);
	DB db = mongoClient.getDB("mydb");
	DBCollection coll = db.getCollection("questionsCollection");
	mongoClient.setWriteConcern(WriteConcern.JOURNALED);
	GIFTParser p = new GIFTParser();
	BasicDBObject doc = null;
	for (Question q : p.parserGIFT("Data/questionsGIFT")) {
		doc = new BasicDBObject("category", q.getCategory())
				.append("question", q.getText())
				.append("correctanswer", q.getCorrectAnswer())
				.append("wrongAnswers",q.getWrongAnswers());
		coll.insert(doc);
	}

	DBCursor cursor = coll.find();
	try {
		   while(cursor.hasNext()) {
		       System.out.println(cursor.next());
		   }
		} finally {
		   cursor.close();
		}
}
 
开发者ID:Arquisoft,项目名称:Trivial5b,代码行数:25,代码来源:Mongo.java

示例11: getFactoryInstance

import com.mongodb.DB; //导入依赖的package包/类
@Override
public Repository getFactoryInstance() throws UnknownHostException {
	String[] hostArray = this.getHost().split(",");
	List<String> hostList = Arrays.asList(hostArray);
	
	List<ServerAddress> serverList = new ArrayList<ServerAddress>();
	for( String hostURL : hostList){
		ServerAddress sa = new ServerAddress(hostURL);
		serverList.add(sa);
	}
	
	MongoClient mc = new MongoClient(serverList);
	DB db = mc.getDB("gravity");
    DocumentNodeStore ns = new DocumentMK.Builder().
            setMongoDB(db).getNodeStore();		    
    
    return new Jcr(new Oak(ns))
    	.with(new RepositoryIndexInitializer())
    	.withAsyncIndexing()
    	.createRepository();	
}
 
开发者ID:cheetah100,项目名称:gravity,代码行数:22,代码来源:MongoRepositoryFactory.java

示例12: run

import com.mongodb.DB; //导入依赖的package包/类
@Override
public void run(LogWriterConfiguration configuration,
                Environment environment) throws UnknownHostException, NoDBNameException {


    final MongoClient mongoClient = configuration.getMongoFactory().buildClient(environment);
    final DB db = configuration.getMongoFactory().buildDB(environment);

    //Register health checks
    environment.healthChecks().register("mongo",new MongoHealthCheck(mongoClient));

    final LogWriterResource resource = new LogWriterResource(
            configuration.getTemplate(),
            configuration.getDefaultName(),
            db
    );
    environment.jersey().register(resource);

    final LogWriterHealthCheck healthCheck =
            new LogWriterHealthCheck(configuration.getTemplate());
    environment.healthChecks().register("logwriter", healthCheck);
    environment.jersey().register(resource);

}
 
开发者ID:guggens,项目名称:log-dropwizard-eureka-mongo-sample,代码行数:25,代码来源:LogWriterApp.java

示例13: setPinStateOfBuild

import com.mongodb.DB; //导入依赖的package包/类
private void setPinStateOfBuild(final String product,
		final String version,
		final String build,
		final boolean state) {
	
	final DB db = this.client.getDB("bdd");
	final DBCollection collection = db.getCollection("summary");
	
	final BasicDBObject query = new BasicDBObject("_id",product+"/"+version);
	final BasicDBObject toBePinned = new BasicDBObject("pinned",build);
	final String method;
	
	if (state) {
		method = "$addToSet";
	} else {
		method = "$pull";
	}
	
	collection.update(query, new BasicDBObject(method,toBePinned));
}
 
开发者ID:orionhealth,项目名称:XBDD,代码行数:21,代码来源:Favourites.java

示例14: connection

import com.mongodb.DB; //导入依赖的package包/类
public static void connection() {
	try {

		DB db = (new MongoClient("localhost", 27017)).getDB("Questions");

		DBCollection coll = db.getCollection("Questions");

		BasicDBObject query = new BasicDBObject();
		query.put("id", 1001);
		DBCursor cursor = coll.find(query);
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}
	} catch (MongoException e) {
		e.printStackTrace();
	}
}
 
开发者ID:Arquisoft,项目名称:Trivial_i1a,代码行数:18,代码来源:Connection.java

示例15: testShellDirect

import com.mongodb.DB; //导入依赖的package包/类
@Test
public void testShellDirect() throws Exception {
    Command cmd = this.utility.parseCommand("SELECT * FROM Customers");
    MongoDBConnection connection = Mockito.mock(MongoDBConnection.class);
    ExecutionContext context = Mockito.mock(ExecutionContext.class);
    DBCollection dbCollection = Mockito.mock(DBCollection.class);
    DB db = Mockito.mock(DB.class);
    Mockito.stub(db.getCollection("MyTable")).toReturn(dbCollection);
    
    Mockito.stub(db.collectionExists(Mockito.anyString())).toReturn(true);
    Mockito.stub(connection.getDatabase()).toReturn(db);
    
    Argument arg = new Argument(Direction.IN, null, String.class, null);
    arg.setArgumentValue(new Literal("$ShellCmd;MyTable;remove;{ qty: { $gt: 20 }}", String.class));

    ResultSetExecution execution = this.translator.createDirectExecution(Arrays.asList(arg), cmd, context, this.utility.createRuntimeMetadata(), connection);
    execution.execute();
    Mockito.verify(dbCollection).remove(QueryBuilder.start("qty").greaterThan(20).get());
}
 
开发者ID:kenweezy,项目名称:teiid,代码行数:20,代码来源:TestMongoDBDirectQueryExecution.java


注:本文中的com.mongodb.DB类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。