com.mongodb.ServerAddress

Here are the examples of the java api com.mongodb.ServerAddress taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

62 Examples 7

19 Source : MongoStoragePlugin.java
with Apache License 2.0
from zpochen

public synchronized MongoClient getClient(List<ServerAddress> addresses) {
    // Take the first replica from the replicated servers
    final ServerAddress serverAddress = addresses.get(0);
    final MongoCredential credential = clientURI.getCredentials();
    String userName = credential == null ? null : credential.getUserName();
    MongoCnxnKey key = new MongoCnxnKey(serverAddress, userName);
    MongoClient client = addressClientMap.getIfPresent(key);
    if (client == null) {
        if (credential != null) {
            List<MongoCredential> credentialList = Arrays.asList(credential);
            client = new MongoClient(addresses, credentialList, clientURI.getOptions());
        } else {
            client = new MongoClient(addresses, clientURI.getOptions());
        }
        addressClientMap.put(key, client);
        logger.debug("Created connection to {}.", key.toString());
        logger.debug("Number of open connections {}.", addressClientMap.size());
    }
    return client;
}

19 Source : MongoCnxnKey.java
with Apache License 2.0
from zpochen

public clreplaced MongoCnxnKey {

    private ServerAddress address;

    private String user;

    public MongoCnxnKey(ServerAddress address, String user) {
        this.address = address;
        this.user = user;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((address == null) ? 0 : address.hashCode());
        result = prime * result + ((user == null) ? 0 : user.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClreplaced() != obj.getClreplaced()) {
            return false;
        }
        MongoCnxnKey other = (MongoCnxnKey) obj;
        if (address == null) {
            if (other.address != null) {
                return false;
            }
        } else if (!address.equals(other.address)) {
            return false;
        }
        if (user == null) {
            if (other.user != null) {
                return false;
            }
        } else if (!user.equals(other.user)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "[address=" + address.toString() + ", user=" + user + "]";
    }
}

19 Source : ReactiveMongoClientFactoryTests.java
with Apache License 2.0
from yuanmabiji

private void replacedertServerAddress(ServerAddress serverAddress, String expectedHost, int expectedPort) {
    replacedertThat(serverAddress.getHost()).isEqualTo(expectedHost);
    replacedertThat(serverAddress.getPort()).isEqualTo(expectedPort);
}

19 Source : Test.java
with Apache License 2.0
from yametech

@org.junit.Test
public void test() {
    try {
        // 连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
        // ServerAddress()两个参数分别为 服务器地址 和 端口
        ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
        List<ServerAddress> addrs = new ArrayList<>();
        addrs.add(serverAddress);
        // MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
        MongoCredential credential = MongoCredential.createScramSha1Credential("a_ecpark_c_rw", "admin", "23xnws".toCharArray());
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        credentials.add(credential);
        // 通过连接认证获取MongoDB连接
        // MongoClient mongoClient = new MongoClient(addrs, credential, MongoClientOptions.builder().build());
        MongoClient mongoClient = new MongoClient(addrs);
        // 连接到数据库
        // MongoDatabase mongoDatabase = mongoClient.getDatabase("ecpark_monitor");
        MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
        // MongoCollection<Doreplacedent> collection = mongoDatabase.getCollection("app_log");
        MongoCollection<Doreplacedent> collection = mongoDatabase.getCollection("user");
        MongoCollection<Doreplacedent> collection2 = mongoDatabase.getCollection("address");
        System.out.println("集合 test 选择成功");
        // 检索所有文档
        /**
         * 1. 获取迭代器FindIterable<Doreplacedent>
         * 2. 获取游标MongoCursor<Doreplacedent>
         * 3. 通过游标遍历检索出的文档集合
         */
        FindIterable<Doreplacedent> findIterable = collection.find().limit(10);
        MongoCursor<Doreplacedent> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next());
        }
        Bson lookup = new Doreplacedent("$lookup", new Doreplacedent("from", "address").append("localField", "id").append("foreignField", "userId").append("as", "look_coll"));
        AggregateIterable<Doreplacedent> it = collection.aggregate(Arrays.asList(lookup));
        for (Doreplacedent row : it) {
            System.out.println("==============>" + row.toJson());
        }
        // updateOne
        collection.updateOne(eq("id", 1), new Doreplacedent("$set", new Doreplacedent("name", "zhangsan")));
        // updateMany
        // collection.updateMany(lt("id", 1), inc("id", 100));
        // deleteOne
        // collection.deleteOne(eq("id", 1));
        // deleteMany
        // collection.deleteMany(eq("id", 1));
        // findOneAndUpdate
        // collection.findOneAndUpdate(eq("id", 1), new Doreplacedent("$set", new Doreplacedent("name", "zhangsan")));
        // collection.findOneAndDelete(eq("id", 1));
        Map<String, Object> obj = new HashMap<>();
        obj.put("userId", 3);
        obj.put("name", "wangwu");
        // collection.insertOne(new Doreplacedent(obj));
        // collection.insertMany(Arrays.asList(new Doreplacedent(obj)));
        collection.count();
        Doreplacedent insertDoreplacedent = new Doreplacedent("name", "GZ");
        insertDoreplacedent.append("userId", 99);
        InsertOneModel<Doreplacedent> insertOneModel = new InsertOneModel<Doreplacedent>(insertDoreplacedent);
        // collection.bulkWrite(Arrays.asList(insertOneModel));
        System.out.println("Connect to database successfully");
        TimeUnit.SECONDS.sleep(5);
    } catch (Exception e) {
        System.err.println(e.getClreplaced().getName() + ": " + e.getMessage());
    }
}

19 Source : MongoConstructorInterceptor.java
with Apache License 2.0
from yametech

private String getServerUrl(Cluster cluster) {
    StringBuilder sb = new StringBuilder();
    for (ServerDescription description : cluster.getDescription().getAll()) {
        ServerAddress address = description.getAddress();
        sb.append(address.getHost()).append(":").append(address.getPort()).append(",");
    }
    return sb.substring(0, sb.length() - 1);
}

19 Source : MongoClientImplInterceptor.java
with Apache License 2.0
from yametech

@Override
public void constructor(Object thisObj, Object[] allArguments) throws Throwable {
    if (!(allArguments[0] instanceof MongoClientSettings)) {
        return;
    }
    final MongoClientSettings mongoClientSettings = (MongoClientSettings) allArguments[0];
    List<ServerAddress> lists = mongoClientSettings.getClusterSettings().getHosts();
    if (lists == null || lists.size() == 0) {
        return;
    }
    StringBuilder sb = new StringBuilder();
    for (ServerAddress serverAddress : lists) {
        sb.append(serverAddress.getHost()).append(":").append(serverAddress.getPort()).append(",");
    }
    String serverUrl = sb.substring(0, sb.length() - 1);
    ((IContext) thisObj)._setAgentContext(ContextConstants.MONGO_SERVER_URL, serverUrl);
}

19 Source : MongoClientDelegateInterceptor.java
with Apache License 2.0
from yametech

private String getServerUrl(Cluster cluster) {
    StringBuilder sb = new StringBuilder();
    for (ServerAddress address : cluster.getSettings().getHosts()) {
        sb.append(address.getHost()).append(":").append(address.getPort()).append(",");
    }
    return sb.substring(0, sb.length() - 1);
}

19 Source : MongoBenchmark.java
with Apache License 2.0
from yametech

/**
 * benchmark之前执行初始化
 */
@Setup
public void before() {
    // 连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
    // ServerAddress()两个参数分别为 服务器地址 和 端口
    // ServerAddress serverAddress = new ServerAddress("10.1.1.232", 40001);
    ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
    List<ServerAddress> addrs = new ArrayList<>();
    addrs.add(serverAddress);
    // MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
    MongoCredential credential = MongoCredential.createScramSha1Credential("a_ecpark_c_rw", "admin", "23xnws".toCharArray());
    List<MongoCredential> credentials = new ArrayList<MongoCredential>();
    credentials.add(credential);
    // 通过连接认证获取MongoDB连接
    // MongoClient mongoClient = new MongoClient(addrs, credential, MongoClientOptions.builder().build());
    mongoClient = new MongoClient(addrs);
}

19 Source : MongoConfig.java
with MIT License
from xwlcn

