Example usage for com.mongodb MongoClient getAddress

List of usage examples for com.mongodb MongoClient getAddress

Introduction

In this page you can find the example usage for com.mongodb MongoClient getAddress.

Prototype

@Deprecated
@SuppressWarnings("deprecation")
@Nullable
public ServerAddress getAddress() 

Source Link

Document

Gets the address of the current master

Usage

From source file:MongoRyaDirectExample.java

License:Apache License

private static Configuration getConf() throws IOException {

    final MongoDBRdfConfiguration conf = new MongoDBRdfConfiguration();
    conf.set(ConfigUtils.USE_MONGO, "true");

    if (USE_MOCK) {
        mock = MockMongoFactory.newFactory();
        final MongoClient c = mock.newMongoClient();
        final ServerAddress address = c.getAddress();
        final String url = address.getHost();
        final String port = Integer.toString(address.getPort());
        c.close();//from  w  w w . j a  v a2  s .  c o  m
        conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE, url);
        conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT, port);
    } else {
        // User name and password must be filled in:
        conf.set(MongoDBRdfConfiguration.MONGO_USER, "fill this in");
        conf.set(MongoDBRdfConfiguration.MONGO_USER_PASSWORD, "fill this in");
        conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE, MONGO_INSTANCE_URL);
        conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT, MONGO_INSTANCE_PORT);
    }
    conf.set(MongoDBRdfConfiguration.MONGO_DB_NAME, MONGO_DB);
    conf.set(MongoDBRdfConfiguration.MONGO_COLLECTION_PREFIX, MONGO_COLL_PREFIX);
    conf.set(ConfigUtils.GEO_PREDICATES_LIST, "http://www.opengis.net/ont/geosparql#asWKT");
    //        conf.set(ConfigUtils.USE_GEO, "true");
    conf.set(ConfigUtils.USE_FREETEXT, "true");
    conf.setTablePrefix(MONGO_COLL_PREFIX);
    conf.set(ConfigUtils.GEO_PREDICATES_LIST, GeoConstants.GEO_AS_WKT.stringValue());
    conf.set(ConfigUtils.FREETEXT_PREDICATES_LIST, RDFS.LABEL.stringValue());
    conf.set(ConfigUtils.FREETEXT_PREDICATES_LIST, RDFS.LABEL.stringValue());
    conf.set(RdfCloudTripleStoreConfiguration.CONF_INFER, Boolean.toString(USE_INFER));
    return conf;
}

From source file:InferenceExamples.java

License:Apache License

private static Configuration getConf() throws IOException {

    // MongoDBIndexingConfigBuilder builder = MongoIndexingConfiguration.builder()
    //     .setUseMockMongo(USE_MOCK).setUseInference(USE_INFER).setAuths("U");
    MongoDBIndexingConfigBuilder builder = MongoIndexingConfiguration.builder()
            .setUseMockMongo(USE_EMBEDDED_MONGO).setUseInference(true).setAuths("U");

    if (USE_EMBEDDED_MONGO) {
        final MongoClient c = EmbeddedMongoFactory.newFactory().newMongoClient();
        final ServerAddress address = c.getAddress();
        final String url = address.getHost();
        final String port = Integer.toString(address.getPort());
        c.close();//from   ww  w. j av  a2s.  co  m
        builder.setMongoHost(url).setMongoPort(port);
    } else {
        // User name and password must be filled in:
        builder = builder.setMongoUser(MongoUserName).setMongoPassword(MongoUserPassword)
                .setMongoHost(MONGO_INSTANCE_URL).setMongoPort(MONGO_INSTANCE_PORT);
    }

    return builder.setMongoDBName(MONGO_DB).setMongoCollectionPrefix(MONGO_COLL_PREFIX)
            .setUseMongoFreetextIndex(true).setMongoFreeTextPredicates(RDFS.LABEL.stringValue()).build();

}

From source file:actor4j.core.persistence.connectors.MongoDBPersistenceConnector.java

License:Open Source License

public MongoDBPersistenceConnector(MongoClient client, String databaseName) {
    super(client.getAddress().getHost(), client.getAddress().getPort(), databaseName);

    this.client = client;
}

From source file:adc.data.viewer.dao.ConnectionBuilderMongo.java

License:Open Source License

@Override
public MongoClient getConnection() {

    try {/*from   w w  w .jav  a 2s . c om*/

        MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoURI));
        mongoClient.getAddress();
        return mongoClient;
    } catch (MongoException | IllegalArgumentException me) {
        System.out.println("Connection to MongoDB failed");
        //    BaseController.alertMongoDBConnectionError();
        return null;
    }
}

From source file:com.edgytech.umongo.MongoPanel.java

License:Apache License

