Java Code Examples for com.mongodb.ServerAddress

The following examples show how to use com.mongodb.ServerAddress. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: ExecDashboard   Source File: DefaultHygieiaServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public MongoClient getMongoClient(BunitCredentials bunitCredential) {
	try {
		if (bunitCredential != null) {
			ServerAddress serverAddr = new ServerAddress(bunitCredential.getHost(), bunitCredential.getPort());

			MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(
					bunitCredential.getDbUserName(), bunitCredential.getDbName(),
					bunitCredential.getDbUserCredentials().toCharArray());
			MongoClient client = new MongoClient(serverAddr, Collections.singletonList(mongoCredential));
			return client;
		}
	} catch (Exception e) {
		LOG.error(e.getMessage());
	}
	return null;
}
 
Example 2
Source Project: Lottor   Source File: MongoTransactionOperateRepository.java    License: MIT License 6 votes vote down vote up
/**
 * 生成mongoClientFacotryBean
 *
 * @param config 配置信息
 * @return bean
 */
private MongoClientFactoryBean buildMongoClientFactoryBean(TxMongoConfig config) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(config.getMongoUserName(),
            config.getMongoDbName(),
            config.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{
            credential
    });
    List<String> urls = Splitter.on(",").trimResults().splitToList(config.getMongoDbUrl());
    final ServerAddress[] serverAddresses = urls.stream().filter(Objects::nonNull)
            .map(url -> {
                List<String> adds = Splitter.on(":").trimResults().splitToList(url);
                return new ServerAddress(adds.get(0), Integer.valueOf(adds.get(1)));
            }).collect(Collectors.toList()).toArray(new ServerAddress[urls.size()]);

    clientFactoryBean.setReplicaSetSeeds(serverAddresses);
    return clientFactoryBean;
}
 
Example 3
Source Project: nuls-v2   Source File: MongoDBService.java    License: MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
    try {
        long time1, time2;
        time1 = System.currentTimeMillis();
        MongoClientOptions options = MongoClientOptions.builder()
                .connectionsPerHost(ApiContext.maxAliveConnect)
                .threadsAllowedToBlockForConnectionMultiplier(ApiContext.maxAliveConnect)
                .socketTimeout(ApiContext.socketTimeout)
                .maxWaitTime(ApiContext.maxWaitTime)
                .connectTimeout(ApiContext.connectTimeOut)
                .build();
        ServerAddress serverAddress = new ServerAddress(ApiContext.databaseUrl, ApiContext.databasePort);
        MongoClient mongoClient = new MongoClient(serverAddress, options);
        MongoDatabase mongoDatabase = mongoClient.getDatabase(DATABASE_NAME);

        mongoDatabase.getCollection(TEST_TABLE).drop();
        time2 = System.currentTimeMillis();
        LoggerUtil.commonLog.info("------connect mongodb use time:" + (time2 - time1));
        this.client = mongoClient;
        this.db = mongoDatabase;
    } catch (Exception e) {
        LoggerUtil.commonLog.error(e);
        System.exit(-1);
    }
}
 
Example 4
Source Project: iot-dc3   Source File: MongoConfig.java    License: Apache License 2.0 6 votes vote down vote up
public MongoDbFactory mongoDbFactory(MongoClientOptionProperties properties) {
    //创建客户端参数
    MongoClientOptions options = mongoClientOptions(properties);

    //创建客户端和Factory
    List<ServerAddress> serverAddresses = new ArrayList<>();
    for (String address : properties.getAddress()) {
        String[] hostAndPort = address.split(":");
        String host = hostAndPort[0];
        int port = Integer.parseInt(hostAndPort[1]);
        ServerAddress serverAddress = new ServerAddress(host, port);
        serverAddresses.add(serverAddress);
    }

    //创建认证客户端
    MongoCredential mongoCredential = MongoCredential
            .createScramSha1Credential(
                    properties.getUsername(),
                    properties.getAuthenticationDatabase() != null ? properties.getAuthenticationDatabase() : properties.getDatabase(),
                    properties.getPassword().toCharArray()
            );
    MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, options);

    return new SimpleMongoDbFactory(mongoClient, properties.getDatabase());
}
 