// 覆盖默认的MongoDbFactory
@Bean
MongoDbFactory mongoDbFactory(MongoSettingsProperties mongoSettingsProperties) {
    // 客户端配置(连接数、副本集群验证)
    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    builder.connectionsPerHost(mongoSettingsProperties.getMaxConnectionsPerHost());
    builder.minConnectionsPerHost(mongoSettingsProperties.getMinConnectionsPerHost());
    if (mongoSettingsProperties.getReplicaSet() != null) {
        builder.requiredReplicaSetName(mongoSettingsProperties.getReplicaSet());
    }
    builder.threadsAllowedToBlockForConnectionMultiplier(mongoSettingsProperties.getThreadsAllowedToBlockForConnectionMultiplier());
    builder.serverSelectionTimeout(mongoSettingsProperties.getServerSelectionTimeout());
    builder.maxWaitTime(mongoSettingsProperties.getMaxWaitTime());
    builder.maxConnectionIdleTime(mongoSettingsProperties.getMaxConnectionIdleTime());
    builder.maxConnectionLifeTime(mongoSettingsProperties.getMaxConnectionLifeTime());
    builder.connectTimeout(mongoSettingsProperties.getConnectTimeout());
    builder.socketTimeout(mongoSettingsProperties.getSocketTimeout());
    builder.sslEnabled(mongoSettingsProperties.getSslEnabled());
    builder.sslInvalidHostNameAllowed(mongoSettingsProperties.getSslInvalidHostNameAllowed());
    builder.alwaysUseMBeans(mongoSettingsProperties.getAlwaysUseMBeans());
    builder.heartbeatFrequency(mongoSettingsProperties.getHeartbeatFrequency());
    builder.minHeartbeatFrequency(mongoSettingsProperties.getMinHeartbeatFrequency());
    builder.heartbeatConnectTimeout(mongoSettingsProperties.getHeartbeatConnectTimeout());
    builder.heartbeatSocketTimeout(mongoSettingsProperties.getHeartbeatSocketTimeout());
    builder.localThreshold(mongoSettingsProperties.getLocalThreshold());
    MongoClientOptions mongoClientOptions = builder.build();
    // MongoDB地址列表
    List<ServerAddress> serverAddresses = new ArrayList<>();
    for (String address : mongoSettingsProperties.getAddress()) {
        String[] hostAndPort = address.split(":");
        String host = hostAndPort[0];
        Integer port = Integer.parseInt(hostAndPort[1]);
        ServerAddress serverAddress = new ServerAddress(host, port);
        serverAddresses.add(serverAddress);
    }
    // 连接认证
    if (mongoSettingsProperties.getUsername() == null) {
        throw new RuntimeException("mongodb username can not be null");
    }
    MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(mongoSettingsProperties.getUsername(), mongoSettingsProperties.getAuthenticationDatabase() != null ? mongoSettingsProperties.getAuthenticationDatabase() : mongoSettingsProperties.getDatabase(), mongoSettingsProperties.getPreplacedword().toCharArray());
    // 创建客户端和Factory
    MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, mongoClientOptions);
    MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, mongoSettingsProperties.getDatabase());
    return mongoDbFactory;
}

19 Source : MongoUtil.java
with Apache License 2.0
from wgzhao

/**
 * 转换为mongo地址协议
 *
 * @param rawAddressList raw address list
 * @return List of ServerAddress
 * @throws UnknownHostException host not reached
 */
private static List<ServerAddress> parseServerAddress(List<Object> rawAddressList) throws UnknownHostException {
    List<ServerAddress> addressList = new ArrayList<>();
    for (Object address : rawAddressList) {
        String[] tempAddress = ((String) address).split(":");
        try {
            ServerAddress sa = new ServerAddress(tempAddress[0], Integer.parseInt(tempAddress[1]));
            addressList.add(sa);
        } catch (Exception e) {
            throw new UnknownHostException();
        }
    }
    return addressList;
}

19 Source : MongoUtil.java
with Apache License 2.0
from wgzhao

/**
 * 转换为mongo地址协议
 *
 * @param rawAddressList raw address list
 * @return List of ServerAddress
 * @throws UnknownHostException can not find host or ip address
 */
private static List<ServerAddress> parseServerAddress(List<Object> rawAddressList) throws UnknownHostException {
    List<ServerAddress> addressList = new ArrayList<>();
    for (Object address : rawAddressList) {
        String[] tempAddress = ((String) address).split(":");
        try {
            ServerAddress sa = new ServerAddress(tempAddress[0], Integer.parseInt(tempAddress[1]));
            addressList.add(sa);
        } catch (Exception e) {
            throw new UnknownHostException();
        }
    }
    return addressList;
}

19 Source : MongoDBDataSource.java
with Apache License 2.0
from uavorg

/**
 * mongo cluster model
 */
@Override
public MongoDatabase initSourceConnect() throws Exception {
    List<MongoCredential> auths = new ArrayList<MongoCredential>();
    if (!StringHelper.isEmpty(connection.getUsername()) && !StringHelper.isEmpty(connection.getPreplacedword())) {
        MongoCredential credential = MongoCredential.createCredential(connection.getUsername(), connection.getDbPower(), connection.getPreplacedword().toCharArray());
        auths.add(credential);
    }
    List<ServerAddress> addres = new ArrayList<ServerAddress>();
    List<String> addrList = connection.getAddressList();
    for (String add : addrList) {
        String[] hosts = add.split(":");
        ServerAddress sa = new ServerAddress(hosts[0], Integer.parseInt(hosts[1]));
        addres.add(sa);
    }
    mongo = new MongoClient(addres, auths);
    MongoDatabase db = mongo.getDatabase(connection.getDbName());
    if (db != null) {
        if (log.isTraceEnable()) {
            log.info(this, "INIT MongoDBDataSource SUCCESS:db=" + connection.getDbName() + ",connection=" + mongo.getConnectPoint());
        }
    } else {
        throw new Exception("INIT MongoDBDataSource FAIL: No db object for database[" + connection.getDbName() + "]");
    }
    return db;
}

19 Source : DatabaseService.java
with MIT License
from Twasi

/**
 * Connect to the database and map Model-Clreplacedes
 */
public void connect() {
    // Apply custom logger
    MorphiaLoggerFactory.registerLogger(TwasiLoggerFactory.clreplaced);
    // Disable Mongo Debugging
    System.setProperty("DEBUG.MONGO", "false");
    morphia = new Morphia();
    morphia.mapPackage("net.twasi.database.models");
    // Connect with given credentials
    Morphia morphia = new Morphia();
    ServerAddress addr = new ServerAddress(ServiceRegistry.get(ConfigService.clreplaced).getCatalog().database.hostname, ServiceRegistry.get(ConfigService.clreplaced).getCatalog().database.port);
    MongoClient client;
    // Use authentication?
    if (ServiceRegistry.get(ConfigService.clreplaced).getCatalog().database.authentication != null && ServiceRegistry.get(ConfigService.clreplaced).getCatalog().database.authentication.user != null && ServiceRegistry.get(ConfigService.clreplaced).getCatalog().database.authentication.preplacedword != null) {
        List<MongoCredential> credentialsList = new ArrayList<>();
        MongoCredential credential = MongoCredential.createCredential(ServiceRegistry.get(ConfigService.clreplaced).getCatalog().database.authentication.user, ServiceRegistry.get(ConfigService.clreplaced).getCatalog().database.database, ServiceRegistry.get(ConfigService.clreplaced).getCatalog().database.authentication.preplacedword.toCharArray());
        credentialsList.add(credential);
        client = new MongoClient(addr, credentialsList);
    } else {
        client = new MongoClient(addr);
    }
    // Create the store
    store = morphia.createDatastore(client, ServiceRegistry.get(ConfigService.clreplaced).getCatalog().database.database);
    store.ensureIndexes();
}

19 Source : MongoWrapper.java
with Apache License 2.0
from RADAR-base

private MongoClient createClient(AbstractConfig config, MongoClientOptions options) {
    String host = config.getString(MONGO_HOST);
    int port = config.getInt(MONGO_PORT);
    try {
        MongoClientOptions actualOptions;
        if (options != null) {
            actualOptions = options;
        } else {
            actualOptions = new MongoClientOptions.Builder().build();
        }
        ServerAddress server = new ServerAddress(host, port);
        if (credentials != null) {
            return new MongoClient(server, credentials, actualOptions);
        } else {
            return new MongoClient(server, actualOptions);
        }
    } catch (MongoException ex) {
        log.error("Failed to create MongoDB client to {}:{} with credentials {}", host, port, credentials, ex);
        throw new ConnectException("MongoDb client cannot be created.", ex);
    }
}

19 Source : MongoAdminService.java
with Apache License 2.0
from PaaS-TA

public String getServerAddresses() {
    StringBuilder builder = new StringBuilder();
    for (ServerAddress address : client.getAllAddress()) {
        builder.append(address.getHost());
        builder.append(":");
        builder.append(address.getPort());
        builder.append(",");
    }
    if (builder.length() > 0) {
        builder.deleteCharAt(builder.length() - 1);
    }
    return builder.toString();
}

19 Source : NewRelicCommandListener.java
with Apache License 2.0
from newrelic

@Override
public void commandStarted(CommandStartedEvent event) {
    try {
        Segment tracer = NewRelic.getAgent().getTransaction().startSegment(null);
        if (tracer != null) {
            holder.set(tracer);
            String collectionName = getCollectionName(event);
            String operationName = event.getCommandName().intern();
            ServerAddress address = event.getConnectionDescription().getServerAddress();
            DatastoreParameters params = DatastoreParameters.product(DatastoreVendor.MongoDB.name()).collection(collectionName).operation(operationName).instance(address.getHost(), address.getPort()).databaseName(event.getDatabaseName()).build();
            tracer.reportAsExternal(params);
        }
    } catch (Throwable t) {
        AgentBridge.instrumentation.noticeInstrumentationError(t, Weaver.getImplementationreplacedle());
    }
}

