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

MongoDriver.java 文件源码 项目:mycat-src-1.6.1-RELEASE 阅读 27 收藏 0 点赞 0 评论 0
@Override
public Connection connect(String url, Properties info) throws SQLException {
    MongoClientURI mcu = null;
    if ((mcu = parseURL(url, info)) == null) {
        return null;
    }

    MongoConnection result = null;
    //System.out.print(info);
    try{
        result = new MongoConnection(mcu, url);
    }catch (Exception e){
        throw new SQLException("Unexpected exception: " + e.getMessage(), e);
    }

    return result;
}
MongoDriver.java 文件源码 项目:mycat-src-1.6.1-RELEASE 阅读 24 收藏 0 点赞 0 评论 0
private MongoClientURI parseURL(String url, Properties defaults) {
    if (url == null) {
        return null;
    }

    if (!StringUtils.startsWithIgnoreCase(url, PREFIX)) {   
        return null;
    }

    //删掉开头的 jdbc:
    //url = url.replace(URL_JDBC, "");

    try {
        //FIXME 判断defaults中的参数,写入URL中?
        return new MongoClientURI(url);
    } catch (Exception e) {
        LOGGER.error("parseURLError",e);
        return null;
    }

}
MongoConnection.java 文件源码 项目:MongoSyphon 阅读 30 收藏 0 点赞 0 评论 0
public void Connect(String user, String pass) {
    try {
        logger.info("Connecting to " + connectionString);

        // Authaenticate
        // MongoCredential credential =
        // MongoCredential.createCredential(user,
        // "admin",
        // pass); //Only users on admin as that will be mandatory in 3.6

        mongoClient = new MongoClient(new MongoClientURI(connectionString));

        mongoClient.getDatabase("admin")
                .runCommand(new Document("ping", 1));

    } catch (Exception e) {
        logger.error("Unable to connect to MongoDB");
        logger.error(e.getMessage());
        System.exit(1);
    }
    this.user = user;
    this.pass = pass;
}
BingoChessChallenge.java 文件源码 项目:BingoChess 阅读 29 收藏 0 点赞 0 评论 0
public BingoChessChallenge(String[] args) {
    announcer = new Chatter(args[0]);
    lichs = new HashMap<String,Lichesser>();
    chessplayers = new HashMap<String,ChessPlayer>();
    chessgames = new HashMap<String,LichessGame>();
    BingoPlayer.SQUARE_BAG = new Vector<Dimension>();
    for (int x=0;x<8;x++)
    for (int y=0;y<8;y++)
    BingoPlayer.SQUARE_BAG.add(new Dimension(x,y));
    initIRC(args[0], args[1], args[2], args[3]);
    loadAdmins("res/admins.txt");
    serv = new BingoServ(Integer.parseInt(args[4]),this);
    serv.startSrv();
    bingoURL = args[5];
    MongoClientURI connStr = new MongoClientURI("mongodb://bingobot:" + args[6] + "@localhost:27017/BingoBase");
    MongoClient mongoClient = new MongoClient(connStr);
    MongoDatabase bingoBase = mongoClient.getDatabase("BingoBase");
    playData = bingoBase.getCollection("players");
}
BingoChess.java 文件源码 项目:BingoChess 阅读 30 收藏 0 点赞 0 评论 0
public BingoChess(String[] args) {
    tv_client = new GameClient();
    twits = new HashMap<String,Chatter>();
    bingoers = new HashMap<String,BingoPlayer>();
    BingoPlayer.SQUARE_BAG = new Vector<Dimension>();
    for (int x=0;x<8;x++)
    for (int y=0;y<8;y++)
    BingoPlayer.SQUARE_BAG.add(new Dimension(x,y));
    initIRC(args[0], args[1], args[2], args[3]);
    loadAdmins("res/admins.txt");
    serv = new BingoServ(Integer.parseInt(args[4]),this);
    serv.startSrv();
    bingoURL = args[5];
    followTVGame();
    MongoClientURI connStr = new MongoClientURI("mongodb://bingobot:" + args[6] + "@localhost:27017/BingoBase");
    mongoClient = new MongoClient(connStr);
    bingoBase = mongoClient.getDatabase("BingoBase");
    playData = bingoBase.getCollection("players");
}
BingoChessChallenge.java 文件源码 项目:BingoChess 阅读 32 收藏 0 点赞 0 评论 0
public BingoChessChallenge(String[] args) {
    announcer = new Chatter(args[0]);
    lichs = new HashMap<String,Lichesser>();
    chessplayers = new HashMap<String,ChessPlayer>();
    chessgames = new HashMap<String,LichessGame>();
    BingoPlayer.SQUARE_BAG = new Vector<Dimension>();
    for (int x=0;x<8;x++)
    for (int y=0;y<8;y++)
    BingoPlayer.SQUARE_BAG.add(new Dimension(x,y));
    initIRC(args[0], args[1], args[2], args[3]);
    loadAdmins("res/admins.txt");
    serv = new BingoServ(Integer.parseInt(args[4]),this);
    serv.startSrv();
    bingoURL = args[5];
    MongoClientURI connStr = new MongoClientURI("mongodb://bingobot:" + args[6] + "@localhost:27017/BingoBase");
    MongoClient mongoClient = new MongoClient(connStr);
    MongoDatabase bingoBase = mongoClient.getDatabase("BingoBase");
    playData = bingoBase.getCollection("players");
}
MongoImpl.java 文件源码 项目:tephra 阅读 22 收藏 0 点赞 0 评论 0
@Override
public void create(JSONObject config) {
    String key = config.getString("key");
    if (mongos.containsKey(key))
        return;

    String schema = config.getString("schema");
    if (validator.isEmpty(schema))
        throw new NullPointerException("未设置schema值[" + config + "]!");

    JSONArray array = config.getJSONArray("ips");
    if (array == null || array.size() == 0)
        throw new NullPointerException("未设置ips值[" + config + "]!");

    String username = config.getString("username");
    String password = config.getString("password");
    MongoClientOptions.Builder builder = MongoClientOptions.builder().connectionsPerHost(maxActive).maxWaitTime(maxWait);
    List<MongoClient> list = new ArrayList<>();
    for (int i = 0; i < array.size(); i++)
        list.add(new MongoClient(new MongoClientURI("mongodb://" + username + ":" + password + "@" + array.getString(i) + "/" + schema, builder)));
    schemas.put(key, schema);
    mongos.put(key, list);

    if (logger.isDebugEnable())
        logger.debug("Mongo数据库[{}]初始化完成。", config);
}
MongoDBConnectionTest.java 文件源码 项目:MCS-Master 阅读 28 收藏 0 点赞 0 评论 0
public static boolean connectionTest(MongoDBConfig mongoDBConfig) {
    Logging.disableMongoDBLogging();
    boolean success = true;
    MongoClient mongoClient = null;
    try {
        mongoClient = new MongoClient(new MongoClientURI("mongodb://" + mongoDBConfig.getIp() + ":" + mongoDBConfig.getPort()));
        mongoClient.getDatabaseNames();
    } catch (MongoException e) {
        success = false;
    } finally {
        if (mongoClient != null) {
            mongoClient.close();
        }
        Logging.enableMongoDBLogging();
    }
    return success;
}
DynamicMongoConnection.java 文件源码 项目:lodsve-framework 阅读 32 收藏 0 点赞 0 评论 0
/**
 * 指定使用的mongouri key
 *
 * @return key
 */