Example 5
Source Project: quarkus   Source File: MongoClients.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void apply(ClusterSettings.Builder builder) {
    Optional<String> maybeConnectionString = config.connectionString;
    if (!maybeConnectionString.isPresent()) {
        // Parse hosts
        List<ServerAddress> hosts = parseHosts(config.hosts);
        builder.hosts(hosts);

        if (hosts.size() == 1 && !config.replicaSetName.isPresent()) {
            builder.mode(ClusterConnectionMode.SINGLE);
        } else {
            builder.mode(ClusterConnectionMode.MULTIPLE);
        }
    }
    if (config.localThreshold.isPresent()) {
        builder.localThreshold(config.localThreshold.get().toMillis(), TimeUnit.MILLISECONDS);
    }

    config.replicaSetName.ifPresent(builder::requiredReplicaSetName);

    if (config.serverSelectionTimeout.isPresent()) {
        builder.serverSelectionTimeout(config.serverSelectionTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }
}
 
Example 6
Source Project: elepy   Source File: Main.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    MongoServer mongoServer = new MongoServer(new MemoryBackend());

    InetSocketAddress serverAddress = mongoServer.bind();

    MongoClient client = new MongoClient(new ServerAddress(serverAddress));

    final var elepyInstance = new Elepy()
            .addConfiguration(MongoConfiguration.of(client, "example", "bucket"))
            .withPort(7331)
            .addModelPackage("com.elepy.tests.devfrontend")
            .addExtension((http, elepy) -> {
                http.before(context -> {
                    context.response().header("Access-Control-Allow-Headers", "*");
                    context.request().addPermissions(Permissions.SUPER_USER);
                });
            })
            .addExtension(new FrontendLoader());
    elepyInstance.start();

}
 
Example 7
Source Project: helper   Source File: HelperMongo.java    License: MIT License 6 votes vote down vote up
public HelperMongo(@Nonnull MongoDatabaseCredentials credentials) {
    MongoCredential mongoCredential = MongoCredential.createCredential(
            credentials.getUsername(),
            credentials.getDatabase(),
            credentials.getPassword().toCharArray()
    );

    this.client = new MongoClient(
            new ServerAddress(credentials.getAddress(), credentials.getPort()),
            mongoCredential,
            MongoClientOptions.builder().build()
    );
    this.database = this.client.getDatabase(credentials.getDatabase());
    this.morphia = new Morphia();
    this.morphiaDatastore = this.morphia.createDatastore(this.client, credentials.getDatabase());
    this.morphia.getMapper().getOptions().setObjectFactory(new DefaultCreator() {
        @Override
        protected ClassLoader getClassLoaderForClass() {
            return LoaderUtils.getPlugin().getClassloader();
        }
    });
}
 
Example 8
private MongoClientFactoryBean buildMongoClientFactoryBean(final TxMongoConfig config) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(config.getMongoUserName(),
            config.getMongoDbName(),
            config.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{credential});
    List<String> urls = Splitter.on(",").trimResults().splitToList(config.getMongoDbUrl());
    final ServerAddress[] serverAddresses = urls.stream().filter(Objects::nonNull)
            .map(url -> {
                List<String> adds = Splitter.on(":").trimResults().splitToList(url);
                return new ServerAddress(adds.get(0), Integer.valueOf(adds.get(1)));
            }).collect(Collectors.toList()).toArray(new ServerAddress[urls.size()]);

    clientFactoryBean.setReplicaSetSeeds(serverAddresses);
    return clientFactoryBean;
}
 
Example 9
Source Project: hmily   Source File: MongoCoordinatorRepository.java    License: Apache License 2.0 6 votes vote down vote up
private MongoClientFactoryBean buildMongoClientFactoryBean(final HmilyMongoConfig hmilyMongoConfig) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(hmilyMongoConfig.getMongoUserName(),
            hmilyMongoConfig.getMongoDbName(),
            hmilyMongoConfig.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{credential});

    List<String> urls = Lists.newArrayList(Splitter.on(",").trimResults().split(hmilyMongoConfig.getMongoDbUrl()));
    ServerAddress[] sds = new ServerAddress[urls.size()];
    for (int i = 0; i < sds.length; i++) {
        List<String> adds = Lists.newArrayList(Splitter.on(":").trimResults().split(urls.get(i)));
        InetSocketAddress address = new InetSocketAddress(adds.get(0), Integer.parseInt(adds.get(1)));
        sds[i] = new ServerAddress(address);
    }
    clientFactoryBean.setReplicaSetSeeds(sds);
    return clientFactoryBean;
}
 