19 Source : MongoDatabase_Weaved.java
with Apache License 2.0
from newrelic

@Weave(type = MatchType.Interface, originalName = "com.mongodb.client.MongoDatabase")
public abstract clreplaced MongoDatabase_Weaved {

    @NewField
    public ServerAddress address = new ServerAddress("unknown");

    public MongoCollection_Instrumentation<Doreplacedent> getCollection(final String collectionName) {
        MongoCollection_Instrumentation<Doreplacedent> collection = Weaver.callOriginal();
        collection.address = address;
        return collection;
    }

    public MongoDatabase_Weaved withCodecRegistry(final CodecRegistry codecRegistry) {
        MongoDatabase_Weaved database = Weaver.callOriginal();
        database.address = address;
        return database;
    }

    public MongoDatabase_Weaved withReadPreference(final ReadPreference readPreference) {
        MongoDatabase_Weaved database = Weaver.callOriginal();
        database.address = address;
        return database;
    }

    public MongoDatabase_Weaved withWriteConcern(final WriteConcern writeConcern) {
        MongoDatabase_Weaved database = Weaver.callOriginal();
        database.address = address;
        return database;
    }
}

19 Source : MongoCollection_Instrumentation.java
with Apache License 2.0
from newrelic

@Weave(type = MatchType.Interface, originalName = "com.mongodb.client.MongoCollection")
public abstract clreplaced MongoCollection_Instrumentation<TDoreplacedent> {

    @NewField
    public ServerAddress address = new ServerAddress("unknown");

    public abstract MongoNamespace getNamespace();

    @Trace(leaf = true)
    public long count(Bson filter, CountOptions options) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_COUNT);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public <TResult> Distincreplacederable<TResult> distinct(String fieldName, Clreplaced<TResult> resultClreplaced) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_DISTINCT);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public <TResult> FindIterable<TResult> find(Bson filter, Clreplaced<TResult> resultClreplaced) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_FIND);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public <TResult> AggregateIterable<TResult> aggregate(List<? extends Bson> pipeline, Clreplaced<TResult> resultClreplaced) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_AGGREGATE);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public <TResult> MapReduceIterable<TResult> mapReduce(String mapFunction, String reduceFunction, Clreplaced<TResult> resultClreplaced) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_MAP_REDUCE);
        return Weaver.callOriginal();
    }

    /*
     * This eventually calls MixedBulkWriteOperation, which is where we record metrics for each individual operation.
     * Hence no leaf = true here.
     */
    @Trace
    public BulkWriteResult bulkWrite(List<? extends WriteModel<? extends TDoreplacedent>> requests, BulkWriteOptions options) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_BULK_WRITE);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public void insertOne(TDoreplacedent doreplacedent) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_INSERT);
        Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public void insertMany(List<? extends TDoreplacedent> doreplacedents, InsertManyOptions options) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_INSERT_MANY);
        Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public DeleteResult deleteOne(Bson filter) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_DELETE);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public DeleteResult deleteMany(Bson filter) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_DELETE);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public UpdateResult replaceOne(final Bson filter, final TDoreplacedent replacement, final UpdateOptions updateOptions) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_REPLACE);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public UpdateResult updateOne(Bson filter, Bson update, UpdateOptions updateOptions) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_UPDATE);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public UpdateResult updateMany(Bson filter, Bson update, UpdateOptions updateOptions) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_UPDATE_MANY);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public TDoreplacedent findOneAndDelete(Bson filter, FindOneAndDeleteOptions options) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_FIND_AND_DELETE);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public TDoreplacedent findOneAndReplace(final Bson filter, final TDoreplacedent replacement, final FindOneAndReplaceOptions options) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_FIND_AND_REPLACE);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public TDoreplacedent findOneAndUpdate(final Bson filter, final Bson update, final FindOneAndUpdateOptions options) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_FIND_AND_UPDATE);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public void drop() {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_DROP_COLLECTION);
        Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public List<String> createIndexes(List<IndexModel> indexes) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_REPLACE);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public <TResult> ListIndexesIterable<TResult> listIndexes(Clreplaced<TResult> resultClreplaced) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_LIST_INDEX);
        return Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public void dropIndex(String indexName) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_DROP_INDEX);
        Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public void dropIndex(Bson keys) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_DROP_INDEX);
        Weaver.callOriginal();
    }

    @Trace(leaf = true)
    public void renameCollection(MongoNamespace newCollectionNamespace, RenameCollectionOptions renameCollectionOptions) {
        instrument(NewRelic.getAgent().getTracedMethod(), MongoUtil.OP_RENAME_COLLECTION);
        Weaver.callOriginal();
    }

    private void instrument(TracedMethod method, String operationName) {
        DatastoreParameters params = DatastoreParameters.product(DatastoreVendor.MongoDB.name()).collection(getNamespace().getCollectionName()).operation(operationName).instance(address.getHost(), address.getPort()).databaseName(getNamespace().getDatabaseName()).build();
        NewRelic.getAgent().getTracedMethod().reportAsExternal(params);
    }

    public MongoCollection_Instrumentation<TDoreplacedent> withCodecRegistry(final CodecRegistry codecRegistry) {
        MongoCollection_Instrumentation<TDoreplacedent> collection = Weaver.callOriginal();
        collection.address = address;
        return collection;
    }

    public <NewTDoreplacedent> MongoCollection_Instrumentation<NewTDoreplacedent> withDoreplacedentClreplaced(final Clreplaced<NewTDoreplacedent> clazz) {
        MongoCollection_Instrumentation<NewTDoreplacedent> collection = Weaver.callOriginal();
        collection.address = address;
        return collection;
    }

    public MongoCollection_Instrumentation<TDoreplacedent> withReadPreference(final ReadPreference readPreference) {
        MongoCollection_Instrumentation<TDoreplacedent> collection = Weaver.callOriginal();
        collection.address = address;
        return collection;
    }

    public MongoCollection_Instrumentation<TDoreplacedent> withWriteConcern(final WriteConcern writeConcern) {
        MongoCollection_Instrumentation<TDoreplacedent> collection = Weaver.callOriginal();
        collection.address = address;
        return collection;
    }

    // these methods are declared for test compatibility
    public abstract void insertMany(List<? extends TDoreplacedent> doreplacedents);

    public abstract FindIterable<TDoreplacedent> find();

    public abstract FindIterable<TDoreplacedent> find(Bson filter);

    public abstract UpdateResult updateOne(Bson filter, Bson update);

    public abstract UpdateResult updateMany(Bson filter, Bson update);

    public abstract BulkWriteResult bulkWrite(List<? extends WriteModel<? extends TDoreplacedent>> requests);

    public abstract long count();
}

19 Source : DefaultMongoConfiguration.java
with Apache License 2.0
from micronaut-projects

/**
 * Sets the server MongoDB server address.
 *
 * @param serverAddress The server address
 */
public void setHost(ServerAddress serverAddress) {
    getClusterSettings().hosts(Collections.singletonList(serverAddress));
}

19 Source : InsertIntoMongo.java
with Apache License 2.0
from linnykoleh

public static void main(String[] s) {
    final String host = "127.0.0.1";
    final int port = 27017;
    final String database = "local";
    final ServerAddress server = new ServerAddress(host, port);
    final MongoClient mongo = new MongoClient(server);
    final MongoOperations mongoOperation = new MongoTemplate(mongo, database);
    mongoOperation.dropCollection(UserTo.clreplaced);
    final UserTo user = new UserTo("ankidaemon", "preplacedword", true);
    mongoOperation.save(user);
    final UserTo user1 = new UserTo("test", "test", true);
    mongoOperation.save(user1);
    // Retrieve all users as a list
    final List<UserTo> users = mongoOperation.findAll(UserTo.clreplaced);
    for (UserTo userVar : users) {
        System.out.println(userVar.getUsername() + " " + userVar.getPreplacedword());
    }
    // Find User based on query
    final UserTo userVar = mongoOperation.findOne(new Query(Criteria.where("username").is("ankidaemon")), UserTo.clreplaced);
    System.out.println(userVar.getUsername() + " " + userVar.getPreplacedword());
}

19 Source : CustomUserDetailsService.java
with Apache License 2.0
from linnykoleh

private MongoTemplate mongoTemplate() {
    final String host = "127.0.0.1";
    final int port = 27017;
    final String database = "local";
    final ServerAddress server = new ServerAddress(host, port);
    final MongoClient mongo = new MongoClient(server);
    return new MongoTemplate(mongo, database);
}

19 Source : ReactiveMongoClientTestConfiguration.java
with Apache License 2.0
from krraghavan

@Bean
public MongoClient mongoClient() throws IOException {
    ServerAddress serverAddress = getServerAddress();
    MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(ClusterSettings.builder().hosts(singletonList(serverAddress)).requiredClusterType(STANDALONE).build()).build();
    return MongoClients.create(settings);
}

