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);
}
}
java类com.mongodb.DB的实例源码
SynonymsGenerator.java 文件源码
项目:geeCommerce-Java-Shop-Software-and-PIM
阅读 26
收藏 0
点赞 0
评论 0
MongoAdminService.java 文件源码
项目:mongodb-broker
阅读 26
收藏 0
点赞 0
评论 0
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);
}
}
MongoServiceInstanceService.java 文件源码
项目:mongodb-broker
阅读 34
收藏 0
点赞 0
评论 0
@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();
}
InitialSetupMigration.java 文件源码
项目:sentry
阅读 29
收藏 0
点赞 0
评论 0
@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);
}
MongoFunctions.java 文件源码
项目:crauler_ISI
阅读 54
收藏 0
点赞 0
评论 0
/**
* 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());
}
}
MongoDbXmiWriter.java 文件源码
项目:biomedicus
阅读 24
收藏 0
点赞 0
评论 0
@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);
}
MongoDB.java 文件源码
项目:cloud-meter
阅读 29
收藏 0
点赞 0
评论 0
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;
}
MongoScriptRunner.java 文件源码
项目:cloud-meter
阅读 24
收藏 0
点赞 0
评论 0
/**
* 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();
}
}
Mongo.java 文件源码
项目:Trivial5b
阅读 37
收藏 0
点赞 0
评论 0
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();
}
}
MongoRepositoryFactory.java 文件源码
项目:gravity
阅读 31
收藏 0
点赞 0
评论 0
@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();
}
LogWriterApp.java 文件源码
项目:log-dropwizard-eureka-mongo-sample
阅读 25
收藏 0
点赞 0
评论 0
@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);
}
Favourites.java 文件源码
项目:XBDD
阅读 30
收藏 0
点赞 0
评论 0
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));
}
Connection.java 文件源码
项目:Trivial_i1a
阅读 39
收藏 0
点赞 0
评论 0
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();
}
}
TestMongoDBDirectQueryExecution.java 文件源码
项目:teiid
阅读 33
收藏 0
点赞 0
评论 0
@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());
}
MongodbLocalServerIntegrationTest.java 文件源码
项目:hadoop-mini-clusters
阅读 25
收藏 0
点赞 0
评论 0
@Test
public void testMongodbLocalServer() throws Exception {
MongoClient mongo = new MongoClient(mongodbLocalServer.getIp(), mongodbLocalServer.getPort());
DB db = mongo.getDB(propertyParser.getProperty(ConfigVars.MONGO_DATABASE_NAME_KEY));
DBCollection col = db.createCollection(propertyParser.getProperty(ConfigVars.MONGO_COLLECTION_NAME_KEY),
new BasicDBObject());
col.save(new BasicDBObject("testDoc", new Date()));
LOG.info("MONGODB: Number of items in collection: {}", col.count());
assertEquals(1, col.count());
DBCursor cursor = col.find();
while(cursor.hasNext()) {
LOG.info("MONGODB: Document output: {}", cursor.next());
}
cursor.close();
}
TrivialAPI.java 文件源码
项目:Trivial4b
阅读 24
收藏 0
点赞 0
评论 0
private static DB conectar() {
MongoClient mongoClient = null;
MongoCredential mongoCredential = MongoCredential
.createMongoCRCredential("trivialuser", "trivial",
"4btrivialmongouser".toCharArray());
try {
mongoClient = new MongoClient(new ServerAddress(
"ds062797.mongolab.com", 62797),
Arrays.asList(mongoCredential));
} catch (UnknownHostException e) {
e.printStackTrace();
}
DB db = mongoClient.getDB("trivial");
System.out.println("Conexion creada con la base de datos");
return db;
}
MongoAccountServiceTests.java 文件源码
项目:kurve-server
阅读 25
收藏 0
点赞 0
评论 0
@BeforeClass
public static void init() throws UnknownHostException {
ServerAddress mongoServer = new ServerAddress(dbConfig.host, Integer.valueOf(dbConfig.port));
MongoCredential credential = MongoCredential.createCredential(
dbConfig.username,
dbConfig.name,
dbConfig.password.toCharArray()
);
MongoClient mongoClient = new MongoClient(mongoServer, new ArrayList<MongoCredential>() {{
add(credential);
}});
DB db = mongoClient.getDB(dbConfig.name);
accountService = new MongoAccountService( db);
}
Monitor.java 文件源码
项目:peak-forecast
阅读 32
收藏 0
点赞 0
评论 0
public CollectTraceWikipedia(ActorRef analyse, ShellService shell) {
this.analyse = analyse;
this.sh = shell;
try {
//nbre de requettes sauvegardé par interval de 30 secondes
Mongo m = new Mongo();
DB db = m.getDB( "trace10" );
DBCollection collTime = db.getCollection("thirtyseconde");
DBCursor cursor = collTime.find().sort(new BasicDBObject( "debutdate" , 1 ));
this.list = cursor.toArray();
}
catch (Exception e) {
System.out.println(e.toString());
}
}
AutomationStatistics.java 文件源码
项目:XBDD
阅读 23
收藏 0
点赞 0
评论 0
@GET
@Path("/recent-builds/{product}")
public DBObject getRecentBuildStatsForProduct(@BeanParam final Coordinates coordinates, @QueryParam("limit") final Integer limit) {
final BasicDBList returns = new BasicDBList();
final DB db = this.client.getDB("bdd");
final DBCollection collection = db.getCollection("reportStats");
final BasicDBObject example = coordinates.getQueryObject(Field.PRODUCT);
final DBCursor cursor = collection.find(example).sort(Coordinates.getFeatureSortingObject());
if (limit != null) {
cursor.limit(limit);
}
try {
while (cursor.hasNext()) {
final DBObject doc = cursor.next();
returns.add(doc);
}
} finally {
cursor.close();
}
return returns;
}
Feature.java 文件源码
项目:XBDD
阅读 28
收藏 0
点赞 0
评论 0
@SuppressWarnings("unchecked")
public static void embedTestingTips(final DBObject feature, final Coordinates coordinates, final DB db) {
final DBCollection tips = db.getCollection("testingTips");
final List<DBObject> elements = (List<DBObject>) feature.get("elements");
for (final DBObject scenario : elements) {
DBObject oldTip = null;
final BasicDBObject tipQuery = coordinates.getTestingTipsCoordinatesQueryObject((String) feature.get("id"), (String) scenario.get("id"));
// get the most recent tip that is LTE to the current coordinates. i.e. sort in reverse chronological order and take the first
// item (if one exists).
final DBCursor oldTipCursor = tips.find(tipQuery)
.sort(new BasicDBObject("coordinates.major", -1).append("coordinates.minor", -1)
.append("coordinates.servicePack", -1).append("coordinates.build", -1)).limit(1);
try {
if (oldTipCursor.hasNext()) {
oldTip = oldTipCursor.next();
scenario.put("testing-tips", oldTip.get("testing-tips"));
}
} finally {
oldTipCursor.close();
}
}
}
Presence.java 文件源码
项目:XBDD
阅读 25
收藏 0
点赞 0
评论 0
@GET
@Path("/{product}/{major}.{minor}.{servicePack}/{build}")
public DBObject getPresencesForBuild(@BeanParam final Coordinates coordinates) {
try {
final DB db = this.client.getDB("bdd");
final DBCollection collection = db.getCollection("presence");
final BasicDBObject query = coordinates.getQueryObject(Field.PRODUCT, Field.VERSION, Field.BUILD);
final BasicDBList presencesForBuild = new BasicDBList();
final DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
presencesForBuild.add(cursor.next());
}
return presencesForBuild;
} catch (final Throwable th) {
th.printStackTrace();
return null;
}
}
NitriteDataGate.java 文件源码
项目:nitrite-database
阅读 28
收藏 0
点赞 0
评论 0
@Bean
public Jongo jongo() {
MongoCredential credential =
MongoCredential.createCredential(mongoUser, mongoDatabase,
mongoPassword.toCharArray());
ServerAddress serverAddress = new ServerAddress(mongoHost, mongoPort);
MongoClient mongoClient = new MongoClient(serverAddress,
new ArrayList<MongoCredential>() {{
add(credential);
}});
DB db = mongoClient.getDB(mongoDatabase);
return new Jongo(db);
}
AgentConfigurationRepository.java 文件源码
项目:elastest-instrumentation-manager
阅读 25
收藏 0
点赞 0
评论 0
public AgentConfigurationRepository(){
MongoClient mongoClient = new MongoClient(
Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST),
27017);
DB db = mongoClient.getDB("eim");
collection = db.getCollection("agentConfiguration");
}
AgentRepository.java 文件源码
项目:elastest-instrumentation-manager
阅读 23
收藏 0
点赞 0
评论 0
public AgentRepository(){
MongoClient mongoClient = new MongoClient(
Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST),
27017);
DB db = mongoClient.getDB("eim");
collection = db.getCollection("agent");
}
MongoConnection.java 文件源码
项目:mycat-src-1.6.1-RELEASE
阅读 28
收藏 0
点赞 0
评论 0
public DB getDB() {
if (this._schema!=null) {
return this.mc.getDB(this._schema);
}
else {
return null;
}
}
InitialSetupMigration.java 文件源码
项目:sentry
阅读 28
收藏 0
点赞 0
评论 0
@ChangeSet(order = "01", author = "initiator", id = "01-addAuthorities")
public void addAuthorities(DB db) {
DBCollection authorityCollection = db.getCollection("jhi_authority");
authorityCollection.insert(
BasicDBObjectBuilder.start()
.add("_id", "ROLE_ADMIN")
.get());
authorityCollection.insert(
BasicDBObjectBuilder.start()
.add("_id", "ROLE_USER")
.get());
}
InitialSetupMigration.java 文件源码
项目:sentry
阅读 22
收藏 0
点赞 0
评论 0
@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);
}
InitialSetupMigration.java 文件源码
项目:sentry
阅读 21
收藏 0
点赞 0
评论 0
@ChangeSet(order = "04", author = "user", id = "04-addAuthorities-2")
public void addAuthorities2(DB db) {
DBCollection authorityCollection = db.getCollection("jhi_authority");
authorityCollection.insert(
BasicDBObjectBuilder.start()
.add("_id", "ROLE_MANAGER")
.get());
authorityCollection.insert(
BasicDBObjectBuilder.start()
.add("_id", "ROLE_SUPPORT")
.get());
}
InitialSetupMigration.java 文件源码
项目:sentry
阅读 23
收藏 0
点赞 0
评论 0
@ChangeSet(order = "05", author = "user", id = "05-addAuthorities-3")
public void addAuthorities3(DB db) {
DBCollection authorityCollection = db.getCollection("jhi_authority");
authorityCollection.insert(
BasicDBObjectBuilder.start()
.add("_id", "ROLE_ACTUATOR")
.get());
}
MongoDBConnectivityTest.java 文件源码
项目:core-data
阅读 25
收藏 0
点赞 0
评论 0
@Test
public void testMongoDBConnect() throws UnknownHostException {
MongoClient mongoClient = new MongoClient(new MongoClientURI(MONGO_URI));
DB database = mongoClient.getDB(DB_NAME);
DBCollection events = database.getCollection(EVENT_COLLECTION_NAME);
DBCollection readings = database.getCollection(READING_COLLECTION_NAME);
try {
assertFalse("MongoDB Events collection not accessible", events.isCapped());
assertFalse("MongoDB Readings collection not accessible", readings.isCapped());
} catch (MongoTimeoutException ex) {
fail("Mongo DB not available. Check that Mongo DB has been started");
}
}