private MongoClientURI determineTargetDataSource() {
    String currentKey = MongoDataSourceHolder.get();
    MongoClientURI mongoURI;

    mongoURI = mongoURIs.get(currentKey);

    if (null == mongoURI) {
        mongoURI = defaultMongoURI;
    }

    if (null == mongoURI) {
        throw new CannotGetMongoDbConnectionException(String.format("determine current lookup key '%s' not exist!", currentKey));
    }

    return mongoURI;
}
DBManager.java 文件源码 项目:Grimoire 阅读 72 收藏 0 点赞 0 评论 0
public DBManager(String host, int port, String dbname, String username, String password) {
    // Construct mongo url
    if (dbname == null || dbname.isEmpty()) dbname = "Grimoire";
    if (host == null || host.isEmpty()) host = "127.0.0.1";
    if (port <= 0 || port >= 65535) port = 27017;
    String mongoURL = host + ":" + port + "/" + dbname;
    if (username != null && !username.isEmpty()) {
        String auth = username;
        if (password != null && !password.isEmpty()) auth += ":" + password;
        mongoURL = auth + "@" + mongoURL;
    }
    mongoURL = "mongodb://" + mongoURL;

    // Construct client
    MongoClient client = new MongoClient(new MongoClientURI(mongoURL));

    // Wrap with jongo
    jongo = new Jongo(client.getDB(dbname));
}
LocalTestSetup.java 文件源码 项目:Rapture 阅读 23 收藏 0 点赞 0 评论 0
public static void createUser() throws IOException, InterruptedException {
    String mongoHost = MultiValueConfigLoader.getConfig("MONGODB-integrationTest");
    log.info("Host is " + mongoHost);
    if (mongoHost != null) {
        MongoClientURI uri = new MongoClientURI(mongoHost);
        List<String> hosts = uri.getHosts();
        for (String host : hosts) {
            String[] cmdarray = createSetupCommand(host, uri.getDatabase(), uri.getUsername(), new String(uri.getPassword()));
            Process process = Runtime.getRuntime().exec(cmdarray);
            int retVal = process.waitFor();
            log.info(String.format("retVal=%s", retVal));
            log.info("output is " + IOUtils.toString(process.getInputStream()));
            if (retVal != 0) {
                log.info("error is " + IOUtils.toString(process.getErrorStream()));
            }
        }
    } else {
        log.error("mongo host is not defined!");
    }
}
MongoDBConnection.java 文件源码 项目:nationalparks 阅读 32 收藏 0 点赞 0 评论 0
@PostConstruct
public void initConnection() {
    String mongoHost = env.getProperty("mongodb.server.host", "127.0.0.1"); // env var MONGODB_SERVER_HOST takes precedence
    String mongoPort = env.getProperty("mongodb.server.port", "27017"); // env var MONGODB_SERVER_PORT takes precedence
    String mongoUser = env.getProperty("mongodb.user", "mongodb"); // env var MONGODB_USER takes precedence
    String mongoPassword = env.getProperty("mongodb.password", "mongodb"); // env var MONGODB_PASSWORD takes precedence
    String mongoDBName = env.getProperty("mongodb.database", "mongodb"); // env var MONGODB_DATABASE takes precedence

    try {
        String mongoURI = "mongodb://" + mongoUser + ":" + mongoPassword + "@" + mongoHost + ":" + mongoPort + "/" + mongoDBName;
        System.out.println("[INFO] Connection string: " + mongoURI);
        MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoURI));
        mongoDB = mongoClient.getDatabase(mongoDBName);
    } catch (Exception e) {
        System.out.println("[ERROR] Creating the mongoDB. " + e.getMessage());
        mongoDB = null;
    }
}
ProfileActivity.java 文件源码 项目:medical-data-android 阅读 40 收藏 0 点赞 0 评论 0
@Override
protected Integer doInBackground(User... params) {
    try {
        MongoClientURI mongoClientURI = new MongoClientURI(Variables.mongo_uri);
        MongoClient mongoClient = new MongoClient(mongoClientURI);
        MongoDatabase dbMongo = mongoClient.getDatabase(mongoClientURI.getDatabase());
        MongoCollection<Document> coll = dbMongo.getCollection("users");
        User local_user = params[0];
        if (!local_user.getEmail().equals(original_email)) {
            Document user = coll.find(eq("email", local_user.getEmail())).first();
            if (user != null) {
                return 1; // Repeated email
            }
        }

        Document search = new Document("_id", new ObjectId(local_user.getId()));
        Document replacement = new Document("$set", local_user.getRegisterDocument());
        // We update some fields of the documents without affecting the rest
        coll.updateOne(search, replacement);
        mongoClient.close();
        return 0; //Successfully saved
    } catch (Exception e) {
        return 2; // Error
    }
}
MainActivity.java 文件源码 项目:medical-data-android 阅读 36 收藏 0 点赞 0 评论 0
@Override
protected Integer doInBackground(User... params) {
    try {
        MongoClientURI mongoClientURI = new MongoClientURI(Variables.mongo_uri);
        MongoClient mongoClient = new MongoClient(mongoClientURI);
        MongoDatabase dbMongo = mongoClient.getDatabase(mongoClientURI.getDatabase());
        MongoCollection<Document> coll = dbMongo.getCollection("users");
        User local_user = params[0];
        Document user = coll.find(eq("email", local_user.getEmail())).first();
        mongoClient.close();
        if (user == null || !(user.get("pin").equals(local_user.getPin()))) {
            return 1; // Wrong data
        }
        Date d = (Date) user.get("birthDate");
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        // WARNING: Calendar.MONTH starts in 0 Calendar.DAY_OF_MONTH starts in 1
        local_user.completeSignIn((String) user.get("name"), cal.get(Calendar.DAY_OF_MONTH) - 1, cal.get(Calendar.MONTH), cal.get(Calendar.YEAR), (Boolean) user.get("gender"), user.getObjectId("_id").toString());
        return 0; //Successfully saved
    } catch (Exception e) {
        return 2; // Error
    }
}
RegisterActivity.java 文件源码 项目:medical-data-android 阅读 30 收藏 0 点赞 0 评论 0
@Override
protected Integer doInBackground(User... params) {
    try {
        MongoClientURI mongoClientURI = new MongoClientURI(Variables.mongo_uri);
        MongoClient mongoClient = new MongoClient(mongoClientURI);
        MongoDatabase dbMongo = mongoClient.getDatabase(mongoClientURI.getDatabase());
        MongoCollection<Document> coll = dbMongo.getCollection("users");
        User local_user = params[0];
        if (coll.find(eq("email", local_user.getEmail())).first() != null) {
            mongoClient.close();
            return 1; // Repeated email
        }
        Document document = local_user.getRegisterDocument();
        coll.insertOne(document);
        local_user.setId(document.getObjectId("_id").toString());
        mongoClient.close();
        return 0; //Successfully saved
    } catch (Exception e) {
        return 2; // Error
    }
}
MongoDatabaseConnection.java 文件源码 项目:geeCommerce-Java-Shop-Software-and-PIM 阅读 23 收藏 0 点赞 0 评论 0
@SuppressWarnings("deprecation")
    @Override
    public void init(String configurationName, Map<String, String> properties) {
        if (mongoClient == null) {
            this.configurationName = configurationName;
            this.properties = new HashMap<>(properties);

            try {
                String mongoClientURI = "mongodb://" + property("user") + ":" + property("pass") + "@" + property("host") + ":" + property("port") + "/" + property("name") + "?authSource=admin";

                MongoClientURI uri = new MongoClientURI(mongoClientURI);
                mongoClient = new MongoClient(uri);                


//                MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(100).autoConnectRetry(true)
//                    .connectTimeout(30000).socketTimeout(60000).socketKeepAlive(true).build();
//                mongoClient = new MongoClient(new ServerAddress(property("host"), Integer.parseInt(property("port"))),
//                    options);
            } catch (Throwable t) {
                throw new IllegalStateException(t);
            }
        }
    }
