Java 类com.mongodb.Mongo 实例源码

项目:beam    文件:MongoDbGridFSIO.java   
@Override
public long getEstimatedSizeBytes(PipelineOptions options) throws Exception {
  Mongo mongo = spec.connectionConfiguration().setupMongo();
  try {
    GridFS gridfs = spec.connectionConfiguration().setupGridFS(mongo);
    DBCursor cursor = createCursor(gridfs);
    long size = 0;
    while (cursor.hasNext()) {
      GridFSDBFile file = (GridFSDBFile) cursor.next();
      size += file.getLength();
    }
    return size;
  } finally {
    mongo.close();
  }
}
项目:navi    文件:NaviMongoListDriver.java   
public NaviMongoListDriver(ServerUrlUtil.ServerUrl server, String auth, NaviPoolConfig poolConfig) throws NumberFormatException, MongoException, UnknownHostException {
    super(server, auth, poolConfig);

    String masterUrl = null;
    if (server.getHost() != null && server.getPort() != 0)
        masterUrl = server.getHost() + ":" + server.getPort();
    List<ServerAddress> addresslist = new ArrayList<>();
    // 找到master
    List<String> listHostPorts = new ArrayList<>();
    String[] hostPorts = server.getUrl().split(",");
    Collections.addAll(listHostPorts, hostPorts);
    for (int i = 0; i < listHostPorts.size(); i++) {
        if (listHostPorts.get(0).equals(masterUrl))
            break;
        listHostPorts.add(listHostPorts.remove(0));
    }
    for (String hostPort : listHostPorts) {
        addresslist.add(new ServerAddress(hostPort));
    }

    mongo = new Mongo(addresslist, getMongoOptions(poolConfig));
    // mongo.setReadPreference(ReadPreference.SECONDARY);

    startIdleConnCheck();
}
项目:navi    文件:NaviMongoListDriver.java   
public Mongo getMongo() {
      if (isClose()) {
          throw new NaviSystemException("the driver has been closed!",
              NaviError.SYSERROR);
      }
      /*
      try {
    log.info("get mongo is open:" + mongo.getConnector().isOpen());
    // int count = mongo.getConnector().getDBPortPool(new
    // ServerAddress(server.getHost(), server.getPort())).available();
    // log.info("get mongo available:" + count);
    log.info("getConnectPoint:"
            + mongo.getConnector().getConnectPoint());
} catch (Exception e) {
    // TODO Auto-generated catch block
    // UnknownHostException
    e.printStackTrace();
}
*/
      return mongo;
  }
项目:cas-5.1.0    文件:MongoDbCloudConfigBootstrapConfiguration.java   
@Override
public Mongo mongo() throws Exception {
    final MongoCredential credential = MongoCredential.createCredential(
            mongoClientUri().getUsername(),
            getDatabaseName(),
            mongoClientUri().getPassword());

    final String hostUri = mongoClientUri().getHosts().get(0);
    final String[] host = hostUri.split(":");
    return new MongoClient(new ServerAddress(
            host[0], host.length > 1 ? Integer.parseInt(host[1]) : DEFAULT_PORT),
            Collections.singletonList(credential),
            mongoClientOptions());
}
项目:cas-5.1.0    文件:Beans.java   
/**
 * New mongo db client.
 *
 * @param mongo the mongo
 * @return the mongo
 */
public static Mongo newMongoDbClient(final AbstractMongoInstanceProperties mongo) {
    return new MongoClient(new ServerAddress(
            mongo.getHost(),
            mongo.getPort()),
            Collections.singletonList(
                    MongoCredential.createCredential(
                            mongo.getUserId(),
                            mongo.getDatabaseName(),
                            mongo.getPassword().toCharArray())),
            newMongoDbClientOptions(mongo));
}
项目:happy-news    文件:TestConfig.java   
@Override
@Bean(destroyMethod = "close")
public Mongo mongo() throws Exception {
    return new EmbeddedMongoBuilder()
        .version("3.4.2")
        .build();
}
项目:happy-news    文件:TwitterCrawlerTest.java   
/**
 * @return A new in memory MongoDB.
 */