Example 10
Source Project: jpa-unit   Source File: EclipseLinkConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("eclipselink.nosql.property.mongo.db", "foo");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(1));
    assertThat(serverAddresses, hasItems(new ServerAddress("127.0.0.1")));
}
 
Example 11
Source Project: scava   Source File: Configuration.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public Mongo getMongoConnection() throws UnknownHostException {

	if (this.mongo == null) {
		String[] hosts = properties.getProperty(MONGO_HOSTS, "localhost:27017").split(",");
		
		if (hosts.length > 1) {
			List<ServerAddress> mongoHostAddresses = new ArrayList<>();
			for (String host : hosts) {
				String[] s = host.split(":");
				mongoHostAddresses.add(new ServerAddress(s[0], Integer.valueOf(s[1])));
			}
			
			this.mongo = new Mongo(mongoHostAddresses);
			
		} else {
			this.mongo = new Mongo();//hosts[0]);
		}
	}

	return this.mongo;
}
 
Example 12
Source Project: ditto   Source File: MongoClientWrapperTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static void assertWithExpected(final DittoMongoClient mongoClient, final boolean sslEnabled,
        final boolean withCredentials) {

    final MongoClientSettings mongoClientSettings = mongoClient.getSettings();
    assertThat(mongoClientSettings.getClusterSettings().getHosts())
            .isEqualTo(Collections.singletonList(new ServerAddress(KNOWN_SERVER_ADDRESS)));

    final List<MongoCredential> expectedCredentials = withCredentials ? Collections.singletonList(
            MongoCredential.createCredential(KNOWN_USER, KNOWN_DB_NAME, KNOWN_PASSWORD.toCharArray())) :
            Collections.emptyList();
    assertThat(mongoClientSettings.getCredentialList()).isEqualTo(
            expectedCredentials);
    assertThat(mongoClientSettings.getSslSettings().isEnabled()).isEqualTo(sslEnabled);

    final MongoDatabase mongoDatabase = mongoClient.getDefaultDatabase();
    assertThat(mongoDatabase).isNotNull();
    assertThat(mongoDatabase.getName()).isEqualTo(KNOWN_DB_NAME);
}
 
Example 13
Source Project: ditto   Source File: BulkWriteResultAckFlowTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void partialSuccess() {
    final List<AbstractWriteModel> writeModels = generate5WriteModels();
    final BulkWriteResult result = BulkWriteResult.acknowledged(1, 2, 1, 2, List.of());
    final List<BulkWriteError> updateFailure = List.of(
            new BulkWriteError(11000, "E11000 duplicate key error", new BsonDocument(), 3),
            new BulkWriteError(50, "E50 operation timed out", new BsonDocument(), 4)
    );

    // WHEN: BulkWriteResultAckFlow receives partial update success with errors, one of which is not duplicate key
    final WriteResultAndErrors resultAndErrors = WriteResultAndErrors.failure(writeModels,
            new MongoBulkWriteException(result, updateFailure, null, new ServerAddress()));
    final String message = runBulkWriteResultAckFlowAndGetFirstLogEntry(resultAndErrors);

    // THEN: the non-duplicate-key error triggers a failure acknowledgement
    actorSystem.log().info(message);
    for (int i = 3; i < 5; ++i) {
        assertThat(expectUpdateThingResponse(writeModels.get(i).getMetadata().getThingId()))
                .describedAs("response is failure")
                .returns(false, UpdateThingResponse::isSuccess);
    }
    assertThat(message).contains("Acknowledged: PartialSuccess");
}
 
Example 14
Source Project: ditto   Source File: BulkWriteResultAckFlowTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void unexpectedMongoSocketReadException() {
    final List<AbstractWriteModel> writeModels = generate5WriteModels();

    // WHEN: BulkWriteResultAckFlow receives unexpected error
    final WriteResultAndErrors resultAndErrors = WriteResultAndErrors.unexpectedError(writeModels,
            new MongoSocketReadException("Gee, database is down. Whatever shall I do?", new ServerAddress(),
                    new IllegalMonitorStateException("Unsupported resolution")));
    final String message = runBulkWriteResultAckFlowAndGetFirstLogEntry(resultAndErrors);

    // THEN: all ThingUpdaters receive negative acknowledgement.
    actorSystem.log().info(message);
    for (final AbstractWriteModel writeModel : writeModels) {
        assertThat(expectUpdateThingResponse(writeModel.getMetadata().getThingId()))
                .describedAs("response is failure")
                .returns(false, UpdateThingResponse::isSuccess);
    }
    assertThat(message).contains("NotAcknowledged: UnexpectedError", "MongoSocketReadException");
}
 