19 Source : NonReactiveMongoClientTestConfiguration.java
with Apache License 2.0
from krraghavan

@Bean
public MongoClient mongoClient() throws IOException {
    ServerAddress serverAddress = getServerAddress();
    return new MongoClient(serverAddress);
}

19 Source : OperationExecutor.java
with GNU Affero General Public License v3.0
from idealo

public static void main(String[] args) throws InterruptedException {
    ServerAddress serverAddress = new ServerAddress("test-db:27017");
    MongoDbAccessor mongoDbAccessor = new MongoDbAccessor("user", "pw", "testdb", true, serverAddress);
    InsertOperation insertOperation = new InsertOperation(mongoDbAccessor, "testdb", "perf", IOperation.ID);
    OperationExecutor operationExecutor = new OperationExecutor(10, 1000000, 3600, insertOperation, new CountDownLatch(1));
    operationExecutor.executeThreads();
    operationExecutor.replacedysis();
    operationExecutor.stopReporters();
    mongoDbAccessor.closeConnections();
}

19 Source : Main.java
with GNU Affero General Public License v3.0
from idealo

private void executeOperations() {
    final ServerAddress serverAddress = new ServerAddress(host, port);
    final MongoDbAccessor mongoDbAccessor = new MongoDbAccessor(user, preplacedword, authDb, ssl, serverAddress);
    int run = 0;
    CountDownLatch runModeLatch = new CountDownLatch(modes.size());
    final ExecutorService executor = Executors.newFixedThreadPool(modes.size());
    try {
        for (int threadCount : threadCounts) {
            if (run >= modes.size()) {
                run = 0;
                LOG.info("All run modes are running with their specified number of threads. Waiting on finishing of each run mode before continuing...");
                runModeLatch.await();
                runModeLatch = new CountDownLatch(modes.size());
            }
            final String mode = modes.get(run);
            final long operationsCount = operationsCounts.size() > run ? operationsCounts.get(run) : operationsCounts.get(0);
            IOperation operation = null;
            if (mode.equals(OperationModes.UPDATE_ONE.name())) {
                operation = new UpdateOperation(mongoDbAccessor, database, collection, IOperation.ID);
            } else if (mode.equals(OperationModes.UPDATE_MANY.name())) {
                operation = new UpdateOperation(mongoDbAccessor, database, collection, IOperation.THREAD_RUN_COUNT);
            } else if (mode.equals(OperationModes.COUNT_ONE.name())) {
                operation = new CountOperation(mongoDbAccessor, database, collection, IOperation.ID);
            } else if (mode.equals(OperationModes.COUNT_MANY.name())) {
                operation = new CountOperation(mongoDbAccessor, database, collection, IOperation.THREAD_RUN_COUNT);
            } else if (mode.equals(OperationModes.ITERATE_ONE.name())) {
                operation = new IterateOperation(mongoDbAccessor, database, collection, IOperation.ID);
            } else if (mode.equals(OperationModes.ITERATE_MANY.name())) {
                operation = new IterateOperation(mongoDbAccessor, database, collection, IOperation.THREAD_RUN_COUNT);
            } else if (mode.equals(OperationModes.DELETE_ONE.name())) {
                operation = new DeleteOperation(mongoDbAccessor, database, collection, IOperation.ID);
            } else if (mode.equals(OperationModes.DELETE_MANY.name())) {
                operation = new DeleteOperation(mongoDbAccessor, database, collection, IOperation.THREAD_RUN_COUNT);
            } else {
                InsertOperation insertOperation = new InsertOperation(mongoDbAccessor, database, collection, IOperation.ID);
                if (dropDb) {
                    LOG.info("drop database '{}'", database);
                    mongoDbAccessor.getMongoDatabase(database).drop();
                    LOG.info("database '{}' dropped", database);
                }
                if (randomFieldLength > 0) {
                    insertOperation.setRandomFieldLength(randomFieldLength);
                }
                operation = insertOperation;
            }
            OperationExecutor operationExecutor = new OperationExecutor(threadCount, operationsCount, maxDurationInSeconds, operation, runModeLatch);
            executor.execute(operationExecutor);
            run++;
        }
        runModeLatch.await();
    } catch (Exception e) {
        LOG.error("Error while waiting on thread.", e);
    } finally {
        executor.shutdown();
        mongoDbAccessor.closeConnections();
    }
}

19 Source : MongoConfig.java
with Apache License 2.0
from Hygieia

@Override
@Bean
public MongoClient mongo() throws Exception {
    MongoClient client;
    LOGGER.info("ReplicaSet" + dbreplicaset);
    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    builder.maxConnectionIdleTime(60000);
    builder.sslEnabled(Boolean.parseBoolean(dbssl));
    // MongoDB default 30 seconds
    builder.serverSelectionTimeout(30000);
    // MongoDB default varies, may be 10 seconds
    builder.connectTimeout(dbConnectTimeout);
    // MongoDB default is 0, means no timeout
    builder.socketTimeout(dbSocketTimeout);
    MongoClientOptions opts = builder.build();
    if (Boolean.parseBoolean(dbreplicaset)) {
        List<ServerAddress> serverAddressList = new ArrayList<>();
        for (String h : hostport) {
            String myHost = h.substring(0, h.indexOf(":"));
            int myPort = Integer.parseInt(h.substring(h.indexOf(":") + 1));
            ServerAddress serverAddress = new ServerAddress(myHost, myPort);
            serverAddressList.add(serverAddress);
        }
        for (ServerAddress s : serverAddressList) {
            LOGGER.info("Initializing Mongo Client server ReplicaSet at: {}", s);
        }
        if (StringUtils.isEmpty(userName)) {
            client = new MongoClient(serverAddressList);
        } else {
            MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(userName, databaseName, preplacedword.toCharArray());
            client = new MongoClient(serverAddressList, Collections.singletonList(mongoCredential), opts);
        }
    } else {
        ServerAddress serverAddr = new ServerAddress(host, port);
        LOGGER.info("Initializing Mongo Client server at: {}", serverAddr);
        if (StringUtils.isEmpty(userName)) {
            client = new MongoClient(serverAddr);
        } else {
            MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(userName, databaseName, preplacedword.toCharArray());
            client = new MongoClient(serverAddr, Collections.singletonList(mongoCredential), opts);
        }
    }
    LOGGER.info("Connecting to Mongo: {}", client);
    return client;
}

19 Source : HygieiaExecMongoConfig.java
with Apache License 2.0
from Hygieia

@Override
@Bean
public MongoClient mongo() throws Exception {
    MongoClient client;
    LOGGER.info("ReplicaSet" + dbreplicaset);
    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    builder.maxConnectionIdleTime(60000);
    MongoClientOptions opts = builder.build();
    if (Boolean.parseBoolean(dbreplicaset)) {
        List<ServerAddress> serverAddressList = new ArrayList<>();
        hostport.forEach(h -> {
            String myHost = h.substring(0, h.indexOf(":"));
            int myPort = Integer.parseInt(h.substring(h.indexOf(":") + 1, h.length()));
            ServerAddress serverAddress = new ServerAddress(myHost, myPort);
            serverAddressList.add(serverAddress);
        });
        serverAddressList.forEach(s -> LOGGER.info("Initializing Mongo Client server ReplicaSet at: {}", s));
        if (StringUtils.isEmpty(userName)) {
            client = new MongoClient(serverAddressList);
        } else {
            MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(userName, databaseName, preplacedword.toCharArray());
            client = new MongoClient(serverAddressList, Collections.singletonList(mongoCredential), opts);
        }
    } else {
        ServerAddress serverAddr = new ServerAddress(host, port);
        LOGGER.info("Initializing Mongo Client server at: {}", serverAddr);
        if (StringUtils.isEmpty(userName)) {
            client = new MongoClient(serverAddr);
        } else {
            MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(userName, databaseName, preplacedword.toCharArray());
            client = new MongoClient(serverAddr, Collections.singletonList(mongoCredential), opts);
        }
    }
    LOGGER.info("Connecting to Mongo: {}", client);
    return client;
}

19 Source : MongoReporterConfiguration.java
with Apache License 2.0
from gravitee-io

@Bean
public MongoClient mongoClient() {
    // Client settings
    com.mongodb.MongoClientSettings.Builder builder = com.mongodb.MongoClientSettings.builder();
    builder.writeConcern(WriteConcern.ACKNOWLEDGED);
    // codec configuration for pojo mapping
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    builder.codecRegistry(pojoCodecRegistry);
    if ((this.configuration.getUri() != null) && (!this.configuration.getUri().isEmpty())) {
        // The builder can be configured with default options, which may be overridden by options specified in
        // the URI string.
        com.mongodb.MongoClientSettings settings = builder.codecRegistry(pojoCodecRegistry).applyConnectionString(new ConnectionString(this.configuration.getUri())).build();
        return MongoClients.create(settings);
    } else {
        // Manual configuration
        // Servers host
        ServerAddress serverAddress = new ServerAddress(this.configuration.getHost(), this.configuration.getPort());
        ClusterSettings clusterSettings = ClusterSettings.builder().hosts(asList(serverAddress)).build();
        // Mongo credentials
        if (this.configuration.isEnableCredentials()) {
            MongoCredential credential = MongoCredential.createCredential(this.configuration.getUsernameCredentials(), this.configuration.getDatabaseCredentials(), this.configuration.getPreplacedwordCredentials().toCharArray());
            builder.credential(credential);
        }
        com.mongodb.MongoClientSettings settings = builder.applyToClusterSettings(builder1 -> builder1.applySettings(clusterSettings)).build();
        return MongoClients.create(settings);
    }
}