@Bean(destroyMethod = "close")
public static Mongo mongo() throws IOException {
    return new EmbeddedMongoBuilder()
        .version("2.4.5")
        .bindIp("127.0.0.1")
        .port(12345)
        .build();
}
项目:lodsve-framework    文件:DynamicMongoConnection.java   
private Mongo getMongo(MongoClientURI mongoURI) {
    try {
        Mongo mongo = new MongoClient(mongoURI);
        activityMongos.add(mongo);

        return mongo;
    } catch (UnknownHostException e) {
        throw new CannotGetMongoDbConnectionException(String.format("con't get mongo '%s' connection!", mongoURI.getHosts()));
    }
}
项目:lodsve-framework    文件:DynamicMongoConnection.java   
@Override
public void destroy() throws Exception {
    if (!CollectionUtils.isEmpty(activityMongos)) {
        for (Mongo mongo : activityMongos) {
            mongo.close();
        }
    }
}
项目:cityoffice    文件:DevelopmentConfiguration.java   
@SuppressWarnings("deprecation")
@Override
public Mongo mongo() {
    try {
        return new Mongo("mongodb://localhost/cityoffice");
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}
项目:cityoffice    文件:RealDatabaseTestConfiguration.java   
@Override
public Mongo mongo() throws Exception {
    /**
     *
     * this is for a single db
     */

    return new MongoClient();
}
项目:ssoidh    文件:ITMongoConfiguration.java   
@Override
public
@Bean
Mongo mongo() {
  // uses fongo for in-memory tests
  return new Fongo("integration-test").getMongo();
}
项目:fiware-openlpwa-iotagent    文件:MongoConfiguration.java   
@Override
@Bean
public Mongo mongo() throws Exception {
    if (username != null && password != null && username.length() > 0) {
        ServerAddress address = new ServerAddress(mongoHost, mongoPort);
        MongoCredential credential = MongoCredential.createCredential(username, mongoDatabasename, password.toCharArray());
        List<MongoCredential> credentials = new ArrayList<>();
        credentials.add(credential);
        return new MongoClient(address, credentials);
    }
    return new MongoClient(mongoHost, mongoPort);
}
项目:kanbanboard    文件:SpringMongoConfig.java   
@Override
public Mongo mongo() throws Exception {
    if(!authenticate) {
        //Allows testing with a database without users and authentication configured.
        //should not be used in production.
        log.warn("MongoDB is accessed without any authentication. " +
                "This is strongly discouraged and should only be used in a testing environment.");
        return new MongoClient(hostname);
    } else {
        List<MongoCredential> cred = new LinkedList<>();
        cred.add(MongoCredential.createCredential(dbUserName, dbAuthDB, dbPasswd.toCharArray()));
        ServerAddress addr = new ServerAddress(hostname, dbPort);
        return new MongoClient(addr, cred);
    }
}
项目:konker-platform    文件:MongoConfig.java   
@Override
public Mongo mongo() throws Exception {
    if (!StringUtils.isEmpty(getUsername()) && !StringUtils.isEmpty(getPassword())) {
        try {
            MongoCredential credential = MongoCredential.createCredential(getUsername(), getDatabaseName(), getPassword().toCharArray());
            return new MongoClient(hostname, Collections.singletonList(credential));
        } catch (Exception e) {
            return new MongoClient(hostname);
        }
    } else {
        return new MongoClient(hostname);
    }

}
项目:konker-platform    文件:MongoAuditConfig.java   
@Override
public Mongo mongo() throws Exception {
    if (!StringUtils.isEmpty(getUsername()) && !StringUtils.isEmpty(getPassword())) {
        try {
            MongoCredential credential = MongoCredential.createCredential(getUsername(), getDatabaseName(), getPassword().toCharArray());
            return new MongoClient(hostname, Collections.singletonList(credential));
        } catch (Exception e) {
            return new MongoClient(hostname);
        }
    } else {
        return new MongoClient(hostname);
    }

}
项目:konker-platform    文件:MongoBillingConfig.java   
@Override
public Mongo mongo() throws Exception {
    if (!StringUtils.isEmpty(getUsername()) && !StringUtils.isEmpty(getPassword())) {
        try {
            MongoCredential credential = MongoCredential.createCredential(getUsername(), getDatabaseName(), getPassword().toCharArray());
            return new MongoClient(hostname, Collections.singletonList(credential));
        } catch (Exception e) {
            return new MongoClient(hostname);
        }
    } else {
        return new MongoClient(hostname);
    }

}
项目:PhET    文件:MongoLog.java   
public MongoLog( String sessionID, String dbName ) throws UnknownHostException {
    mongo = new Mongo( HOST_IP_ADDRESS, PORT );

    // All sessions are stored in the same DB.  Having a separate DB for
    // each uses an excessive amount of disk space.
    DB database = mongo.getDB( dbName );

    // Authenticate.
    try {
        boolean auth = database.authenticate( "phetsimclient", ( MER + SimSharingManager.MONGO_PASSWORD + "" + ( 2 * 2 * 2 ) + "ss0O88723otbubaoue" ).toCharArray() );
        if ( !auth ) {
            new RuntimeException( "Authentication failed" ).printStackTrace();
        }
    }

    //A MongoException.Network indicates a failure to reach mongo for the authentication attempt, and hence there is probably no internet connection.  See #3304
    catch ( MongoException.Network exception ) {
        LOGGER.warning( "Failed to connect to mongo during authentication.  Perhaps there is no internet connection." );
    }

    //One collection per session, lets us easily iterate and add messages per session.
    collection = database.getCollection( sessionID );

    /*
     * Mongo logs entire stack traces when failure occur, which is incredibly annoying.
     * Turn off Mongo logging here by interrogating the LogManager.
     * Do this at the end of the constructor, so that Mongo loggers have been instantiated.
     */
    LOGGER.info( "turning off MongoDB loggers" );
    Enumeration<String> names = LogManager.getLogManager().getLoggerNames();
    while ( names.hasMoreElements() ) {
        String name = names.nextElement();
        if ( name.startsWith( "com.mongodb" ) ) {
            LogManager.getLogManager().getLogger( name ).setLevel( Level.OFF );
        }
    }
}
项目:PhET    文件:MongoLoadTesterReader.java   
public static void main( String[] args ) throws UnknownHostException {
    Mongo m = new Mongo( MongoLog.HOST_IP_ADDRESS, MongoLog.PORT );
    DB db = m.getDB( MongoLoadTester.LOAD_TESTING_DB_NAME );
    boolean authenticated = db.authenticate( MongoLoadTester.DB_USER_NAME,
                                             ( MongoLoadTester.MER + SimSharingManager.MONGO_PASSWORD + "" + ( 2 * 2 * 2 ) + "ss0O88723otbubaoue" ).toCharArray() );

    System.out.println( "authenticated = " + authenticated );
    if ( !authenticated ) {
        System.out.println( "Authentication failed, aborting test." );
        return;
    }
    DBCollection collection = db.getCollection( MongoLoadTester.DB_COLLECTION );
    long count = collection.getCount();
    System.out.println( "count = " + count );
}
项目:pimp    文件:MongoConfig.java   
@Override
public Mongo mongo() throws Exception {
    MongoClient mongoClient;
    if ("none".compareTo(dbUri) != 0) {
        MongoClientURI uri = new MongoClientURI(dbUri);
        mongoClient = new MongoClient(uri);
    } else {
        mongoClient = new MongoClient(dbHost, dbPort);
    }
    return mongoClient;
}
项目:Camel    文件:GridFsComponent.java   
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    if (db == null) {
        db = CamelContextHelper.mandatoryLookup(getCamelContext(), remaining, Mongo.class);
        LOG.debug("Resolved the connection with the name {} as {}", remaining, db);
    }

    GridFsEndpoint endpoint = new GridFsEndpoint(uri, this);
    parameters.put("mongoConnection", db);
    endpoint.setConnectionBean(remaining);
    endpoint.setMongoConnection(db);
    setProperties(endpoint, parameters);

    return endpoint;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:MongoDataAutoConfigurationTests.java   
@Test
public void customConversions() throws Exception {
    this.context = new AnnotationConfigApplicationContext();
    this.context.register(CustomConversionsConfig.class);
    this.context.register(PropertyPlaceholderAutoConfiguration.class,
            MongoAutoConfiguration.class, MongoDataAutoConfiguration.class);
    this.context.refresh();
    MongoTemplate template = this.context.getBean(MongoTemplate.class);
    assertThat(template.getConverter().getConversionService().canConvert(Mongo.class,
            Boolean.class)).isTrue();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:MongoRepositoriesAutoConfigurationTests.java   
@Test
public void testDefaultRepositoryConfiguration() throws Exception {
    prepareApplicationContext(TestConfiguration.class);

    assertThat(this.context.getBean(CityRepository.class)).isNotNull();
    Mongo mongo = this.context.getBean(Mongo.class);
    assertThat(mongo).isInstanceOf(MongoClient.class);
    MongoMappingContext mappingContext = this.context
            .getBean(MongoMappingContext.class);
    @SuppressWarnings("unchecked")
    Set<? extends Class<?>> entities = (Set<? extends Class<?>>) ReflectionTestUtils
            .getField(mappingContext, "initialEntitySet");
    assertThat(entities).hasSize(1);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:MongoRepositoriesAutoConfigurationTests.java   
@Test
public void testNoRepositoryConfiguration() throws Exception {
    prepareApplicationContext(EmptyConfiguration.class);

    Mongo mongo = this.context.getBean(Mongo.class);
    assertThat(mongo).isInstanceOf(MongoClient.class);
}
项目:finerleague    文件:InitialDataLoadingConfig.java   
/**
 * Init.
 *
 * @return the mongeez
 */
@Bean(initMethod = "process")
public Mongeez loadInitialData(final Mongo mongo) {
    logger.info("Initializing default data");
    final Mongeez mongeez = new Mongeez();
    mongeez.setMongo(mongo);
    mongeez.setDbName(databaseName);
    mongeez.setFile(new ClassPathResource(initialLoadingFile));
    return mongeez;
}
项目:finerleague    文件:MongoLocalConfig.java   
/**
 * Get mongeez runner mongeez runner.
 *
 * @return the mongeez runner
 */
@Override
@Bean
public Mongo mongo() throws Exception {
    super.getLogger().info("MongeezRunner Running");
    return new EmbeddedMongoBuilder()
            .version(this.getDabaseVersion())
            .bindIp(super.getDabaseURI())
            .port(super.getDabasePort())
            .build();
}
项目:finerleague    文件:MongoTestConfig.java   
@Override
@Bean
public Mongo mongo() throws Exception {
    return new EmbeddedMongoBuilder()
            .version(DB_VERSION)
            .bindIp(DB_URI)
            .port(DB_PORT)
            .build();
}
项目:finerleague    文件:MongoTestConfig.java   
/**
 * Load initial data mongeez.
 *
 * @param mongo the mongo
 * @return the mongeez
 */
@Bean(initMethod = "process")
public Mongeez loadInitialData(final Mongo mongo) {
    final Mongeez mongeez = new Mongeez();
    mongeez.setMongo(mongo);
    mongeez.setDbName(FinerLeagueTestConstants.DB_NAME);
    mongeez.setFile(new ClassPathResource("db/mongeez_test.xml"));
    mongeez.process();
    return mongeez;
}
项目:beam    文件:MongoDbGridFSIO.java   
@Override
public List<? extends BoundedSource<ObjectId>> split(
    long desiredBundleSizeBytes, PipelineOptions options) throws Exception {
  Mongo mongo = spec.connectionConfiguration().setupMongo();
  try {
    GridFS gridfs = spec.connectionConfiguration().setupGridFS(mongo);
    DBCursor cursor = createCursor(gridfs);
    long size = 0;
    List<BoundedGridFSSource> list = new ArrayList<>();
    List<ObjectId> objects = new ArrayList<>();
    while (cursor.hasNext()) {
      GridFSDBFile file = (GridFSDBFile) cursor.next();
      long len = file.getLength();
      if ((size + len) > desiredBundleSizeBytes && !objects.isEmpty()) {
        list.add(new BoundedGridFSSource(spec, objects));
        size = 0;
        objects = new ArrayList<>();
      }
      objects.add((ObjectId) file.getId());
      size += len;
    }
    if (!objects.isEmpty() || list.isEmpty()) {
      list.add(new BoundedGridFSSource(spec, objects));
    }
    return list;
  } finally {
    mongo.close();
  }
}
项目:Wiab.pro    文件:MongoDbProvider.java   
/**
 * Return the {@link Mongo} instance that we are managing.
 */
private Mongo getMongo() {
  if (!isRunning) {
    start();
  }
  return mongo;
}
项目:navi    文件:NaviMongoDbFactory.java   
public DB getDb(String dbName) throws DataAccessException {
    Assert.hasText(dbName, "Database name must not be empty.");

    DefaultNaviDataSource defaultDataSource = (DefaultNaviDataSource) dataSource;

    //NaviMongoDriver driver = (NaviMongoDriver) defaultDataSource.getHandle();
    Mongo mongo = (Mongo) defaultDataSource.getHandle().getDriver();
    //DB db = MongoDbUtils.getDB(mongo, dbName, null, null);
    DB db = mongo.getDB(databaseNm);
    if (writeConcern != null) {
        db.setWriteConcern(writeConcern);
    }

    return db;
}
项目:navi    文件:NaviMongoDriver.java   
public NaviMongoDriver(ServerUrlUtil.ServerUrl server, String auth, NaviPoolConfig poolConfig) throws NumberFormatException, MongoException, UnknownHostException {
    super(server, auth, poolConfig);
    this.mongo = new Mongo(
        new ServerAddress(server.getHost(), server.getPort()), getMongoOptions(poolConfig)
    );

    startIdleConnCheck();
}
项目:navi    文件:NaviMongoDriver.java   
public Mongo getMongo() {
    if (isClose()) {
        throw new NaviSystemException("the driver has been closed!",
            NaviError.SYSERROR);
    }

    return mongo;
}
项目:spring-boot-concourse    文件:MongoAutoConfigurationTests.java   
@SuppressWarnings("deprecation")
@Test
public void optionsAdded() {
    this.context = new AnnotationConfigApplicationContext();
    EnvironmentTestUtils.addEnvironment(this.context,
            "spring.data.mongodb.host:localhost");
    this.context.register(OptionsConfig.class,
            PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class);
    this.context.refresh();
    assertThat(this.context.getBean(Mongo.class).getMongoOptions().getSocketTimeout())
            .isEqualTo(300);
}
项目:spring-boot-concourse    文件:MongoAutoConfigurationTests.java   
@SuppressWarnings("deprecation")
@Test
public void optionsAddedButNoHost() {
    this.context = new AnnotationConfigApplicationContext();
    EnvironmentTestUtils.addEnvironment(this.context,
            "spring.data.mongodb.uri:mongodb://localhost/test");
    this.context.register(OptionsConfig.class,
            PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class);
    this.context.refresh();
    assertThat(this.context.getBean(Mongo.class).getMongoOptions().getSocketTimeout())
            .isEqualTo(300);
}
项目:spring-boot-concourse    文件:MongoDataAutoConfigurationTests.java   
@Test
public void customConversions() throws Exception {
    this.context = new AnnotationConfigApplicationContext();
    this.context.register(CustomConversionsConfig.class);
    this.context.register(PropertyPlaceholderAutoConfiguration.class,
            MongoAutoConfiguration.class, MongoDataAutoConfiguration.class);
    this.context.refresh();
    MongoTemplate template = this.context.getBean(MongoTemplate.class);
    assertThat(template.getConverter().getConversionService().canConvert(Mongo.class,
            Boolean.class)).isTrue();
}
项目:spring-boot-concourse    文件:MongoRepositoriesAutoConfigurationTests.java   
@Test
public void testNoRepositoryConfiguration() throws Exception {
    prepareApplicationContext(EmptyConfiguration.class);

    Mongo mongo = this.context.getBean(Mongo.class);
    assertThat(mongo).isInstanceOf(MongoClient.class);
}
项目:Elko    文件:MongoObjectStore.java   
/**
 * Do the initialization required to begin providing object store
 * services.
 *
 * <p>The property <tt>"<i>propRoot</i>.odb.mongo.hostport"</tt> should
 * specify the address of the MongoDB server holding the objects.
 *
 * <p>The optional property <tt>"<i>propRoot</i>.odb.mongo.dbname"</tt>
 * allows the Mongo database name to be specified.  If omitted, this
 * defaults to <tt>"elko"</tt>.
 *
 * <p>The optional property <tt>"<i>propRoot</i>.odb.mongo.collname"</tt>
 * allows the collection containing the object repository to be specified.
 * If omitted, this defaults to <tt>"odb"</tt>.
 *
 * @param props  Properties describing configuration information.
 * @param propRoot  Prefix string for selecting relevant properties.
 * @param appTrace  Trace object for use in logging.
 */
public void initialize(BootProperties props, String propRoot,
                       Trace appTrace)
{
    tr = appTrace;
    propRoot = propRoot + ".odb.mongo";

    String addressStr = props.getProperty(propRoot + ".hostport");
    if (addressStr == null) {
        tr.fatalError("no mongo database server address specified");
    }
    int colon = addressStr.indexOf(':');
    int port;
    String host;
    if (colon < 0) {
        port = 27017;
        host = addressStr;
    } else {
        port = Integer.parseInt(addressStr.substring(colon + 1)) ;
        host = addressStr.substring(0, colon);
    }
    //try {
        myMongo = new Mongo(host, port);
    //} catch (UnknownHostException e) {
    //    tr.fatalError("mongodb server " + addressStr + ": unknown host");
    //}
    String dbName = props.getProperty(propRoot + ".dbname", "elko");
    myDB = myMongo.getDB(dbName);

    String collName = props.getProperty(propRoot + ".collname", "odb");
    myODBCollection = myDB.getCollection(collName);
}
项目:forweaver2.0    文件:MongoDBConfig.java   
public @Bean MongoDbFactory mongoDbFactory() throws Exception {
return new SimpleMongoDbFactory(new Mongo("localhost", 27017), "forweaver");
 }
项目:Facegram    文件:MongoConfig.java   
@Override
public Mongo mongo() throws Exception {
    return  new MongoClient(HOST, PORT);
}