Example 15
Source Project: ditto   Source File: BulkWriteResultAckFlowTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void errorIndexOutOfBoundError() {
    final List<AbstractWriteModel> writeModels = generate5WriteModels();
    final BulkWriteResult result = BulkWriteResult.acknowledged(1, 2, 1, 2, List.of());
    final List<BulkWriteError> updateFailure = List.of(
            new BulkWriteError(11000, "E11000 duplicate key error", new BsonDocument(), 0),
            new BulkWriteError(50, "E50 operation timed out", new BsonDocument(), 5)
    );

    // WHEN: BulkWriteResultAckFlow receives partial update success with at least 1 error with out-of-bound index
    final WriteResultAndErrors resultAndErrors = WriteResultAndErrors.failure(writeModels,
            new MongoBulkWriteException(result, updateFailure, null, new ServerAddress()));
    final String message = runBulkWriteResultAckFlowAndGetFirstLogEntry(resultAndErrors);

    // THEN: All updates are considered failures
    actorSystem.log().info(message);
    for (final AbstractWriteModel writeModel : writeModels) {
        final UpdateThingResponse response = expectUpdateThingResponse(writeModel.getMetadata().getThingId());
        assertThat(response).describedAs("response is failure").returns(false, UpdateThingResponse::isSuccess);
    }
    assertThat(message).contains("ConsistencyError[indexOutOfBound]");
}
 
Example 16
Source Project: act   Source File: FreemarkerRenderer.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void init(String dbHost, Integer dbPort, String dbName, String dnaCollection, String pathwayCollection) throws IOException {
  cfg = new Configuration(Configuration.VERSION_2_3_23);

  cfg.setClassLoaderForTemplateLoading(
      this.getClass().getClassLoader(), "/act/installer/reachablesexplorer/templates");
  cfg.setDefaultEncoding("UTF-8");

  cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  cfg.setLogTemplateExceptions(true);

  reachableTemplate = cfg.getTemplate(reachableTemplateName);
  pathwayTemplate = cfg.getTemplate(pathwayTemplateName);

  // TODO: move this elsewhere.
  MongoClient client = new MongoClient(new ServerAddress(dbHost, dbPort));
  DB db = client.getDB(dbName);

  dnaDesignCollection = JacksonDBCollection.wrap(db.getCollection(dnaCollection), DNADesign.class, String.class);
  Cascade.setCollectionName(pathwayCollection);
}
 
Example 17
@Override
public void afterPropertiesSet() throws Exception {

    final IMongodConfig mongodConfig = new MongodConfigBuilder()
            .version(Version.Main.PRODUCTION).build();

    IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder()
            .defaultsWithLogger(Command.MongoD, logger)
            .processOutput(ProcessOutput.getDefaultInstanceSilent())
            .build();

    MongodStarter runtime = MongodStarter.getInstance(runtimeConfig);

    MongodExecutable mongodExecutable = runtime.prepare(mongodConfig);
    mongod = mongodExecutable.start();

    // cluster configuration
    ClusterSettings clusterSettings = ClusterSettings.builder().hosts(Collections.singletonList(new ServerAddress(mongodConfig.net().getServerAddress().getHostName(), mongodConfig.net().getPort()))).build();
    // codec configuration
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));

    MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings).codecRegistry(pojoCodecRegistry).writeConcern(WriteConcern.ACKNOWLEDGED).build();
    mongoClient = MongoClients.create(settings);
    mongoDatabase = mongoClient.getDatabase(databaseName);
}
 