19 Source : MongoAuthenticationProviderConfiguration.java
with Apache License 2.0
from gravitee-io

@Bean
public MongoClient mongoClient() {
    MongoClient mongoClient;
    if ((this.configuration.getUri() != null) && (!this.configuration.getUri().isEmpty())) {
        mongoClient = MongoClients.create(this.configuration.getUri());
    } else {
        ServerAddress serverAddress = new ServerAddress(this.configuration.getHost(), this.configuration.getPort());
        ClusterSettings clusterSettings = ClusterSettings.builder().hosts(asList(serverAddress)).build();
        MongoClientSettings.Builder settings = MongoClientSettings.builder().clusterSettings(clusterSettings);
        if (this.configuration.isEnableCredentials()) {
            MongoCredential credential = MongoCredential.createCredential(this.configuration.getUsernameCredentials(), this.configuration.getDatabaseCredentials(), this.configuration.getPreplacedwordCredentials().toCharArray());
            settings.credential(credential);
        }
        mongoClient = MongoClients.create(settings.build());
    }
    return mongoClient;
}

19 Source : MongoDbUtilities.java
with MIT License
from gagoyal01

public static boolean getMongoClient(SyncConnectionInfo connectionInfo) {
    boolean flag = false;
    List<ServerAddress> addressList = null;
    List<MongoCredential> credList = null;
    MongoClient client = null;
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
    optionsBuilder.readPreference(ReadPreference.secondary());
    if (connectionInfo.getPreplacedword() != null && !connectionInfo.getPreplacedword().isEmpty()) {
        MongoCredential credential = MongoCredential.createCredential(connectionInfo.getUserName(), connectionInfo.getDbName(), connectionInfo.getPreplacedword().toCharArray());
        credList = new ArrayList<MongoCredential>();
        credList.add(credential);
    }
    if (connectionInfo.getHostToPortMap() != null && !connectionInfo.getHostToPortMap().isEmpty()) {
        addressList = new ArrayList<ServerAddress>();
        ServerAddress address = null;
        for (Map.Entry<String, Double> hostPort : connectionInfo.getHostToPortMap().entrySet()) {
            address = new ServerAddress(hostPort.getKey(), hostPort.getValue().intValue());
            addressList.add(address);
        }
    }
    if (credList != null) {
        client = new MongoClient(addressList, credList, optionsBuilder.build());
    } else {
        client = new MongoClient(addressList, optionsBuilder.build());
    }
    if (client != null) {
        flag = true;
        client.close();
    }
    return flag;
}

19 Source : ExtentKlovReporter.java
with Apache License 2.0
from extent-framework

/**
 * Initializes the Mongo DB connection with {@link ServerAddress}
 *
 * @param addr
 *            {@link ServerAddress} server address
 * @return a {@link ExtentKlovReporter} object
 */
public ExtentKlovReporter initMongoDbConnection(ServerAddress addr) {
    mongoClient = new MongoClient(addr);
    return this;
}

19 Source : MongodbClientUtil.java
with Apache License 2.0
from DTStack

/**
 * parse server address from hostPorts string
 */
private static List<ServerAddress> getServerAddress(String hostPorts) {
    List<ServerAddress> addresses = new ArrayList<>();
    for (String hostPort : hostPorts.split(HOST_SPLIT_REGEX)) {
        if (hostPort.length() == 0) {
            continue;
        }
        Matcher matcher = HOST_PORT_PATTERN.matcher(hostPort);
        if (matcher.find()) {
            String host = matcher.group("host");
            String portStr = matcher.group("port");
            int port = portStr == null ? DEFAULT_PORT : Integer.parseInt(portStr);
            ServerAddress serverAddress = new ServerAddress(host, port);
            addresses.add(serverAddress);
        }
    }
    return addresses;
}

19 Source : MongoDbSource.java
with Apache License 2.0
from dounine

@Bean
public MongoDbFactory mongoDbFactory() throws Exception {
    MongoClientOptions.Builder mongoOperations = MongoClientOptions.builder();
    mongoOperations.socketTimeout(1000 * 2);
    mongoOperations.connectTimeout(1000 * 2);
    ServerAddress serverAddress = new ServerAddress(env.getProperty("db.host"), Integer.valueOf(env.getProperty("db.post")));
    MongoClientOptions mo = mongoOperations.build();
    MongoClient mongoClient = new MongoClient(serverAddress, mo);
    return new SimpleMongoDbFactory(mongoClient, env.getProperty("db.name"));
}

19 Source : MongoDBAdapter.java
with MIT License
from BotMill

/**
 * The mongodb ops.
 */
/* (non-Javadoc)
	 * @see co.aurasphere.botmill.core.datastore.adapter.DataAdapter#setup()
	 */
public void setup() {
    MongoCredential credential = MongoCredential.createCredential(ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.username"), ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.database"), ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.preplacedword").toCharArray());
    ServerAddress serverAddress = new ServerAddress(ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.server"), Integer.valueOf(ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.port")));
    MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
    SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(mongoClient, ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.database"));
    MongoTemplate mongoTemplate = new MongoTemplate(simpleMongoDbFactory);
    this.source = (MongoOperations) mongoTemplate;
}

19 Source : MongoTemplateFactory.java
with Apache License 2.0
from AxonFramework

/**
 * Constructs a {@link MongoTemplate} connecting with the given {@code host} and {@code port}. The {@code
 * settingsCustomization} is used to further fine tune the settings for creatin the {@code MongoTemplate}. Used for
 * testing purposes.
 *
 * @param host                  a {@link String} specifying the host of the MongoDb instance to connect with
 * @param port                  an {@code int} specifying the port of the MongoDb instance to connect with
 * @param settingsCustomization {@link Consumer} of the {@link MongoSettingsFactory} to allow for adding custom
 *                              settings
 * @return a {@link MongoTemplate} connecting with the given {@code host} and {@code port} to be used during testing
 */
public static MongoTemplate build(String host, int port, Consumer<MongoSettingsFactory> settingsCustomization) {
    MongoSettingsFactory mongoSettingsFactory = new MongoSettingsFactory();
    ServerAddress containerAddress = new ServerAddress(host, port);
    mongoSettingsFactory.setMongoAddresses(Collections.singletonList(containerAddress));
    mongoSettingsFactory.setConnectionsPerHost(100);
    settingsCustomization.accept(mongoSettingsFactory);
    MongoFactory mongoFactory = new MongoFactory();
    mongoFactory.setMongoClientSettings(mongoSettingsFactory.createMongoClientSettings());
    MongoClient mongoClient = mongoFactory.createMongo();
    return DefaultMongoTemplate.builder().mongoDatabase(mongoClient).build();
}

19 Source : MongoDBAbstractFactory.java
with MIT License
from AwakenCN

public MongoDbFactory mongoDbFactory() throws Exception {
    ServerAddress address = new ServerAddress(host, port);
    // 采用建造者模式才配置MongoDB初始化的参数
    MongoClientOptions options = MongoClientOptions.builder().connectTimeout(30000).build();
    MongoClient mongoClient = null;
    if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(preplacedword)) {
        MongoCredential credential = MongoCredential.createCredential(username, database, preplacedword.toCharArray());
        mongoClient = new MongoClient(address, credential, options);
    } else {
        mongoClient = new MongoClient(address);
    }
    SimpleMongoDbFactory factory = new SimpleMongoDbFactory(mongoClient, database);
    return factory;
}

19 Source : StandardMongoClientServiceIT.java
with Apache License 2.0
from Asymmetrik