TestServerManager.java 文件源码 项目:EventStreamAnalytics 阅读 24 收藏 0 点赞 0 评论 0
private void startMangoDb() throws InterruptedException {
    startInNewThread(() -> {
        try {
            MongodStarter starter = MongodStarter.getDefaultInstance();
            IMongodConfig mongodConfig = new MongodConfigBuilder()
                    .version(Version.Main.PRODUCTION)
                    .net(new Net(12345, Network.localhostIsIPv6()))
                    .pidFile(new File("target/process.pid").getAbsolutePath())
                    .replication(new Storage(new File("target/tmp/mongodb/").getAbsolutePath(), null, 0))
                    .build();
            logger.debug("Would download MongoDB if not yet downloaded.");
            MongodExecutable mongodExecutable = starter.prepare(mongodConfig);
            logger.debug("Done with downloading MongoDB exec.");
            mongodExecutable.start();

            MongoClientURI uri = new MongoClientURI("mongodb://localhost:12345/eventStreamAnalytics");
            MongoClient client = new MongoClient(uri);
            MongoDatabase mongoDatabase = client.getDatabase(uri.getDatabase());
            mongoDatabase.createCollection("events");
        } catch (Exception ex) {
            logger.error("Failed to start MongoDB", ex);
            throw new RuntimeException(ex);
        }
    }, "MangoDB").join();
    logger.debug("Successfully Started MongoDB.");
}
MongoDbIO.java 文件源码 项目:beam 阅读 21 收藏 0 点赞 0 评论 0
@Override
public boolean start() {
  Read spec = source.spec;
  MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
  optionsBuilder.maxConnectionIdleTime(spec.maxConnectionIdleTime());
  optionsBuilder.socketKeepAlive(spec.keepAlive());
  client = new MongoClient(new MongoClientURI(spec.uri(), optionsBuilder));

  MongoDatabase mongoDatabase = client.getDatabase(spec.database());

  MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(spec.collection());

  if (spec.filter() == null) {
    cursor = mongoCollection.find().iterator();
  } else {
    Document bson = Document.parse(spec.filter());
    cursor = mongoCollection.find(bson).iterator();
  }

  return advance();
}
MongoDB.java 文件源码 项目:jlogstash-input-plugin 阅读 35 收藏 0 点赞 0 评论 0
@Override
public void prepare() {
    // 初始化增量的开始时间
    startTime = new StartTime(sinceTime, lastRunMetadataPath);

    // 获取用户自定义的筛选条件
    queryDocument = parseQueryDocument(query);

    // 获取是否需要转换Binary对象为byte[]
    if (binaryFields != null && binaryFields.size() > 0) {
        needConvertBin = true;
    }

    // 连接client
    mongoClient = new MongoClient(new MongoClientURI(uri));
    database = mongoClient.getDatabase(dbName);
    coll = database.getCollection(collection);
}
MongoDBTest.java 文件源码 项目:jlogstash-input-plugin 阅读 22 收藏 0 点赞 0 评论 0
@Override
public void prepare() {
    // 获取是否需要转换Binary
    if (bin_fields != null && bin_fields.size() > 0) {
        convertBin = true;
    }

    // 准备since_time
    prepareSinceTime();

    // 将filter查询语句转换为Document对象
    filterDocument = parseFilterDocument(filter);

    // 连接client
    mongoClient = new MongoClient(new MongoClientURI(uri));
    database = mongoClient.getDatabase(db_name);
    coll = database.getCollection(collection);
}
MorphiaPackageBundleTest.java 文件源码 项目:dropwizard-morphia 阅读 24 收藏 0 点赞 0 评论 0
@BeforeClass
public static void setUpAll() throws Exception {
    morphiaBundle = new MorphiaPackageBundle<DummyConfiguration>(DummyEntity.class.getPackage().getName(), false) {
        @Override
        protected MongoConfiguration getMongo(DummyConfiguration configuration) {
            UriMongoConfiguration mongoConfiguration = new UriMongoConfiguration();
            mongoConfiguration.setDbName("test");
            mongoConfiguration.setStoreEmpties(false);
            mongoConfiguration.setStoreNulls(false);
            mongoConfiguration.setIgnoreFinals(false);
            mongoConfiguration.setUseLowerCaseCollectionNames(false);
            mongoConfiguration.setUri(new MongoClientURI(String.format("mongodb://localhost:%d", port)));

            return mongoConfiguration;
        }
    };
}
MongoDataSourceAdapter.java 文件源码 项目:ymate-platform-v2 阅读 25 收藏 0 点赞 0 评论 0
public void initialize(IMongoClientOptionsHandler optionsHandler, MongoDataSourceCfgMeta cfgMeta) throws Exception {
    __cfgMeta = cfgMeta;
    MongoClientOptions.Builder _builder = null;
    if (optionsHandler != null) {
        _builder = optionsHandler.handler(cfgMeta.getName());
    }
    if (_builder == null) {
        _builder = MongoClientOptions.builder();
    }
    if (StringUtils.isNotBlank(cfgMeta.getConnectionUrl())) {
        __mongoClient = new MongoClient(new MongoClientURI(cfgMeta.getConnectionUrl(), _builder));
    } else {
        String _username = StringUtils.trimToNull(cfgMeta.getUserName());
        String _password = StringUtils.trimToNull(cfgMeta.getPassword());
        if (_username != null && _password != null) {
            if (__cfgMeta.isPasswordEncrypted() && __cfgMeta.getPasswordClass() != null) {
                _password = __cfgMeta.getPasswordClass().newInstance().decrypt(_password);
            }
            MongoCredential _credential = MongoCredential.createCredential(cfgMeta.getUserName(), cfgMeta.getDatabaseName(), _password == null ? null : _password.toCharArray());
            __mongoClient = new MongoClient(cfgMeta.getServers(), Collections.singletonList(_credential), _builder.build());
        } else {
            __mongoClient = new MongoClient(cfgMeta.getServers(), _builder.build());
        }
    }
}
MongoApplicationStructure.java 文件源码 项目:Kvantum 阅读 26 收藏 0 点赞 0 评论 0
MongoApplicationStructure(final String applicationName)
{
    super( applicationName );

    // Turn off the really annoying MongoDB spam :/
    {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger rootLogger = loggerContext.getLogger( "org.mongodb.driver" );
        rootLogger.setLevel( Level.OFF );
    }

    this.mongoClient = new MongoClient( new MongoClientURI( CoreConfig.MongoDB.uri ) );
    this.accountManager = createNewAccountManager();
    xyz.kvantum.server.api.logging.Logger.info( "Initialized MongoApplicationStructure: {}", this
            .applicationName );

    this.morphia = new Morphia();
    this.morphia.mapPackage( "com.github.intellectualsites.kvantum.implementation" );
    this.morphiaDatastore = morphia.createDatastore( this.mongoClient, CoreConfig.MongoDB.dbMorphia );
}
PersistenceManagerImpl.java 文件源码 项目:verbum-domini 阅读 32 收藏 0 点赞 0 评论 0
@Override
public void startUp() {
    Logger.getLogger("org.mongodb").setLevel(Level.SEVERE);
    Logger.getLogger("com.mongodb").setLevel(Level.SEVERE);

    AppConfiguration configuration = AppConfiguration.instance();
    this.databaseName = configuration.getProperty("database.name");
    if (this.databaseName == null) {
        throw new VerbumDominiException("Property database.name not found in app-configuration.properties file.");
    }

    String connectionUrl = configuration.getProperty("mongodb.connection.url");

    if (Environments.TEST.equals(configuration.getEnvironment())) {
        this.databaseName = "verbum_domini_test";
        connectionUrl = "mongodb://localhost";
    } else if (Environments.PRODUCTION.equals(configuration.getEnvironment())) {
        this.databaseName = System.getenv("MONGOLAB_DB_NAME");
        connectionUrl = System.getenv("MONGOLAB_URI");
    }

    MongoClientOptions.Builder options = this.buildOptions(configuration);
    MongoClientURI uri = new MongoClientURI(connectionUrl, options);

    this.mongoClient = new MongoClient(uri);
}
MongoDBPersistenceService.java 文件源码 项目:openhab-hdl 阅读 22 收藏 0 点赞 0 评论 0
/**
 * Connects to the database
 */