@Override
protected void updateComponentCustom(JPanel old) {
    try {/*from w w  w  .  j  av  a  2s . c o  m*/
        MongoClient mongo = getMongoNode().getMongoClient();
        setStringFieldValue(Item.version, mongo.getVersion());

        ServerAddress master = mongo.getAddress();
        if (master != null) {
            setStringFieldValue(Item.masterServer, getServerAddressString(master));
        }
        List<ServerAddress> addrs = mongo.getAllAddress();
        String html = "<html>";
        for (ServerAddress addr : addrs) {
            html += getServerAddressString(addr) + "<br/>";
        }
        html += "</html>";
        setStringFieldValue(Item.seedServers, html);

        addrs = mongo.getServerAddressList();
        html = "<html>";
        for (ServerAddress addr : addrs) {
            //                String ports = MongoUtils.makeInfoString("used", mongo.getConnector().getDBPortPool(addr).inUse(),
            //                        "available", mongo.getConnector().getDBPortPool(addr).available(),
            //                        "created", mongo.getConnector().getDBPortPool(addr).everCreated());
            String txt = getServerAddressString(addr);
            html += txt + "<br/>";
        }
        setStringFieldValue(Item.activeServers, html);

        setStringFieldValue(Item.queryOptions, MongoUtils.queryOptionsToString(mongo.getOptions()));
        ((DocField) getBoundUnit(Item.writeConcern)).setDoc(mongo.getWriteConcern().getCommand());
        ((DocField) getBoundUnit(Item.readPreference)).setDoc(mongo.getReadPreference().toDBObject());
        setStringFieldValue(Item.maxObjectSize, String.valueOf(mongo.getMaxBsonObjectSize()));
    } catch (Exception e) {
        UMongo.instance.showError(this.getClass().getSimpleName() + " update", e);
    }
}

From source file:com.edgytech.umongo.ServerNode.java

License:Apache License

public ServerNode(MongoClient mongo, boolean isReplica, boolean isConfig) {
    serverMongo = mongo;//from   w  ww .  j  a va2s  .  c om
    serverAddress = mongo.getAddress();
    setLabel(serverAddress != null ? serverAddress.toString() : "?");
    this.isReplica = isReplica;
    this.isConfig = isConfig;

    try {
        xmlLoad(Resource.getXmlDir(), Resource.File.serverNode, null);
    } catch (Exception ex) {
        getLogger().log(Level.SEVERE, null, ex);
    }

    markStructured();
}

From source file:com.owly.srv.config.ApplicationListener.java

License:Apache License

/**
 * This methond checks status of the stadistics server database
 * // ww  w.  j  a va2  s.  c  o m
 * @param StadisticsServer
 * @param listInitRemoteServer
 * @return a bolean true in case parameters of database are OK, and database
 *         is up.
 */