@Test
public void test_various_host_inputs() {
    StandardMongoClientService service = new StandardMongoClientService();
    // Single host without specifying port
    List<ServerAddress> addresses = service.parseServerAddresses("e01sv05");
    replacedertEquals("Expecting one host", 1, addresses.size());
    ServerAddress address = addresses.get(0);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be default port: 27017", 27017, address.getPort());
    // Multiple hosts without specifying port
    addresses = service.parseServerAddresses("e01sv05, e01sv06");
    replacedertEquals("Expecting two hosts", 2, addresses.size());
    address = addresses.get(0);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be default port: 27017", 27017, address.getPort());
    address = addresses.get(1);
    replacedertEquals("should be host: e01sv06", "e01sv06", address.getHost());
    replacedertEquals("should be default port: 27017", 27017, address.getPort());
    // Multiple hosts, specifying port
    addresses = service.parseServerAddresses("e01sv05:2700, e01sv05:2701");
    replacedertEquals("Expecting two hosts", 2, addresses.size());
    address = addresses.get(0);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 2700", 2700, address.getPort());
    address = addresses.get(1);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 2701", 2701, address.getPort());
    // Multiple, repeating hosts, specifying port
    addresses = service.parseServerAddresses("e01sv05, e01sv05");
    replacedertEquals("Expecting two hosts", 2, addresses.size());
    address = addresses.get(0);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 27017", 27017, address.getPort());
    address = addresses.get(1);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 27017", 27017, address.getPort());
    // Try space delimiter
    addresses = service.parseServerAddresses("e01sv05:27017 e01sv05:27018");
    replacedertEquals("Expecting one host", 2, addresses.size());
    address = addresses.get(0);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 27017", 27017, address.getPort());
    address = addresses.get(1);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 27018", 27018, address.getPort());
    // Try repeated space delimiter
    addresses = service.parseServerAddresses("e01sv05:27017      e01sv05:27018");
    replacedertEquals("Expecting one host", 2, addresses.size());
    address = addresses.get(0);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 27017", 27017, address.getPort());
    address = addresses.get(1);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 27018", 27018, address.getPort());
    // Try semi-colon delimiter
    addresses = service.parseServerAddresses("e01sv05:27017;e01sv05:27018");
    replacedertEquals("Expecting one host", 2, addresses.size());
    address = addresses.get(0);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 27017", 27017, address.getPort());
    address = addresses.get(1);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 27018", 27018, address.getPort());
    // Try repeated semi-colon delimiter
    addresses = service.parseServerAddresses("e01sv05:27017;;;;e01sv05:27018");
    replacedertEquals("Expecting one host", 2, addresses.size());
    address = addresses.get(0);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 27017", 27017, address.getPort());
    address = addresses.get(1);
    replacedertEquals("should be host: e01sv05", "e01sv05", address.getHost());
    replacedertEquals("should be port: 27018", 27018, address.getPort());
}

19 Source : MongoDbInputTest.java
with Apache License 2.0
from apache

@Test
public void testFindWithMoreResults() throws HopException, MongoDbException {
    // no query or fields defined, should do a collection.find()
    setupReturns();
    when(mockCursor.hasNext()).thenReturn(true);
    ServerAddress serverAddress = mock(ServerAddress.clreplaced);
    when(serverAddress.toString()).thenReturn("serveraddress");
    when(mockCursor.getServerAddress()).thenReturn(serverAddress);
    DBObject nextDoc = (DBObject) JSON.parse("{ 'foo' : 'bar' }");
    when(mockCursor.next()).thenReturn(nextDoc);
    dbInput.setStopped(false);
    dbInput.init();
    replacedertTrue("more results -> should return true", dbInput.processRow());
    verify(mongoCollectionWrapper).find();
    verify(mockCursor).next();
    verify(mockLog).logBasic(stringCaptor.capture());
    replacedertThat(stringCaptor.getValue(), containsString("serveraddress"));
    replacedertThat(iTransformData.cursor, equalTo(mockCursor));
    replacedertThat(putRow[0], CoreMatchers.<Object>equalTo(JSON.serialize(nextDoc)));
}

18 Source : ReactiveMongoClientFactory.java
with Apache License 2.0
from yuanmabiji

private MongoClient createCredentialNetworkMongoClient(MongoClientSettings settings) {
    replacedert.state(this.properties.getUri() == null, "Invalid mongo configuration, " + "either uri or host/port/credentials must be specified");
    Builder builder = builder(settings);
    if (hasCustomCredentials()) {
        applyCredentials(builder);
    }
    String host = getOrDefault(this.properties.getHost(), "localhost");
    int port = getOrDefault(this.properties.getPort(), MongoProperties.DEFAULT_PORT);
    ServerAddress serverAddress = new ServerAddress(host, port);
    builder.applyToClusterSettings((cluster) -> cluster.hosts(Collections.singletonList(serverAddress)));
    return createMongoClient(builder);
}

18 Source : MongoTestMockFactory.java
with Apache License 2.0
from UltimateSoftware

@Primary
@Bean
@Singleton
public MongoClient mongoClient(DefaultReactiveMongoConfiguration defaultReactiveMongoConfiguration) {
    LOG.info("Mocking Mongo Client with embedded memory client.");
    MongoServer server = new MongoServer(new MemoryBackend());
    ServerAddress serverAddress = new ServerAddress(server.bind());
    defaultReactiveMongoConfiguration.setHost(serverAddress);
    return MongoClients.create(defaultReactiveMongoConfiguration.buildSettings());
}

18 Source : MongoStore.java
with Apache License 2.0
from iotaledger