private void connectToDatabase() {
    try {
        logger.debug("Connect MongoDB");
        this.cl = new MongoClient(new MongoClientURI(this.url));
        mongoCollection = cl.getDB(this.db).getCollection(this.collection);

        BasicDBObject idx = new BasicDBObject();
        idx.append(FIELD_TIMESTAMP, 1).append(FIELD_ITEM, 1);
        this.mongoCollection.createIndex(idx);
        logger.debug("Connect MongoDB ... done");
    } catch (Exception e) {
        logger.error("Failed to connect to database {}", this.url);
        throw new RuntimeException("Cannot connect to database", e);
    }
}
MongoService.java 文件源码 项目:mongofx 阅读 26 收藏 0 点赞 0 评论 0
public MongoDbConnection connect(ConnectionSettings connectionSettings) {
  StringBuilder authString = new StringBuilder();

  String user = connectionSettings.getUser();
  if (user != null && !user.isEmpty()) {
    authString.append(user);
    String password = connectionSettings.getPassword();
    if (password != null && !password.isEmpty()) {
      authString.append(":").append(password);
    }
    authString.append("@");
  }
  String uri = String.format("mongodb://%s%s", authString, connectionSettings.getHost());
  Builder options = MongoClientOptions.builder().serverSelectionTimeout(10000);
  MongoClient client = new MongoClient(new MongoClientURI(uri, options));
  MongoConnection mongoConnection = new MongoConnection(client);
  return new MongoDbConnection(mongoConnection, connectionSettings);
}
MongodbInputPlugin.java 文件源码 项目:embulk-input-mongodb 阅读 30 收藏 0 点赞 0 评论 0
private MongoDatabase connect(final PluginTask task) throws UnknownHostException, MongoException
{
    MongoClient mongoClient;
    String database;

    if (!task.getUri().isPresent() && !task.getHosts().isPresent()) {
        throw new ConfigException("'uri' or 'hosts' is required");
    }

    if (task.getUri().isPresent()) {
        MongoClientURI uri = new MongoClientURI(task.getUri().get());
        database = uri.getDatabase();
        mongoClient = new MongoClient(uri);
    }
    else {
        mongoClient = createClientFromParams(task);
        database = task.getDatabase().get();
    }

    MongoDatabase db = mongoClient.getDatabase(database);
    // Get collection count for throw Exception
    db.getCollection(task.getCollection()).count();
    return db;
}
TestMongodbInputPlugin.java 文件源码 项目:embulk-input-mongodb 阅读 22 收藏 0 点赞 0 评论 0
@Test
public void testRunWithConnectionParams() throws Exception
{
    MongoClientURI uri = new MongoClientURI(MONGO_URI);
    String host = uri.getHosts().get(0);
    Integer port = (host.split(":")[1] != null) ? Integer.valueOf(host.split(":")[1]) : 27017;
    ConfigSource config = Exec.newConfigSource()
            .set("hosts", Arrays.asList(ImmutableMap.of("host", host.split(":")[0], "port", port)))
            .set("user", uri.getUsername())
            .set("password", uri.getPassword())
            .set("database", uri.getDatabase())
            .set("collection", MONGO_COLLECTION);
    PluginTask task = config.loadConfig(PluginTask.class);

    dropCollection(task, MONGO_COLLECTION);
    createCollection(task, MONGO_COLLECTION);
    insertDocument(task, createValidDocuments());

    plugin.transaction(config, new Control());
    assertValidRecords(getFieldSchema(), output);
}
TestServerManager.java 文件源码 项目:EventStreamAnalytics 阅读 33 收藏 0 点赞 0 评论 0
private void startMangoDb() throws InterruptedException {
    startInNewThread(() -> {
        try {
            MongodStarter starter = MongodStarter.getDefaultInstance();
            IMongodConfig mongodConfig = new MongodConfigBuilder()
                    .version(Version.Main.PRODUCTION)
                    .net(new Net(12345, Network.localhostIsIPv6()))
                    .pidFile(new File("target/process.pid").getAbsolutePath())
                    .replication(new Storage(new File("target/tmp/mongodb/").getAbsolutePath(), null, 0))
                    .build();
            logger.debug("Would download MongoDB if not yet downloaded.");
            MongodExecutable mongodExecutable = starter.prepare(mongodConfig);
            logger.debug("Done with downloading MongoDB exec.");
            mongodExecutable.start();

            MongoClientURI uri = new MongoClientURI("mongodb://localhost:12345/eventStreamAnalytics");
            MongoClient client = new MongoClient(uri);
            MongoDatabase mongoDatabase = client.getDatabase(uri.getDatabase());
            mongoDatabase.createCollection("events");
        } catch (Exception ex) {
            logger.error("Failed to start MongoDB", ex);
            throw new RuntimeException(ex);
        }
    }, "MangoDB").join();
    logger.debug("Successfully Started MongoDB.");
}
TestMultiTenantConfiguration.java 文件源码 项目:daikon 阅读 32 收藏 0 点赞 0 评论 0
/**
 * @return A {@link TenantInformationProvider} that gets the database name from {@link #dataBaseName}.
 */
@Bean
public TenantInformationProvider tenantProvider() {
    return new TenantInformationProvider() {
        @Override
        public String getDatabaseName() {
            if("failure".equals(dataBaseName.get())) {
                throw new RuntimeException("On purpose thrown exception.");
            }
            return dataBaseName.get();
        }

        @Override
        public MongoClientURI getDatabaseURI() {
            String uri = "mongodb://fake_host:27017/" + dataBaseName.get();
            return new MongoClientURI(uri);
        }
    };
}


问题


面经


文章

微信
公众号

扫码关注公众号