Example 18
@Override
public void afterPropertiesSet() throws Exception {
    final IMongodConfig mongodConfig = new MongodConfigBuilder()
            .version(Version.Main.PRODUCTION).build();

    IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder()
            .defaultsWithLogger(Command.MongoD, logger)
            .processOutput(ProcessOutput.getDefaultInstanceSilent())
            .build();

    MongodStarter runtime = MongodStarter.getInstance(runtimeConfig);

    MongodExecutable mongodExecutable = runtime.prepare(mongodConfig);
    mongod = mongodExecutable.start();

    // cluster configuration
    ClusterSettings clusterSettings = ClusterSettings.builder().hosts(Collections.singletonList(new ServerAddress(mongodConfig.net().getServerAddress().getHostName(), mongodConfig.net().getPort()))).build();
    // codec configuration
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));

    MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings).codecRegistry(pojoCodecRegistry).writeConcern(WriteConcern.ACKNOWLEDGED).build();
    mongoClient = MongoClients.create(settings);
    mongoDatabase = mongoClient.getDatabase(databaseName);
}
 
Example 19
Source Project: konker-platform   Source File: MongoAuditConfig.java    License: Apache License 2.0 6 votes vote down vote up
public MongoAuditConfig() {
   	Map<String, Object> defaultMap = new HashMap<>();
   	defaultMap.put("mongoAudit.hostname", "localhost");
   	defaultMap.put("mongoAudit.port", 27017);
   	defaultMap.put("mongoAudit.username", "");
   	defaultMap.put("mongoAudit.password", "");
   	Config defaultConf = ConfigFactory.parseMap(defaultMap);

   	Config config = ConfigFactory.load().withFallback(defaultConf);
   	setPort(config.getInt("mongoAudit.port"));
   	setUsername(config.getString("mongoAudit.username"));
   	setPassword(config.getString("mongoAudit.password"));

	List<String> seedList = Optional.ofNullable(config.getString("mongoAudit.hostname")).isPresent() ?
			Arrays.asList(config.getString("mongoAudit.hostname").split(",")) : null;

	for (String seed : seedList) {
		try {
			hostname.add(new ServerAddress(seed, port));
		} catch (Exception e) {
			LOG.error("Error constructing mongo factory", e);
		}
	}

}
 
Example 20
Source Project: jpa-unit   Source File: HibernateOgmConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("hibernate.ogm.datastore.database", "foo");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(1));
    assertThat(serverAddresses, hasItems(new ServerAddress("127.0.0.1")));
}
 
Example 21
Source Project: jpa-unit   Source File: HibernateOgmConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("hibernate.ogm.datastore.database", "foo");
    properties.put("hibernate.ogm.datastore.host",
            "www.example.com, www2.example.com:123, 192.0.2.1, 192.0.2.2:123, 2001:db8::ff00:42:8329, [2001:db8::ff00:42:8329]:123 ");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(6));
    assertThat(serverAddresses,
            hasItems(new ServerAddress("www.example.com"), new ServerAddress("www2.example.com", 123), new ServerAddress("192.0.2.1"),
                    new ServerAddress("192.0.2.2", 123), new ServerAddress("2001:db8::ff00:42:8329"),
                    new ServerAddress("[2001:db8::ff00:42:8329]", 123)));
}
 
Example 22
Source Project: MongoDb-Sink-Connector   Source File: MongoWrapper.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 23
Source Project: jpa-unit   Source File: EclipseLinkConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
private void configureServerAddresses(final Map<String, Object> properties) {
    final String ports = (String) properties.get(ECLIPSELINK_NOSQL_PROPERTY_MONGO_PORT);
    final String hosts = (String) properties.get(ECLIPSELINK_NOSQL_PROPERTY_MONGO_HOST);
    final String[] hostList = hosts != null ? hosts.split(",") : new String[] {};
    final String[] portList = ports != null ? ports.split(",") : new String[] {};

    serverAddresses = new ArrayList<>();
    for (int i = 0; i < hostList.length; i++) {
        int port;
        if (i >= portList.length) {
            port = ServerAddress.defaultPort();
        } else {
            port = Integer.valueOf(portList[i].trim());
        }
        serverAddresses.add(new ServerAddress(hostList[i].trim(), port));
    }
    if (serverAddresses.isEmpty()) {
        serverAddresses.add(new ServerAddress());
    }
}
 
