Java 类com.mongodb.DB 实例源码

项目:geeCommerce-Java-Shop-Software-and-PIM    文件:SynonymsGenerator.java   
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);
    }
}
项目:mongodb-broker    文件:MongoAdminService.java   
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);
        }
    }
项目:mongodb-broker    文件:MongoServiceInstanceService.java   
@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();
}
项目:sentry    文件:InitialSetupMigration.java   
@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);
}
项目:crauler_ISI    文件:MongoFunctions.java   
/**
 * 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());
    }
}
项目:biomedicus    文件:MongoDbXmiWriter.java   
@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);
}
项目:cloud-meter    文件:MongoDB.java   
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;
    }
项目:cloud-meter    文件:MongoScriptRunner.java   
/**
 * 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();
    }
}
项目:Trivial5b    文件:Mongo.java   
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();
        }
}
项目:gravity    文件:MongoRepositoryFactory.java   
@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();    
}
项目:log-dropwizard-eureka-mongo-sample    文件:LogWriterApp.java   
@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);

}
项目:XBDD    文件:Favourites.java   
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));
}
项目:Trivial_i1a    文件:Connection.java   
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();
    }
}
项目:teiid    文件:TestMongoDBDirectQueryExecution.java   
@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());
}
项目:hadoop-mini-clusters    文件:MongodbLocalServerIntegrationTest.java   
@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();
}
项目:Trivial4b    文件:TrivialAPI.java   
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;
}
项目:kurve-server    文件:MongoAccountServiceTests.java   
@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);
}
项目:peak-forecast    文件:Monitor.java   
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());
       }
}
项目:XBDD    文件:AutomationStatistics.java   
@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;
}
项目:XBDD    文件:Feature.java   
@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();
        }
    }
}
项目:XBDD    文件:Presence.java   
@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;
    }
}
项目:nitrite-database    文件:NitriteDataGate.java   
@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);
}
项目:elastest-instrumentation-manager    文件:AgentConfigurationRepository.java   
public AgentConfigurationRepository(){
    MongoClient mongoClient = new MongoClient( 
            Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST), 
            27017);
    DB db = mongoClient.getDB("eim");
    collection = db.getCollection("agentConfiguration");
}
项目:elastest-instrumentation-manager    文件:AgentRepository.java   
public AgentRepository(){
    MongoClient mongoClient = new MongoClient( 
            Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST), 
            27017);
    DB db = mongoClient.getDB("eim");
    collection = db.getCollection("agent");
}
项目:mycat-src-1.6.1-RELEASE    文件:MongoConnection.java   
public DB getDB()  {
    if (this._schema!=null) {
      return this.mc.getDB(this._schema);
    }
    else {
        return null;
    }
}
项目:sentry    文件:InitialSetupMigration.java   
@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());
}
项目:sentry    文件:InitialSetupMigration.java   
@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);
}
项目:sentry    文件:InitialSetupMigration.java   
@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());
}
项目:sentry    文件:InitialSetupMigration.java   
@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());
}
项目:core-data    文件:MongoDBConnectivityTest.java   
@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");
  }
}
项目:KernelHive    文件:DataManager.java   
public GridFS connectToDatabase(ServerAddress server) {
    MongoCredential credential = MongoCredential.createMongoCRCredential("hive-dataserver", "admin", "hive-dataserver".toCharArray());
    MongoClient mongoClient = new MongoClient(server, Arrays.asList(credential));
    logger.info("got client");
    DB db = mongoClient.getDB("hive-dataserver");
    logger.info("Got DB");
    return new GridFS(db);
}
项目:sample-acmegifts    文件:MongoAccess.java   
/** Get a connection to Mongo. */
public synchronized DB getMongoDB() {
  if (database == null) {
    try {
      MongoClient client = new MongoClient(mongoHostname, mongoPort);
      database = client.getDB("gifts-user");
    } catch (UnknownHostException uhe) {
      throw new RuntimeException(uhe);
    }
  }

  return database;
}
项目:sample-acmegifts    文件:UserResource.java   
/**
 * Delete a user.
 *
 * @param id The ID of the user to delete.
 * @return Nothing.
 */
