java类com.mongodb.Mongo的实例源码

MongoDbGridFSIO.java 文件源码 项目:beam 阅读 25 收藏 0 点赞 0 评论 0
@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();
  }
}
NaviMongoListDriver.java 文件源码 项目:navi 阅读 30 收藏 0 点赞 0 评论 0
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();
}
NaviMongoListDriver.java 文件源码 项目:navi 阅读 35 收藏 0 点赞 0 评论 0
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;
  }
MongoDbCloudConfigBootstrapConfiguration.java 文件源码 项目:cas-5.1.0 阅读 26 收藏 0 点赞 0 评论 0
@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());
}
Beans.java 文件源码 项目:cas-5.1.0 阅读 31 收藏 0 点赞 0 评论 0
/**
 * 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));
}
TestConfig.java 文件源码 项目:happy-news 阅读 28 收藏 0 点赞 0 评论 0
@Override
@Bean(destroyMethod = "close")
public Mongo mongo() throws Exception {
    return new EmbeddedMongoBuilder()
        .version("3.4.2")
        .build();
}
TwitterCrawlerTest.java 文件源码 项目:happy-news 阅读 32 收藏 0 点赞 0 评论 0
/**
 * @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();
}
DynamicMongoConnection.java 文件源码 项目:lodsve-framework 阅读 36 收藏 0 点赞 0 评论 0
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()));
    }
}
DynamicMongoConnection.java 文件源码 项目:lodsve-framework 阅读 39 收藏 0 点赞 0 评论 0
@Override
public void destroy() throws Exception {
    if (!CollectionUtils.isEmpty(activityMongos)) {
        for (Mongo mongo : activityMongos) {
            mongo.close();
        }
    }
}
DevelopmentConfiguration.java 文件源码 项目:cityoffice 阅读 32 收藏 0 点赞 0 评论 0
@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;
}
RealDatabaseTestConfiguration.java 文件源码 项目:cityoffice 阅读 28 收藏 0 点赞 0 评论 0
@Override
public Mongo mongo() throws Exception {
    /**
     *
     * this is for a single db
     */

    return new MongoClient();
}
ITMongoConfiguration.java 文件源码 项目:ssoidh 阅读 27 收藏 0 点赞 0 评论 0
@Override
public
@Bean
Mongo mongo() {
  // uses fongo for in-memory tests
  return new Fongo("integration-test").getMongo();
}
MongoConfiguration.java 文件源码 项目:fiware-openlpwa-iotagent 阅读 29 收藏 0 点赞 0 评论 0
@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);
}
SpringMongoConfig.java 文件源码 项目:kanbanboard 阅读 31 收藏 0 点赞 0 评论 0
@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);
    }
}
MongoConfig.java 文件源码 项目:konker-platform 阅读 35 收藏 0 点赞 0 评论 0
@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);
    }

}
MongoAuditConfig.java 文件源码 项目:konker-platform 阅读 24 收藏 0 点赞 0 评论 0
@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);
    }

}
MongoBillingConfig.java 文件源码 项目:konker-platform 阅读 29 收藏 0 点赞 0 评论 0
@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);
    }

}
MongoLog.java 文件源码 项目:PhET 阅读 26 收藏 0 点赞 0 评论 0
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 );
        }
    }
}
MongoLoadTesterReader.java 文件源码 项目:PhET 阅读 27 收藏 0 点赞 0 评论 0
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 );
}
MongoConfig.java 文件源码 项目:pimp 阅读 34 收藏 0 点赞 0 评论 0
@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;
}
GridFsComponent.java 文件源码 项目:Camel 阅读 46 收藏 0 点赞 0 评论 0
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;
}
MongoDataAutoConfigurationTests.java 文件源码 项目:https-github.com-g0t4-jenkins2-course-spring-boot 阅读 32 收藏 0 点赞 0 评论 0
@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();
}
MongoRepositoriesAutoConfigurationTests.java 文件源码 项目:https-github.com-g0t4-jenkins2-course-spring-boot 阅读 37 收藏 0 点赞 0 评论 0
@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);
}
MongoRepositoriesAutoConfigurationTests.java 文件源码 项目:https-github.com-g0t4-jenkins2-course-spring-boot 阅读 38 收藏 0 点赞 0 评论 0
@Test
public void testNoRepositoryConfiguration() throws Exception {
    prepareApplicationContext(EmptyConfiguration.class);

    Mongo mongo = this.context.getBean(Mongo.class);
    assertThat(mongo).isInstanceOf(MongoClient.class);
}
InitialDataLoadingConfig.java 文件源码 项目:finerleague 阅读 35 收藏 0 点赞 0 评论 0
/**
 * 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;
}
MongoLocalConfig.java 文件源码 项目:finerleague 阅读 39 收藏 0 点赞 0 评论 0
/**
 * 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();
}
MongoTestConfig.java 文件源码 项目:finerleague 阅读 31 收藏 0 点赞 0 评论 0
@Override
@Bean
public Mongo mongo() throws Exception {
    return new EmbeddedMongoBuilder()
            .version(DB_VERSION)
            .bindIp(DB_URI)
            .port(DB_PORT)
            .build();
}
MongoTestConfig.java 文件源码 项目:finerleague 阅读 28 收藏 0 点赞 0 评论 0
/**
 * 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;
}
MongoDbGridFSIO.java 文件源码 项目:beam 阅读 27 收藏 0 点赞 0 评论 0
@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();
  }
}
MongoDbProvider.java 文件源码 项目:Wiab.pro 阅读 29 收藏 0 点赞 0 评论 0
/**
 * Return the {@link Mongo} instance that we are managing.
 */
private Mongo getMongo() {
  if (!isRunning) {
    start();
  }
  return mongo;
}


问题


面经


文章

微信
公众号

扫码关注公众号