@SuppressWarnings("unchecked")
public clreplaced MongoStore extends DatabaseStore {

    private static final String PENDING = "pending_transfers";

    private static final String DEPOSIT = "deposit_requests";

    private static final String INDEX = "key_index";

    private static final String TAILS = "tail_hashes";

    // Used to deserialize mongodb bson to jackson accepted json
    private static final JsonWriterSettings settings = JsonWriterSettings.builder().int64Converter((value, writer) -> writer.writeNumber(value.toString())).dateTimeConverter((value, writer) -> writer.writeString(value + "")).build();

    private MongoClientOptions options;

    private List<MongoCredential> credentials;

    private ServerAddress address;

    private MongoClient client;

    private MongoCollection<Doreplacedent> collection;

    private MongoDatabase database;

    private UpdateOptions updateOptions;

    public MongoStore() {
        this(IotaDefaultConfig.Defaults.DATABASE_NAME, IotaDefaultConfig.Defaults.TABLE_NAME, "localhost", 27017);
    }

    public MongoStore(String databaseName) {
        this(databaseName, IotaDefaultConfig.Defaults.TABLE_NAME, "localhost", 27017);
    }

    public MongoStore(String databaseName, String tableName) {
        this(databaseName, tableName, "localhost", 27017);
    }

    public MongoStore(String databaseName, String tableName, String hostName) {
        this(databaseName, tableName, hostName, 27017);
    }

    public MongoStore(String databaseName, String tableName, URL databaseUrl) {
        this(databaseName, tableName, databaseUrl.getHost(), databaseUrl.getPort());
    }

    public MongoStore(String databaseName, String tableName, String hostName, int port) {
        super(databaseName, tableName);
        this.address = new ServerAddress(hostName, port);
        this.updateOptions = new UpdateOptions().upsert(true);
        List<Convention> conventions = new LinkedList<>(Conventions.DEFAULT_CONVENTIONS);
        conventions.add(new SnakeConvention());
        PojoCodecProvider.Builder builder = PojoCodecProvider.builder();
        builder.register(StringAccountState.clreplaced);
        builder.conventions(conventions);
        CodecRegistry codecRegistry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(), CodecRegistries.fromProviders(PojoCodecProvider.builder().conventions(conventions).automatic(true).build()));
        this.options = MongoClientOptions.builder().codecRegistry(codecRegistry).build();
    }

    /**
     * Adds a credential to the mongodb connection.
     * Must be added before {@link #load()}
     * @param userName
     * @param preplacedword
     */
    public void addCredentials(String userName, String preplacedword) {
        addCredentials(userName, preplacedword, getDatabaseName());
    }

    public void addCredentials(String userName, String preplacedword, String database) {
        if (credentials == null) {
            credentials = new LinkedList<>();
        }
        credentials.add(MongoCredential.createCredential(userName, database, preplacedword.toCharArray()));
    }

    public void setOptions(MongoClientOptions options) {
        this.options = options;
    }

    @Override
    public void load() {
    // Cannot load anything since calling client.stop() ends the client opject for further use
    }

    @Override
    public boolean start() {
        if (credentials != null) {
            client = new MongoClient(address, credentials, options);
        } else {
            client = new MongoClient(address, options);
        }
        database = client.getDatabase(getDatabaseName());
        try {
            collection = database.getCollection(getTableName());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            try {
                database.createCollection(getTableName());
                collection = database.getCollection(getTableName());
            } catch (IllegalArgumentException e2) {
                // TODO Log account error
                e2.printStackTrace();
                return false;
            }
        }
        return true;
    }

    @Override
    public void shutdown() {
        collection = null;
        database = null;
        if (client != null) {
            client.close();
        }
    }

    @Override
    public AccountState loadAccount(String id) {
        StringAccountState state = collection.find(Filters.eq("_id", id), StringAccountState.clreplaced).projection(Projections.excludeId()).first();
        AccountState accState;
        if (null == state) {
            accState = new AccountState();
            saveAccount(id, accState);
        } else {
            accState = state.toAccountState();
        }
        return accState;
    }

    @Override
    public void saveAccount(String id, AccountState state) {
        Doreplacedent doc = new Doreplacedent(id, new StringAccountState(state));
        UpdateResult result = collection.replaceOne(Filters.eq("_id", id), doc, updateOptions);
        if (result.isModifiedCountAvailable() && result.getModifiedCount() == 0) {
        // TODO Log account error
        }
    }

    @Override
    public void removeAccount(String id) {
        DeleteResult result = collection.deleteOne(Filters.eq("_id", id));
        if (result.getDeletedCount() == 0) {
        // TODO Log account error
        }
    }

    @Override
    public int readIndex(String id) {
        Doreplacedent index = collection.find(Filters.eq("_id", id)).projection(Projections.fields(Projections.include(INDEX))).first();
        return index != null && index.containsKey(INDEX) ? index.getInteger(INDEX) : -1;
    }

    @Override
    public void writeIndex(String id, int index) {
        UpdateResult result = collection.updateOne(Filters.eq("_id", id), new Doreplacedent("$set", new Doreplacedent(INDEX, index)), updateOptions);
        if (result.isModifiedCountAvailable() && result.getModifiedCount() == 0) {
        // TODO Log account error
        }
    }

    @Override
    public void addDepositAddress(String id, int index, StoredDepositAddress request) {
        UpdateResult result = collection.updateOne(Filters.eq("_id", id), new Doreplacedent("$set", new Doreplacedent(DEPOSIT, new Doreplacedent(index + "", request))), updateOptions);
        if (result == null) {
        // TODO Log account error
        }
    }

    @Override
    public void removeDepositAddress(String id, int index) {
        UpdateResult result = collection.updateOne(Filters.eq("_id", id), new Doreplacedent("$unset", new Doreplacedent(DEPOSIT, new Doreplacedent(index + "", ""))), updateOptions);
        if (result == null) {
        // TODO Log account error
        }
    }

    @Override
    public Map<Integer, StoredDepositAddress> getDepositAddresses(String id) {
        Doreplacedent requests = collection.find(Filters.eq("_id", id)).projection(Projections.fields(Projections.include(DEPOSIT))).first();
        Map<Integer, StoredDepositAddress> deposits = null;
        if (requests != null) {
            Map<String, Doreplacedent> strDeposits = requests.get(DEPOSIT, Map.clreplaced);
            deposits = new java.util.HashMap<>();
            if (strDeposits != null) {
                for (Entry<String, Doreplacedent> entry : strDeposits.entrySet()) {
                    BsonDoreplacedent store = entry.getValue().toBsonDoreplacedent(StoredDepositAddress.clreplaced, collection.getCodecRegistry());
                    try {
                        // Get custom Reverse snake parser, read Doreplacedent as bson using custom builder
                        StoredDepositAddress dep = JsonParser.get().getObjectMapper().readValue(store.toJson(settings), StoredDepositAddress.clreplaced);
                        deposits.put(Integer.valueOf(entry.getKey()), dep);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        return deposits;
    }

    @Override
    public void addPendingTransfer(String id, Hash tailTx, Trytes[] bundleTrytes, int... indices) {
        PendingTransfer transfer = new PendingTransfer(super.trytesToTrits(bundleTrytes));
        transfer.addTail(tailTx);
        UpdateResult result = collection.updateOne(Filters.eq("_id", id), new Doreplacedent("$set", new Doreplacedent(PENDING, new Doreplacedent(tailTx.getHash(), transfer))), updateOptions);
        if (result.isModifiedCountAvailable() && result.getModifiedCount() == 0) {
        // TODO Log account error
        }
    }

    @Override
    public void removePendingTransfer(String id, Hash tailHash) {
        UpdateResult result = collection.updateOne(Filters.eq("_id", id), new Doreplacedent("$unset", new Doreplacedent(PENDING, new Doreplacedent(tailHash.getHash(), ""))), updateOptions);
        if (result == null) {
        // TODO Log account error
        }
    }

    @Override
    public void addTailHash(String id, Hash tailHash, Hash newTailTxHash) {
        UpdateResult result = collection.updateOne(Filters.eq("_id", id), new Doreplacedent("$push", new Doreplacedent(PENDING + "." + tailHash.getHash() + "." + TAILS, newTailTxHash)), updateOptions);
        if (result == null) {
        // TODO Log account error
        }
    }

    @Override
    public Map<String, PendingTransfer> getPendingTransfers(String id) {
        Doreplacedent requests = collection.find(Filters.eq("_id", id)).projection(Projections.fields(Projections.include(PENDING))).first();
        Map<String, Doreplacedent> requestsMap = requests.get(PENDING, Map.clreplaced);
        Map<String, PendingTransfer> pendingTransfers = new java.util.HashMap<>();
        if (requestsMap != null) {
            for (Entry<String, Doreplacedent> entry : requestsMap.entrySet()) {
                BsonDoreplacedent store = entry.getValue().toBsonDoreplacedent(PendingTransfer.clreplaced, collection.getCodecRegistry());
                try {
                    // Get custom Reverse snake parser, read Doreplacedent as bson using custom builder
                    PendingTransfer dep = JsonParser.get().getObjectMapper().readValue(store.toJson(settings), PendingTransfer.clreplaced);
                    pendingTransfers.put(entry.getKey(), dep);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return pendingTransfers;
    }

    @Override
    public void importAccount(ExportedAccountState state) {
        saveAccount(state.getId(), state.getState());
    }

    @Override
    public ExportedAccountState exportAccount(String id) {
        AccountState state = loadAccount(id);
        return new ExportedAccountState(new Date(), id, state);
    }

    public MongoCollection<Doreplacedent> getCollection() {
        return collection;
    }

    private clreplaced SnakeConvention implements Convention {

        @Override
        public void apply(ClreplacedModelBuilder<?> clreplacedModelBuilder) {
            for (PropertyModelBuilder<?> fieldModelBuilder : clreplacedModelBuilder.getPropertyModelBuilders()) {
                fieldModelBuilder.discriminatorEnabled(false);
                fieldModelBuilder.readName(fieldModelBuilder.getName().replaceAll("([^_A-Z])([A-Z])", "$1_$2").toLowerCase());
                fieldModelBuilder.writeName(fieldModelBuilder.getName().replaceAll("([^_A-Z])([A-Z])", "$1_$2").toLowerCase());
            }
        }
    }

    private clreplaced StringAccountState {

        int keyIndex;

        Map<String, PendingTransfer> pendingTransfers;

        Map<String, StoredDepositAddress> depositRequests;

        public StringAccountState(AccountState state) {
            keyIndex = state.getKeyIndex();
            pendingTransfers = state.getPendingTransfers();
            depositRequests = new java.util.HashMap<>();
            for (Entry<Integer, StoredDepositAddress> entry : state.getDepositRequests().entrySet()) {
                depositRequests.put(entry.getKey() + "", entry.getValue());
            }
        }

        public AccountState toAccountState() {
            Map<Integer, StoredDepositAddress> depositRequests = new java.util.HashMap<>();
            for (Entry<String, StoredDepositAddress> entry : this.depositRequests.entrySet()) {
                depositRequests.put(Integer.valueOf(entry.getKey()), entry.getValue());
            }
            return new AccountState(keyIndex, depositRequests, pendingTransfers);
        }
    }
}

18 Source : ExtentKlovReporter.java
with Apache License 2.0
from extent-framework

/**
 * Initializes the Mongo DB connection with a {@link ServerAddress} and
 * {@link MongoClientOptions}
 *
 * @param addr
 *            A list of {@link ServerAddress} server addresses
 * @param options
 *            {@link MongoClientOptions} options
 * @return a {@link ExtentKlovReporter} object
 */
public ExtentKlovReporter initMongoDbConnection(ServerAddress addr, MongoClientOptions options) {
    mongoClient = new MongoClient(addr, options);
    return this;
}

18 Source : ConnectionInstrumentation.java
with Apache License 2.0
from elastic

@Nullable
@Advice.OnMethodEnter(suppress = Throwable.clreplaced)
public static Span onEnter(@Advice.This Connection thiz, @Advice.Argument(0) MongoNamespace namespace, @Advice.Origin("#m") String methodName) {
    Span span = null;
    final AbstractSpan<?> activeSpan = tracer.getActive();
    if (activeSpan != null && !activeSpan.isExit()) {
        span = activeSpan.createExitSpan();
    }
    if (span == null) {
        return null;
    }
    span.withType("db").withSubtype("mongodb").getContext().getDb().withType("mongodb");
    span.getContext().getDestination().getService().withName("mongodb").withResource("mongodb").withType("db");
    ServerAddress serverAddress = thiz.getDescription().getServerAddress();
    span.getContext().getDestination().withAddress(serverAddress.getHost()).withPort(serverAddress.getPort());
    String command = methodName;
    if (methodName.equals("query")) {
        // if the method name is query, that corresponds to the find command
        command = "find";
    }
    span.withAction(command);
    StringBuilder spanName = span.getAndOverrideName(AbstractSpan.PRIO_DEFAULT);
    if (spanName != null) {
        int indexOfCommand = command.indexOf("Command");
        spanName.append(namespace.getDatabaseName()).append(".").append(namespace.getCollectionName()).append(".").append(command, 0, indexOfCommand > 0 ? indexOfCommand : command.length());
    }
    span.activate();
    return span;
}

18 Source : ConnectionAdvice.java
with Apache License 2.0
from elastic

@Nullable
@Advice.OnMethodEnter(suppress = Throwable.clreplaced)
public static Span onEnter(@Advice.This Connection thiz, @Advice.Argument(0) Object databaseOrMongoNamespace, @Advice.Argument(1) BsonDoreplacedent command) {
    Span span = null;
    final AbstractSpan<?> activeSpan = GlobalTracer.get().getActive();
    if (activeSpan != null && !activeSpan.isExit()) {
        span = activeSpan.createExitSpan();
    }
    if (span == null) {
        return null;
    }
    String database = "";
    String collection = null;
    if (databaseOrMongoNamespace instanceof String) {
        database = (String) databaseOrMongoNamespace;
    } else if (databaseOrMongoNamespace instanceof MongoNamespace) {
        MongoNamespace namespace = (MongoNamespace) databaseOrMongoNamespace;
        database = namespace.getDatabaseName();
        collection = namespace.getCollectionName();
    }
    span.withType("db").withSubtype("mongodb").appendToName(database).getContext().getDb().withType("mongodb");
    span.getContext().getDestination().getService().withName("mongodb").withResource("mongodb").withType("db");
    ServerAddress serverAddress = thiz.getDescription().getServerAddress();
    span.getContext().getDestination().withAddress(serverAddress.getHost()).withPort(serverAddress.getPort());
    try {
        String cmd = // try to determine main commands in a garbage free way
        command.containsKey("find") ? "find" : command.containsKey("insert") ? "insert" : command.containsKey("count") ? "count" : command.containsKey("drop") ? "drop" : command.containsKey("update") ? "update" : command.containsKey("delete") ? "delete" : command.containsKey("create") ? "create" : command.containsKey("getMore") ? "getMore" : // fall back to getting the first key which is the command name
        // by allocating a key set and an iterator
        command.keySet().iterator().next();
        if (collection == null) {
            BsonValue collectionName = command.get(cmd);
            if (collectionName != null && collectionName.isString()) {
                collection = collectionName.replacedtring().getValue();
                span.appendToName(".").appendToName(collection);
            }
        }
        if (collection == null) {
            BsonValue collectionName = command.get("collection");
            if (collectionName != null && collectionName.isString()) {
                collection = collectionName.replacedtring().getValue();
                span.appendToName(".").appendToName(collection);
            }
        }
        span.appendToName(".").appendToName(cmd).withAction(cmd);
    } catch (RuntimeException e) {
        logger.error("Exception while determining MongoDB command and collection", e);
    }
    span.activate();
    return span;
}

18 Source : MongoDbInput.java
with Apache License 2.0
from apache

@Override
public boolean processRow() throws HopException {
    try {
        if (meta.getExecuteForEachIncomingRow() && m_currentInputRowDrivingQuery == null) {
            m_currentInputRowDrivingQuery = getRow();
            if (m_currentInputRowDrivingQuery == null) {
                // no more input, no more queries to make
                setOutputDone();
                return false;
            }
            if (!first) {
                initQuery();
            }
        }
        if (first) {
            data.outputRowMeta = new RowMeta();
            meta.getFields(data.outputRowMeta, getTransformName(), null, null, MongoDbInput.this, metadataProvider);
            initQuery();
            first = false;
            data.init();
        }
        boolean hasNext = ((meta.isQueryIsPipeline() ? data.m_pipelineResult.hasNext() : data.cursor.hasNext()) && !isStopped());
        if (hasNext) {
            DBObject nextDoc = null;
            Object[] row = null;
            if (meta.isQueryIsPipeline()) {
                nextDoc = data.m_pipelineResult.next();
            } else {
                nextDoc = data.cursor.next();
            }
            if (!meta.isQueryIsPipeline() && !m_serverDetermined) {
                ServerAddress s = data.cursor.getServerAddress();
                if (s != null) {
                    m_serverDetermined = true;
                    logBasic(BaseMessages.getString(PKG, "MongoDbInput.Message.QueryPulledDataFrom", s.toString()));
                }
            }
            if (meta.isOutputJson() || meta.getMongoFields() == null || meta.getMongoFields().size() == 0) {
                String json = JSON.serialize(nextDoc);
                row = RowDataUtil.allocateRowData(data.outputRowMeta.size());
                int index = 0;
                row[index++] = json;
                putRow(data.outputRowMeta, row);
            } else {
                Object[][] outputRows = data.mongoDoreplacedentToHop(nextDoc, MongoDbInput.this);
                // there may be more than one row if the paths contain an array
                // unwind
                for (int i = 0; i < outputRows.length; i++) {
                    putRow(data.outputRowMeta, outputRows[i]);
                }
            }
        } else {
            if (!meta.getExecuteForEachIncomingRow()) {
                setOutputDone();
                return false;
            } else {
                // finished with this row
                m_currentInputRowDrivingQuery = null;
            }
        }
        return true;
    } catch (Exception e) {
        if (e instanceof HopException) {
            throw (HopException) e;
        } else {
            throw new HopException(e);
        }
    }
}

17 Source : ReactiveMongoClientFactory.java
with Apache License 2.0
from hello-shf

private MongoClient createCredentialNetworkMongoClient(MongoClientSettings settings) {
    replacedert.state(this.properties.getUri() == null, "Invalid mongo configuration, " + "either uri or host/port/credentials must be specified");
    Builder builder = builder(settings);
    if (hasCustomCredentials()) {
        applyCredentials(builder);
    }
    String host = getOrDefault(this.properties.getHost(), "localhost");
    int port = getOrDefault(this.properties.getPort(), MongoProperties.DEFAULT_PORT);
    ServerAddress serverAddress = new ServerAddress(host, port);
    builder.clusterSettings(ClusterSettings.builder().hosts(Collections.singletonList(serverAddress)).build());
    return createMongoClient(builder);
}

17 Source : NoAuthMongoClientWrapper.java
with Apache License 2.0
from apache

private List<ServerAddress> getServerAddressList() throws MongoDbException {
    String hostsPorts = props.get(MongoProp.HOST);
    String singlePort = props.get(MongoProp.PORT);
    int singlePortI = -1;
    try {
        singlePortI = Integer.parseInt(singlePort);
    } catch (NumberFormatException n) {
    // don't complain
    }
    if (Util.isEmpty(hostsPorts)) {
        throw new MongoDbException(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Error.EmptyHostsString"));
    }
    List<ServerAddress> serverList = new ArrayList<>();
    String[] parts = hostsPorts.trim().split(",");
    for (String part : parts) {
        // host:port?
        int port = singlePortI != -1 ? singlePortI : MONGO_DEFAULT_PORT;
        String[] hp = part.split(":");
        if (hp.length > 2) {
            throw new MongoDbException(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Error.MalformedHost", part));
        }
        String host = hp[0];
        if (hp.length == 2) {
            // non-default port
            try {
                port = Integer.parseInt(hp[1].trim());
            } catch (NumberFormatException n) {
                throw new MongoDbException(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Error.UnableToParsePortNumber", hp[1]));
            }
        }
        try {
            ServerAddress s = new ServerAddress(host, port);
            serverList.add(s);
        } catch (Throwable u) {
            throw new MongoDbException(u);
        }
    }
    return serverList;
}

16 Source : MongoClientTracer.java
with Apache License 2.0
from open-telemetry

@Override
protected String dbConnectionString(CommandStartedEvent event) {
    ConnectionDescription connectionDescription = event.getConnectionDescription();
    if (connectionDescription != null) {
        ServerAddress sa = connectionDescription.getServerAddress();
        if (sa != null) {
            // https://docs.mongodb.com/manual/reference/connection-string/
            String host = sa.getHost();
            int port = sa.getPort();
            if (host != null && port != 0) {
                return "mongodb://" + host + ":" + port;
            }
        }
    }
    return null;
}

16 Source : DBusMongoClient.java
with Apache License 2.0
from BriData

private List<ServerAddress> seeds(String url) {
    if (StringUtils.isBlank(url))
        throw new IllegalArgumentException("mongo url is empty.");
    List<ServerAddress> seeds = new ArrayList<>();
    for (String str : url.split(",")) {
        if (StringUtils.startsWith(str, "mongodb://")) {
            str = StringUtils.replace(str, "mongodb://", "");
        }
        String[] ipAndPort = StringUtils.split(str, ":");
        ServerAddress sa = new ServerAddress(new InetSocketAddress(ipAndPort[0], Integer.valueOf(ipAndPort[1])));
        seeds.add(sa);
    }
    return seeds;
}

16 Source : ServerConnection.java
with Apache License 2.0
from 597365581

public static String buildUrlString(ArrayList<ServerAddress> servers) {
    StringBuilder buf = new StringBuilder(100);
    Iterator i$ = servers.iterator();
    while (i$.hasNext()) {
        ServerAddress a = (ServerAddress) i$.next();
        buf.append(a.getHost());
        buf.append(":");
        buf.append(a.getPort());
    }
    return buf.toString();
}

See More Examples