@DELETE
@Path("/{id}")
public Response deleteUser(@PathParam("id") String id) {
  // Validate the JWT.  The JWT must be in the 'users' group.  We do not check
  // to see if the user is deleting their own profile.
  try {
    validateJWT(new HashSet<String>(Arrays.asList("users")));
  } catch (JWTException jwte) {
    return Response.status(Status.UNAUTHORIZED)
        .type(MediaType.TEXT_PLAIN)
        .entity(jwte.getMessage())
        .build();
  }

  // Retrieve the user from the database.
  DB database = mongo.getMongoDB();
  DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
  ObjectId dbId = new ObjectId(id);
  DBObject dbUser = dbCollection.findOne(dbId);

  // If the user did not exist, return an error.  Otherwise, remove the user.
  if (dbUser == null) {
    return Response.status(Status.BAD_REQUEST).entity("The user name was not Found.").build();
  }

  dbCollection.remove(new BasicDBObject(User.DB_ID, dbId));
  return Response.ok().build();
}
项目:sample-acmegifts    文件:UserResource.java   
/**
 * Retrieve a user's profile.
 *
 * @param id The ID of the user.
 * @return The user's profile, as a JSON object. Private fields such as password and salt are not
 *     returned.
 */
@GET
@Path("/{id}")
@Produces("application/json")
public Response getUser(@PathParam("id") String id) {
  // Validate the JWT.  The JWT must belong to the 'users' or 'orchestrator' group.
  // We do not check if the user is retrieving their own profile, or someone else's.
  try {
    validateJWT(new HashSet<String>(Arrays.asList("users", "orchestrator")));
  } catch (JWTException jwte) {
    return Response.status(Status.UNAUTHORIZED)
        .type(MediaType.TEXT_PLAIN)
        .entity(jwte.getMessage())
        .build();
  }

  // Retrieve the user from the database.
  DB database = mongo.getMongoDB();
  DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
  DBObject user = dbCollection.findOne(new ObjectId(id));

  // If the user did not exist, return an error.  Otherwise, only return the public
  // fields (exclude things like the password).
  if (user == null) {
    return Response.status(Status.BAD_REQUEST).entity("The user not Found.").build();
  }

  JsonObject responsePayload = new User(user).getPublicJsonObject();

  return Response.ok(responsePayload, MediaType.APPLICATION_JSON).build();
}
项目:sample-acmegifts    文件:UserResource.java   
/**
 * Get all user profiles.
 *
 * @return All user profiles (excluding private fields like password).
 */
@GET
@Produces("application/json")
public Response getAllUsers() {
  // Validate the JWT. The JWT must be in the 'users' group.
  try {
    validateJWT(new HashSet<String>(Arrays.asList("users")));
  } catch (JWTException jwte) {
    return Response.status(Status.UNAUTHORIZED)
        .type(MediaType.TEXT_PLAIN)
        .entity(jwte.getMessage())
        .build();
  }

  // Get all the users from the database, and add them to an array.
  DB database = mongo.getMongoDB();
  DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
  DBCursor cursor = dbCollection.find();
  JsonArrayBuilder userArray = Json.createArrayBuilder();
  while (cursor.hasNext()) {
    // Exclude all private information from the list.
    userArray.add((new User(cursor.next()).getPublicJsonObject()));
  }

  // Return the user list to the caller.
  JsonObjectBuilder responseBuilder = Json.createObjectBuilder().add("users", userArray.build());
  return Response.ok(responseBuilder.build(), MediaType.APPLICATION_JSON).build();
}
项目:sample-acmegifts    文件:MongoAccess.java   
/** Get a connection to Mongo */
public synchronized DB getMongoDB() {
  if (database == null) {
    try {
      MongoClient client = new MongoClient(mongoHostname, mongoPort);
      database = client.getDB("gifts-occasion");
    } catch (UnknownHostException uhe) {
      throw new RuntimeException(uhe);
    }
  }

  return database;
}
项目:sample-acmegifts    文件:MongoAccess.java   
/** Get a connection to Mongo */
public synchronized DB getMongoDB() {
  if (database == null) {
    try {
      MongoClient client = new MongoClient(mongoHostname, mongoPort);
      database = client.getDB("gifts-group");
    } catch (UnknownHostException uhe) {
      throw new RuntimeException(uhe);
    }
  }

  return database;
}
项目:QDrill    文件:MongoPStoreProvider.java   
@Override
public void start() throws IOException {
  MongoClientURI clientURI = new MongoClientURI(mongoURL);
  client = new MongoClient(clientURI);
  DB db = client.getDB(clientURI.getDatabase());
  collection = db.getCollection(clientURI.getCollection());
  collection.setWriteConcern(WriteConcern.JOURNALED);
  DBObject index = new BasicDBObject(1).append(pKey, Integer.valueOf(1));
  collection.createIndex(index);
}