public boolean checkDatabaseStatus(StatsServer StadisticsServer, ArrayList<RemoteServer> listInitRemoteServer) {

    final String CollectionDB = "StatsSrvCfg";

    // logger.debug("Configuration of the Stats Server : " +
    // StadisticsServer.toString());

    if (!StadisticsServer.isEnabled()) {
        logger.error("Statistics server is disabled, check configuration file");
        RuntimeException ex = new RuntimeException("Error starting the Application ");
        throw ex;

    } else {
        if (!StadisticsServer.getStatsDatabaseType().equals("MONGODB")) {
            logger.error(
                    "Statistics server database should be MongoDB (others not implemented), check configuration file");
            RuntimeException ex = new RuntimeException("Error starting the Application ");
            throw ex;
        } else {
            if (!StadisticsServer.getStatsIpAddress().equals("127.0.0.1")) {
                logger.info("Statistics server IP is not 127.0.0.1 --> Database is a remote server");
            } else {
                logger.info("Statistics server IP is  127.0.0.1 --> Database is local server");
            }

            logger.debug("Checking if MongoDB is up and running for IP : "
                    + StadisticsServer.getStatsIpAddress() + " and port : " + StadisticsServer.getStatsPort());
            try {

                /**** Connect to MongoDB ****/
                // Since 2.10.0, uses MongoClient
                MongoClient mongoClient = new MongoClient(StadisticsServer.getStatsIpAddress(),
                        StadisticsServer.getStatsPort());

                try {
                    Socket socket = mongoClient.getMongoOptions().socketFactory.createSocket();
                    socket.connect(mongoClient.getAddress().getSocketAddress());
                    socket.close();
                } catch (IOException e) {
                    logger.error("mongoDB Error : " + e.getMessage());
                    logger.error("Exception ::", e);
                    RuntimeException ex = new RuntimeException("Error starting the Application ");
                    throw ex;

                }

                /**** Get database ****/
                // if database doesn't exists, MongoDB will create it
                // for you
                DB statsDB = mongoClient.getDB(StadisticsServer.getStatsDatabase());

                StatsServerMongoDAOImpl statServerCfg = new StatsServerMongoDAOImpl(statsDB);

                RemoteServerMongoDAOImpl remoteServerCfg = new RemoteServerMongoDAOImpl(statsDB);

                // Drop all previous configuration in the database

                statServerCfg.deleteAllStatsServer();
                //remoteServerCfg.deleteAllRemoteServer();

                // Create new configuration in database
                int numberStats = statServerCfg.numberStatsServer();

                if (numberStats == 0) {
                    logger.debug("Actual Server Stats configuration NOT in database");
                    logger.debug("Insert configuration in Database");

                    // Insert Stats Server in Database
                    statServerCfg.insertStatsServer(StadisticsServer);

                    // Insert Remote Servers in the Database
                    for (int srv = 0; srv < listInitRemoteServer.size(); srv++) {
                        logger.debug("Remote Server to Insert in database (" + srv + ") : "
                                + listInitRemoteServer.get(srv).toString());
                        RemoteServer remoteServer = listInitRemoteServer.get(srv);
                        String nameSrv = remoteServer.getName();
                        String ipSrv = remoteServer.getNodeIPAddress();

                        // Drop the server from database is already exists
                        remoteServerCfg.deleteRemoteServer(nameSrv, ipSrv);

                        // Insert the remote server. 
                        remoteServerCfg.insertRemoteServer(listInitRemoteServer.get(srv));
                        logger.debug("Remote Serverinserted");

                    }

                    // Add a unique index based on IP and name
                    remoteServerCfg.addUniqueIndex("NodeIPAddress", "Name");

                } else {
                    logger.error("Configuration in database " + CollectionDB
                            + " is not OK, manual action is required");
                    // Close the conection to database
                    logger.info("Closing MongoClient");
                    mongoClient.close();
                    RuntimeException ex = new RuntimeException("Error starting the Application ");
                    throw ex;
                }

                // Close the conection to database
                logger.info("Closing MongoClient");
                mongoClient.close();

            } catch (UnknownHostException e) {
                logger.error("mongoDB Error : " + e.getMessage());
                logger.error("Exception ::", e);
                RuntimeException ex = new RuntimeException("Error starting the Application ");
                throw ex;
            }

        }
    }

    return true;

}

From source file:com.ultratechnica.mongodb.Main.java

License:Apache License

public static void main(String[] args) {

    log.info("=============================================================================================\n"
            + "                       _   _     _                 \n"
            + " |\\/|  _  ._   _   _  | \\ |_)   |_)  _  ._   _ |_  \n"
            + " |  | (_) | | (_| (_) |_/ |_)   |_) (/_ | | (_ | | \n"
            + "               _|                                  \n"
            + "Copyright 2013 Keith Bishop, Ultratechnica Ltd, http://ultratechnica.com\n"
            + "Licensed to Apache "
            + "=============================================================================================\n");
    Options options = getOptions();//from   www. j ava2  s.c  om

    CommandLine commandLine = parseArgs(args, options);

    MongoClient client = null;

    if (commandLine.hasOption("host") && commandLine.hasOption("port")) {

        String host = commandLine.getOptionValue("host");
        String port = commandLine.getOptionValue("port");

        try {

            client = new MongoClient(host, Integer.parseInt(port));
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on port [{}]", host, port);
        }
    } else if (options.hasOption("host")) {

        String host = commandLine.getOptionValue("host");

        try {
            client = new MongoClient(host);
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on default port ()", host);
        }
    } else {

        try {
            client = new MongoClient();
        } catch (UnknownHostException e) {
            log.error("Unable to connect default host ({}) on default port ()", DEFAULT_HOST, DEFAULT_PORT);
        }
    }

    if (client == null) {
        System.out.println("Exiting, due to previous connection errors");
        System.exit(1);
    }

    ServerAddress clientAddress = client.getAddress();
    log.info("Connected to MongoDB [{}]", clientAddress);

    MongoClientOptions mongoClientOptions = client.getMongoClientOptions();

    log.info("=============================================================================================\n"
            + "Using Mongo Client options:\n" + "\tConnections per host: "
            + mongoClientOptions.getConnectionsPerHost() + "\n" + "\tConect timeout: "
            + mongoClientOptions.getConnectTimeout() + " \n" + "\tSocket timeout: "
            + mongoClientOptions.getSocketTimeout() + "\n" + "\tMax Wait time: "
            + mongoClientOptions.getMaxWaitTime() + "\n" + "\tMax Auto connect retry time: "
            + mongoClientOptions.getMaxAutoConnectRetryTime() + "\n"
            + "\tMax threads allowed to block for conneciton multipler: "
            + mongoClientOptions.getThreadsAllowedToBlockForConnectionMultiplier() + "\n" + "\tWrite concern: "
            + mongoClientOptions.getWriteConcern() + "\n" + "\tRead Preference: "
            + mongoClientOptions.getReadPreference() + "\n"
            + "=============================================================================================\n");

    String items = commandLine.getOptionValue("n");

    int numberOfItems = 0;
    try {
        numberOfItems = Integer.parseInt(items);
    } catch (NumberFormatException e) {
        log.error("The parameter provided for -n was not an integer [{}]", items);
        System.exit(1);
    }

    DB local = client.getDB("local");

    DBCollection collection = local.getCollection(DEFAULT_COLLECTION_NAME);

    log.info("Starting benchmark, inserting [{}] items into collection [{}]", numberOfItems,
            DEFAULT_COLLECTION_NAME);

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < numberOfItems; i++) {

        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("timestamp", new Date())
                .add("field1", "123456").add("field2", "2345678")
                .add("field3", "123123231313131232131231231231123132123123123").add("field4", true);

        WriteResult result = collection.insert(builder.get());
        if (!result.getLastError().ok()) {
            log.error("An error occurred [{}]", result.getLastError());
        }
    }

    long endTime = System.currentTimeMillis();

    log.info("Finished benchmarking.");
    long timeTakenMillis = endTime - startTime;

    float timeTaken = (float) timeTakenMillis / 1000;

    log.info("Results:\n\n" + String.format("%-25s %d", "Number of Items inserted:", numberOfItems) + "\n"
            + String.format("%-25s %.2f", "Time elapsed:", timeTaken) + " seconds\n"
            + String.format("%-25s %.2f", "Throughput:", numberOfItems / timeTaken) + " items/sec\n");

    log.info("Removing test data...");
    collection.remove(new BasicDBObject());
    log.info("Cleared collection [test]");
}

