com.mongodb.ServerAddress Java Examples

The following examples show how to use com.mongodb.ServerAddress. 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 File: MongoDBService.java    From nuls-v2 with MIT License 7 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 #2
Source File: EclipseLinkConfigurationTest.java    From jpa-unit with 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 #3
Source File: MongoTransactionOperateRepository.java    From Lottor with 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 #4
Source File: MongoAuditConfig.java    From konker-platform with 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 #5
Source File: HibernateOgmConfigurationTest.java    From jpa-unit with 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 #6
Source File: HibernateOgmConfigurationTest.java    From jpa-unit with 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 #7
Source File: MongoWrapper.java    From MongoDb-Sink-Connector with 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 #8
Source File: DefaultHygieiaServiceImpl.java    From ExecDashboard with 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 #9
Source File: KunderaConfiguration.java    From jpa-unit with 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 #10
Source File: KunderaConfigurationTest.java    From jpa-unit with 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 #11
Source File: KunderaConfigurationTest.java    From jpa-unit with 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 #12
Source File: EclipseLinkConfiguration.java    From jpa-unit with 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 #13
Source File: MongoConfig.java    From iot-dc3 with 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 #14
Source File: EmbeddedClient.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: EmbeddedClient.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: MongoCoordinatorRepository.java    From hmily with 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 #17
Source File: Configuration.java    From scava with 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 #18
Source File: MongoTransactionRecoverRepository.java    From Raincat with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #19
Source File: HelperMongo.java    From helper with 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 #20
Source File: Main.java    From elepy with 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 #21
Source File: MongoClientWrapperTest.java    From ditto with 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 #22
Source File: BulkWriteResultAckFlowTest.java    From ditto with 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 #23
Source File: BulkWriteResultAckFlowTest.java    From ditto with 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 #24
Source File: BulkWriteResultAckFlowTest.java    From ditto with 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 #25
Source File: FreemarkerRenderer.java    From act with 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 #26
Source File: MongoClients.java    From quarkus with 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 #27
Source File: MongoConfig.java    From micro-integrator with 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 File: MongodManager.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void initializeReplicaSet(final List<IMongodConfig> mongodConfigList) throws UnknownHostException, InterruptedException {
    Thread.sleep(1000);
    final MongoClientOptions mo = MongoClientOptions.builder().connectTimeout(10).build();
    final ServerAddress arbitrerAddress = new ServerAddress(mongodConfigList.get(0).net().getServerAddress().getHostName(),
            mongodConfigList.get(0).net().getPort());

    try (MongoClient mongo = new MongoClient(arbitrerAddress, mo)) {
        final MongoDatabase mongoAdminDB = mongo.getDatabase("admin");

        Document cr = mongoAdminDB.runCommand(new Document("isMaster", 1));
        LOGGER.info("isMaster: {}", cr);

        // Build replica set configuration settings
        final Document rsConfiguration = buildReplicaSetConfiguration(mongodConfigList);
        LOGGER.info("replSetSettings: {}", rsConfiguration);

        // Initialize replica set
        cr = mongoAdminDB.runCommand(new Document("replSetInitiate", rsConfiguration));
        LOGGER.info("replSetInitiate: {}", cr);

        // Check replica set status before to proceed
        int maxWaitRounds = 10;
        do {
            LOGGER.info("Waiting for 1 second...");
            Thread.sleep(1000);
            cr = mongoAdminDB.runCommand(new Document("replSetGetStatus", 1));
            LOGGER.info("replSetGetStatus: {}", cr);
            maxWaitRounds--;
        } while (!isReplicaSetStarted(cr) || maxWaitRounds != 0);

        if (!isReplicaSetStarted(cr) && maxWaitRounds == 0) {
            throw new RuntimeException("Could not initialize replica set");
        }
    }
}
 
Example #29
Source File: DefaultDataSourceCreater.java    From tangyuan2 with GNU General Public License v3.0 5 votes vote down vote up
private ServerAddress parseAddr(String url) {
	int start = "mongodb://".length();
	int end = url.lastIndexOf("/");
	String host = url.substring(start, end).trim();
	String[] array = host.split(":");
	return new ServerAddress(array[0], Integer.parseInt(array[1]));
}
 
Example #30
Source File: DataNucleusConfiguration.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void parseUrl(final String url) {
    // the url has the following structure:
    // mongodb:[{server}][/{dbName}] [,{server2}[,server3}]]
    final List<HostAndPort> hostAndPortList = new ArrayList<>();

    final String serversAndDbName = url.substring(8); // skip mongodb: part
    final String[] servers = serversAndDbName.split(",");
    for (int i = 0; i < servers.length; i++) {
        String server;
        if (i == 0) {
            final String[] parts = servers[i].split("/");
            if (parts.length == 2) {
                databaseName = parts[1].trim();
            }
            server = parts[0].trim();
        } else {
            server = servers[i].trim();
        }
        hostAndPortList.add(HostAndPort.fromString(server));
    }

    serverAddresses = hostAndPortList.stream()
            .map(h -> new ServerAddress(h.getHost(), h.hasPort() ? h.getPort() : ServerAddress.defaultPort()))
            .collect(Collectors.toList());

    if (serverAddresses.isEmpty()) {
        serverAddresses.add(new ServerAddress());
    }
}