Example 24
Source Project: jpa-unit   Source File: KunderaConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
private void configureServerAddresses(final Map<String, Object> properties) {
    final String port = (String) properties.get(KUNDERA_PORT);
    final String hosts = (String) properties.get(KUNDERA_NODES);

    final String[] hostList = hosts != null ? hosts.split(",") : new String[] {};
    final Integer defaultPort = port != null ? Integer.valueOf(port) : 27017;

    serverAddresses = new ArrayList<>();
    for (int i = 0; i < hostList.length; i++) {
        final HostAndPort hostAndPort = HostAndPort.fromString(hostList[i].trim());
        serverAddresses.add(new ServerAddress(hostAndPort.getHost(), hostAndPort.getPortOrDefault(defaultPort)));
    }
    if (serverAddresses.isEmpty()) {
        serverAddresses.add(new ServerAddress());
    }
}
 
Example 25
Source Project: jpa-unit   Source File: KunderaConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("kundera.keyspace", "foo");
    properties.put("kundera.nodes", "www.example.com, 192.0.2.2:123, [2001:db8::ff00:42:8329]:27027, www2.example.com");
    properties.put("kundera.port", "27016");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(4));
    assertThat(serverAddresses, hasItems(new ServerAddress("www.example.com", 27016), new ServerAddress("192.0.2.2", 123),
            new ServerAddress("2001:db8::ff00:42:8329", 27027), new ServerAddress("www2.example.com", 27016)));
}
 
Example 26
Source Project: jpa-unit   Source File: KunderaConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("kundera.keyspace", "foo");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(1));
    assertThat(serverAddresses, hasItems(new ServerAddress("127.0.0.1")));
}
 
Example 27
Source Project: micro-integrator   Source File: MongoConfig.java    License: Apache License 2.0 5 votes vote down vote up
private List<ServerAddress> createServerAddresses(String[] servers) throws Exception {
    List<ServerAddress> result = new ArrayList<>();
    String[] tmpAddr;
    for (String server : servers) {
        tmpAddr = server.split(":");
        if (tmpAddr.length == 2) {
            result.add(new ServerAddress(tmpAddr[0], Integer.parseInt(tmpAddr[1])));
        } else {
            result.add(new ServerAddress(tmpAddr[0]));
        }
    }
    return result;
}
 
Example 28
Source Project: presto   Source File: MongoClientConfig.java    License: Apache License 2.0 5 votes vote down vote up
private List<ServerAddress> buildSeeds(Iterable<String> hostPorts)
{
    ImmutableList.Builder<ServerAddress> builder = ImmutableList.builder();
    for (String hostPort : hostPorts) {
        List<String> values = PORT_SPLITTER.splitToList(hostPort);
        checkArgument(values.size() == 1 || values.size() == 2, "Invalid ServerAddress format. Requires host[:port]");
        if (values.size() == 1) {
            builder.add(new ServerAddress(values.get(0)));
        }
        else {
            builder.add(new ServerAddress(values.get(0), Integer.parseInt(values.get(1))));
        }
    }
    return builder.build();
}
 
Example 29
Source Project: microshed-testing   Source File: MongoProducer.java    License: Apache License 2.0 5 votes vote down vote up
@Produces
public MongoClient createMongo() {
    System.out.println("Create mongo with host=" + MONGO_HOSTNAME + " port=" + MONGO_PORT);
    return new MongoClient(new ServerAddress(MONGO_HOSTNAME, MONGO_PORT), //
                    new MongoClientOptions.Builder()
                                    .connectTimeout(5000)
                                    .maxWaitTime(5000)
                                    .build());
}
 
Example 30
Source Project: jpa-unit   Source File: DataNucleusConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    // mongodb:[{server}][/{dbName}] [,{server2}[,server3}]]

    properties.put("datanucleus.ConnectionURL",
            "mongodb:www.example.com/foo, www2.example.com:123,192.0.2.1, 192.0.2.2:123, 2001:db8::ff00:42:8329, [2001:db8::ff00:42:8329]:123 ");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(6));
    assertThat(serverAddresses,
            hasItems(new ServerAddress("www.example.com"), new ServerAddress("www2.example.com", 123), new ServerAddress("192.0.2.1"),
                    new ServerAddress("192.0.2.2", 123), new ServerAddress("2001:db8::ff00:42:8329"),
                    new ServerAddress("[2001:db8::ff00:42:8329]", 123)));
}