From source file:flipkart.mongo.replicator.node.ReplicationTask.java

License:Apache License

@Override
public void run() {
    String shardId = rsConfig.shardName;
    Node masterNode = rsConfig.getMasterNode().get();
    MongoClient client = MongoConnector.getMongoClient(Lists.newArrayList(masterNode));

    MongoDatabase database = client.getDatabase("local");
    lastCp = taskContext.checkPointHandler.getCheckPoint(shardId);

    logger.info(String.format("######## START REPLICATOR FOR MongoURI: %s. LastCheckpoint: %s #######",
            client.getAddress(), lastCp));
    MongoCollection<Document> collection = database.getCollection("oplog.rs");
    FindIterable<Document> iterable;
    MongoCursor<Document> cursor;
    do {/*from w w w  .  j ava  2 s. c o m*/
        if (lastCp == null) {
            iterable = collection.find();
        } else {
            iterable = collection.find(new Document("ts", new Document("$gt", lastCp)));
        }
        cursor = iterable.sort(new Document("$natural", 1)).noCursorTimeout(true)
                .cursorType(CursorType.TailableAwait).batchSize(3000).iterator();
        try {
            executeCursor(cursor);
            Thread.sleep(WAIT_FOR_NEXT_ITERATION);
        } catch (MongoCursorNotFoundException e) {
            logger.info("Cursor has been closed. About to open a new cursor. ID: "
                    + cursor.getServerCursor().getId());
        } catch (Exception e) {
            logger.error("Exception while replicating", e);
            throw new RuntimeException(e);
        } finally {
            cursor.close();
        }
    } while (true);
}

From source file:io.debezium.connector.mongodb.Replicator.java

License:Apache License

/**
 * Use the given primary to read the oplog.
 * /*  w  w  w. jav a 2  s  .  c o  m*/
 * @param primary the connection to the replica set's primary node; may not be null
 */
protected void readOplog(MongoClient primary) {
    BsonTimestamp oplogStart = source.lastOffsetTimestamp(replicaSet.replicaSetName());
    logger.info("Reading oplog for '{}' primary {} starting at {}", replicaSet, primary.getAddress(),
            oplogStart);

    // Include none of the cluster-internal operations and only those events since the previous timestamp ...
    MongoCollection<Document> oplog = primary.getDatabase("local").getCollection("oplog.rs");
    Bson filter = Filters.and(Filters.gt("ts", oplogStart), // start just after our last position
            Filters.exists("fromMigrate", false)); // skip internal movements across shards
    FindIterable<Document> results = oplog.find(filter).sort(new Document("$natural", 1)) // force forwards collection scan
            .oplogReplay(true) // tells Mongo to not rely on indexes
            .noCursorTimeout(true) // don't timeout waiting for events
            .cursorType(CursorType.TailableAwait); // tail and await new data
    // Read as much of the oplog as we can ...
    ServerAddress primaryAddress = primary.getAddress();
    try (MongoCursor<Document> cursor = results.iterator()) {
        while (running.get() && cursor.hasNext()) {
            if (!handleOplogEvent(primaryAddress, cursor.next())) {
                // Something happened, and we're supposed to stop reading
                return;
            }
        }
    }
}