Example usage for com.mongodb MongoClientURI getHosts

List of usage examples for com.mongodb MongoClientURI getHosts

Introduction

In this page you can find the example usage for com.mongodb MongoClientURI getHosts.

Prototype

public List<String> getHosts() 

Source Link

Document

Gets the list of hosts

Usage

From source file:localdomain.localhost.MyServlet.java

License:Apache License

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter writer = resp.getWriter();

    writer.println("<html>");
    writer.println("<head><title>MyServlet</title></head>");
    writer.println("<body><h1>MyServlet</h1>");

    writer.println("<h2>MongoDB</h2>");

    String uriAsString = System.getProperty("MONGOHQ_URL_MYDB", "mongodb://localhost/local");

    MongoClient mongoClient = null;/* w  ww  .j  a v  a 2 s  . co  m*/
    try {
        writer.println("<h4>MongoClientURI</h4>");

        MongoClientURI uri = new MongoClientURI(uriAsString);
        writer.println("<p>" + "host=" + uri.getHosts() + ",username=" + uri.getUsername() + ",database="
                + uri.getDatabase() + ",collection=" + uri.getCollection() + "</p>");

        writer.println("<h4>MongoClient</h4>");

        mongoClient = new MongoClient(uri);
        writer.println("<p>" + mongoClient + "</p>");

        writer.println("<h4>Databases</h4>");

        try {
            List<String> databaseNames = mongoClient.getDatabaseNames();
            writer.println("<ul>");
            for (String databaseName : databaseNames) {
                writer.println("<li>" + databaseName
                        + (databaseName.equals(uri.getDatabase()) ? " - default database" : ""));
            }
            writer.println("</ul>");
        } catch (Exception e) {
            writer.println("<p>Could not list the databases of the MongoDB instance: <code>" + e.getMessage()
                    + "</code></p>");

        }

        writer.println("<h4>Database</h4>");

        DB db = mongoClient.getDB(uri.getDatabase());
        writer.println("<p>DB: " + db.getName() + "</p>");

        writer.println("<h4>Collections</h4>");
        Set<String> myCollections = db.getCollectionNames();
        if (myCollections.isEmpty()) {
            writer.println("<p>NO COLLECTIONS!</p>");

        } else {

            writer.println("<ul>");
            for (String collection : myCollections) {
                DBCollection dbCollection = db.getCollection(collection);
                writer.println(
                        "<li>" + dbCollection.getName() + " - " + dbCollection.getCount() + " entries</li>");
            }
            writer.println("</ul>");
        }
        writer.println("<h4>Success!</h4>");
        writer.println("SUCCESS to access the mongodb database");

    } catch (Exception e) {
        writer.println("<code><pre>");
        e.printStackTrace(writer);
        writer.println("</pre></code>");

        e.printStackTrace();
    } finally {
        if (mongoClient != null) {
            try {
                mongoClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    writer.println("</body></html>");

}

From source file:org.alfresco.mongo.MongoClientFactory.java

License:Open Source License

/**
 * Validates MongoClientURI //www .ja  va 2s .  c  o m
 * @param mongoClientURI {MongoClientURI} must not be null and contain valid host and (optional) port. 
 */
private void validateMongoClientURI(MongoClientURI mongoClientURI) {
    // 1. Argument not optional
    if (null == mongoClientURI) {
        throw new IllegalArgumentException("'mongoClientURI' argument may not be null.");
    }

    // 2.  Validate host
    for (String host : mongoClientURI.getHosts()) {
        // ensure not null or empty or just whitespace chars
        if (null != host && host.trim().length() > 0) {
            try {
                // create a URI from the host name - may throw URISyntaxException
                URI uri = new URI("my://" + host);

                // get host without port from URI
                host = uri.getHost();

                if (null == host || host.trim().length() == 0) {
                    throw new IllegalArgumentException(
                            "'mongoClientURI' argument must contain a valid host: " + mongoClientURI);
                }
            } catch (URISyntaxException ex) {
                // validation failed due to malformed host
                throw new IllegalArgumentException(
                        "'mongoClientURI' argument must contain a valid host: " + mongoClientURI);
            }
        } else {
            throw new IllegalArgumentException(
                    "'mongoClientURI' argument: host is mandatory: " + mongoClientURI);
        }
    }
}

From source file:org.alfresco.mongo.MongoDBForTestsFactory.java

License:Open Source License

/**
 * Get a Mongo host string e.g. <b>127.0.0.1:51932</b>
 *//*from  w  w  w. j  av  a  2 s  .c  o  m*/
public String getMongoHost() {
    MongoClientURI mongoClientURI = new MongoClientURI(getMongoURIWithoutDB());
    return mongoClientURI.getHosts().get(0);
}

From source file:org.apache.jackrabbit.oak.plugins.document.DocumentNodeStoreService.java

License:Apache License

private void registerNodeStore() throws IOException {
    String uri = PropertiesUtil.toString(prop(PROP_URI, FWK_PROP_URI), DEFAULT_URI);
    String db = PropertiesUtil.toString(prop(PROP_DB, FWK_PROP_DB), DEFAULT_DB);

    int cacheSize = toInteger(prop(PROP_CACHE), DEFAULT_CACHE);
    int nodeCachePercentage = toInteger(prop(PROP_NODE_CACHE_PERCENTAGE), DEFAULT_NODE_CACHE_PERCENTAGE);
    int prevDocCachePercentage = toInteger(prop(PROP_PREV_DOC_CACHE_PERCENTAGE), DEFAULT_NODE_CACHE_PERCENTAGE);
    int childrenCachePercentage = toInteger(prop(PROP_CHILDREN_CACHE_PERCENTAGE),
            DEFAULT_CHILDREN_CACHE_PERCENTAGE);
    int docChildrenCachePercentage = toInteger(prop(PROP_DOC_CHILDREN_CACHE_PERCENTAGE),
            DEFAULT_DOC_CHILDREN_CACHE_PERCENTAGE);
    int diffCachePercentage = toInteger(prop(PROP_DIFF_CACHE_PERCENTAGE), DEFAULT_DIFF_CACHE_PERCENTAGE);
    int blobCacheSize = toInteger(prop(PROP_BLOB_CACHE_SIZE), DEFAULT_BLOB_CACHE_SIZE);
    String persistentCache = PropertiesUtil.toString(prop(PROP_PERSISTENT_CACHE), DEFAULT_PERSISTENT_CACHE);
    int cacheSegmentCount = toInteger(prop(PROP_CACHE_SEGMENT_COUNT), DEFAULT_CACHE_SEGMENT_COUNT);
    int cacheStackMoveDistance = toInteger(prop(PROP_CACHE_STACK_MOVE_DISTANCE),
            DEFAULT_CACHE_STACK_MOVE_DISTANCE);
    DocumentMK.Builder mkBuilder = new DocumentMK.Builder().setStatisticsProvider(statisticsProvider)
            .memoryCacheSize(cacheSize * MB)
            .memoryCacheDistribution(nodeCachePercentage, prevDocCachePercentage, childrenCachePercentage,
                    docChildrenCachePercentage, diffCachePercentage)
            .setCacheSegmentCount(cacheSegmentCount).setCacheStackMoveDistance(cacheStackMoveDistance)
            .setLeaseCheck(true /* OAK-2739: enabled by default */)
            .setLeaseFailureHandler(new LeaseFailureHandler() {

                @Override/*from  w  w  w  .  j  a v  a  2s . c om*/
                public void handleLeaseFailure() {
                    try {
                        // plan A: try stopping oak-core
                        log.error("handleLeaseFailure: stopping oak-core...");
                        Bundle bundle = context.getBundleContext().getBundle();
                        bundle.stop();
                        log.error("handleLeaseFailure: stopped oak-core.");
                        // plan A worked, perfect!
                    } catch (BundleException e) {
                        log.error("handleLeaseFailure: exception while stopping oak-core: " + e, e);
                        // plan B: stop only DocumentNodeStoreService (to stop the background threads)
                        log.error("handleLeaseFailure: stopping DocumentNodeStoreService...");
                        context.disableComponent(DocumentNodeStoreService.class.getName());
                        log.error("handleLeaseFailure: stopped DocumentNodeStoreService");
                        // plan B succeeded.
                    }
                }
            });

    if (persistentCache != null && persistentCache.length() > 0) {
        mkBuilder.setPersistentCache(persistentCache);
    }

    boolean wrappingCustomBlobStore = customBlobStore && blobStore instanceof BlobStoreWrapper;

    //Set blobstore before setting the DB
    if (customBlobStore && !wrappingCustomBlobStore) {
        checkNotNull(blobStore,
                "Use of custom BlobStore enabled via  [%s] but blobStore reference not " + "initialized",
                CUSTOM_BLOB_STORE);
        mkBuilder.setBlobStore(blobStore);
    }

    if (documentStoreType == DocumentStoreType.RDB) {
        checkNotNull(dataSource, "DataStore type set [%s] but DataSource reference not initialized",
                PROP_DS_TYPE);
        if (!customBlobStore) {
            checkNotNull(blobDataSource, "DataStore type set [%s] but BlobDataSource reference not initialized",
                    PROP_DS_TYPE);
            mkBuilder.setRDBConnection(dataSource, blobDataSource);
            log.info("Connected to datasources {} {}", dataSource, blobDataSource);
        } else {
            if (blobDataSource != null && blobDataSource != dataSource) {
                log.info("Ignoring blobDataSource {} as custom blob store takes precedence.", blobDataSource);
            }
            mkBuilder.setRDBConnection(dataSource);
            log.info("Connected to datasource {}", dataSource);
        }
    } else {
        MongoClientURI mongoURI = new MongoClientURI(uri);

        if (log.isInfoEnabled()) {
            // Take care around not logging the uri directly as it
            // might contain passwords
            log.info(
                    "Starting DocumentNodeStore with host={}, db={}, cache size (MB)={}, persistentCache={}, "
                            + "blobCacheSize (MB)={}, maxReplicationLagInSecs={}",
                    mongoURI.getHosts(), db, cacheSize, persistentCache, blobCacheSize,
                    maxReplicationLagInSecs);
            log.info("Mongo Connection details {}", MongoConnection.toString(mongoURI.getOptions()));
        }

        mkBuilder.setMaxReplicationLag(maxReplicationLagInSecs, TimeUnit.SECONDS);
        mkBuilder.setMongoDB(uri, db, blobCacheSize);

        log.info("Connected to database '{}'", db);
    }

    if (!customBlobStore) {
        defaultBlobStore = mkBuilder.getBlobStore();
        log.info("Registering the BlobStore with ServiceRegistry");
        blobStoreReg = context.getBundleContext().registerService(BlobStore.class.getName(), defaultBlobStore,
                null);
    }

    //Set wrapping blob store after setting the DB
    if (wrappingCustomBlobStore) {
        ((BlobStoreWrapper) blobStore).setBlobStore(mkBuilder.getBlobStore());
        mkBuilder.setBlobStore(blobStore);
    }

    mkBuilder.setExecutor(executor);
    mk = mkBuilder.open();

    // ensure a clusterId is initialized 
    // and expose it as 'oak.clusterid' repository descriptor
    GenericDescriptors clusterIdDesc = new GenericDescriptors();
    clusterIdDesc.put(ClusterRepositoryInfo.OAK_CLUSTERID_REPOSITORY_DESCRIPTOR_KEY,
            new SimpleValueFactory().createValue(ClusterRepositoryInfo.getOrCreateId(mk.getNodeStore())), true,
            false);
    whiteboard.register(Descriptors.class, clusterIdDesc, Collections.emptyMap());

    // If a shared data store register the repo id in the data store
    if (SharedDataStoreUtils.isShared(blobStore)) {
        try {
            String repoId = ClusterRepositoryInfo.getOrCreateId(mk.getNodeStore());
            ((SharedDataStore) blobStore).addMetadataRecord(new ByteArrayInputStream(new byte[0]),
                    SharedDataStoreUtils.SharedStoreRecordType.REPOSITORY.getNameFromId(repoId));
        } catch (Exception e) {
            throw new IOException("Could not register a unique repositoryId", e);
        }
    }

    registerJMXBeans(mk.getNodeStore(), mkBuilder);
    registerLastRevRecoveryJob(mk.getNodeStore());
    registerJournalGC(mk.getNodeStore());

    NodeStore store;
    documentNodeStore = mk.getNodeStore();
    store = documentNodeStore;
    observerTracker = new ObserverTracker(documentNodeStore);

    observerTracker.start(context.getBundleContext());

    DocumentStore ds = mk.getDocumentStore();

    // OAK-2682: time difference detection applied at startup with a default
    // max time diff of 2000 millis (2sec)
    final long maxDiff = Long.parseLong(System.getProperty("oak.documentMK.maxServerTimeDiffMillis", "2000"));
    try {
        if (maxDiff >= 0) {
            final long timeDiff = ds.determineServerTimeDifferenceMillis();
            log.info("registerNodeStore: server time difference: {}ms (max allowed: {}ms)", timeDiff, maxDiff);
            if (Math.abs(timeDiff) > maxDiff) {
                throw new AssertionError("Server clock seems off (" + timeDiff
                        + "ms) by more than configured amount (" + maxDiff + "ms)");
            }
        }
    } catch (RuntimeException e) { // no checked exception
        // in case of a RuntimeException, just log but continue
        log.warn("registerNodeStore: got RuntimeException while trying to determine time difference to server: "
                + e, e);
    }

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(Constants.SERVICE_PID, DocumentNodeStore.class.getName());
    props.put(DESCRIPTION, getMetadata(ds));
    // OAK-2844: in order to allow DocumentDiscoveryLiteService to directly
    // require a service DocumentNodeStore (instead of having to do an 'instanceof')
    // the registration is now done for both NodeStore and DocumentNodeStore here.
    nodeStoreReg = context.getBundleContext().registerService(new String[] { NodeStore.class.getName(),
            DocumentNodeStore.class.getName(), Clusterable.class.getName() }, store, props);
}

From source file:org.craftercms.commons.mongo.MongoScriptRunner.java

License:Open Source License

private List<String> getCommands(final Path scriptPath) throws MongoDataException {
    List<String> commandList = new ArrayList<>();
    if (SystemUtils.IS_OS_WINDOWS) {
        commandList.add("CMD");
        commandList.add("/C");
    }//ww w . j  a v a2s.  c om
    if (StringUtils.isBlank(mongoClientBin)) {
        throw new MongoDataException("Unable to run scripts, mongo client bin path is not set ");
    }
    String pwd = null;
    String authSource = null;
    String user = null;
    MongoClientURI uri = new MongoClientURI(connectionStr);
    if (uri.getCredentials() != null) {
        authSource = uri.getCredentials().getSource();
        user = uri.getCredentials().getUserName();
        if (uri.getCredentials().getPassword() != null) {
            pwd = new String(uri.getCredentials().getPassword());
        }
    }
    String replicaSetName = "";
    if (uri.getHosts().size() > 1) {
        replicaSetName = uri.getOptions().getRequiredReplicaSetName() + "/";
    }
    final String host = StringUtils.trim(replicaSetName + StringUtils.join(uri.getHosts(), ","));
    commandList.add(mongoClientBin);
    commandList.add("--host");
    commandList.add(host);
    commandList.add(uri.getDatabase());
    if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(pwd) && StringUtils.isNotBlank(authSource)) {
        commandList.add("-u");
        commandList.add(user);
        commandList.add("-p");
        commandList.add(pwd);
        commandList.add("--authenticationDatabase");
        commandList.add(authSource);
    }
    commandList.add(scriptPath.toAbsolutePath().toString());
    return commandList;
}

From source file:org.graylog.plugins.metrics.mongodb.providers.MongoDBReporterProvider.java

License:Open Source License

private ServerAddress[] extractServerAddresses(MongoClientURI mongoClientURI) {
    final List<String> hosts = mongoClientURI.getHosts();
    final List<ServerAddress> serverAddresses = new ArrayList<>(hosts.size());
    for (String host : hosts) {
        final HostAndPort hostAndPort = HostAndPort.fromString(host)
                .withDefaultPort(ServerAddress.defaultPort());
        final ServerAddress serverAddress = new ServerAddress(hostAndPort.getHostText(), hostAndPort.getPort());
        serverAddresses.add(serverAddress);
    }/*from   w w w .  j a  v  a2 s. c o  m*/
    return serverAddresses.toArray(new ServerAddress[serverAddresses.size()]);
}

From source file:org.netbeans.modules.mongodb.native_tools.MongoDumpExecAction.java

License:Open Source License

private void parseOptionsFromURI(MongoClientURI uri, Map<String, String> options) {
    if (uri.getUsername() != null && uri.getUsername().isEmpty() == false) {
        options.put(MongoDumpOptions.USERNAME, uri.getUsername());
    }//from  ww w . j  ava  2s. c  om
    if (uri.getPassword() != null && uri.getPassword().length > 0) {
        options.put(MongoDumpOptions.PASSWORD, new String(uri.getPassword()));
    }
    if (uri.getHosts() != null && uri.getHosts().isEmpty() == false) {
        final String hostWithPort = uri.getHosts().get(0);
        final Pattern p = Pattern.compile("(.*)(:(\\d+))?");
        final Matcher m = p.matcher(hostWithPort);
        if (m.matches()) {
            final String host = m.group(1);
            final String port = m.group(3);
            if (host.isEmpty() == false) {
                options.put(MongoDumpOptions.HOST, host);
                if (port != null) {
                    options.put(MongoDumpOptions.PORT, port);
                }
            }
        }
    }
    if (uri.getDatabase() != null && uri.getDatabase().isEmpty() == false) {
        options.put(MongoDumpOptions.DB, uri.getDatabase());
    }
    if (uri.getCollection() != null && uri.getCollection().isEmpty() == false) {
        options.put(MongoDumpOptions.COLLECTION, uri.getCollection());
    }
}

From source file:org.netbeans.modules.mongodb.native_tools.MongoRestoreExecAction.java

License:Open Source License

private void parseOptionsFromURI(MongoClientURI uri, Map<String, String> options) {
    if (uri.getUsername() != null && uri.getUsername().isEmpty() == false) {
        options.put(MongoRestoreOptions.USERNAME, uri.getUsername());
    }/*from w w  w .j a va  2s  .com*/
    if (uri.getPassword() != null && uri.getPassword().length > 0) {
        options.put(MongoRestoreOptions.PASSWORD, new String(uri.getPassword()));
    }
    if (uri.getHosts() != null && uri.getHosts().isEmpty() == false) {
        final String hostWithPort = uri.getHosts().get(0);
        final Pattern p = Pattern.compile("(.*)(:(\\d+))?");
        final Matcher m = p.matcher(hostWithPort);
        if (m.matches()) {
            final String host = m.group(1);
            final String port = m.group(3);
            if (host.isEmpty() == false) {
                options.put(MongoRestoreOptions.HOST, host);
                if (port != null) {
                    options.put(MongoRestoreOptions.PORT, port);
                }
            }
        }
    }
    if (uri.getDatabase() != null && uri.getDatabase().isEmpty() == false) {
        options.put(MongoRestoreOptions.DB, uri.getDatabase());
    }
    if (uri.getCollection() != null && uri.getCollection().isEmpty() == false) {
        options.put(MongoRestoreOptions.COLLECTION, uri.getCollection());
    }
}

From source file:org.netbeans.modules.mongodb.native_tools.MongoShellExecAction.java

License:Open Source License

private void parseOptionsFromURI(ProcessCreator.Builder builder, MongoClientURI uri) {
    if (uri.getUsername() != null && uri.getUsername().isEmpty() == false) {
        builder.option("--username", uri.getUsername());
    }/*from  w  w  w  .ja  va2 s. c  o m*/
    if (uri.getPassword() != null && uri.getPassword().length > 0) {
        builder.option("--password", new String(uri.getPassword()));
    }
    if (uri.getHosts() != null && uri.getHosts().isEmpty() == false) {
        final String hostWithPort = uri.getHosts().get(0);
        final Pattern p = Pattern.compile("(.*)(:(\\d+))?");
        final Matcher m = p.matcher(hostWithPort);
        if (m.matches()) {
            final String host = m.group(1);
            final String port = m.group(3);
            if (host.isEmpty() == false) {
                builder.option("--host", host);
                if (port != null) {
                    builder.option("--port", port);
                }
            }
        }
    }
}

From source file:org.netbeans.modules.mongodb.native_tools.MongoTopExecAction.java

License:Open Source License

private void parseOptionsFromURI(MongoClientURI uri, Map<String, String> options) {
    if (uri.getUsername() != null && uri.getUsername().isEmpty() == false) {
        options.put(MongoDumpOptions.USERNAME, uri.getUsername());
    }//from   ww  w  . ja v a2s. com
    if (uri.getPassword() != null && uri.getPassword().length > 0) {
        options.put(MongoDumpOptions.PASSWORD, new String(uri.getPassword()));
    }
    if (uri.getHosts() != null && uri.getHosts().isEmpty() == false) {
        final String hostWithPort = uri.getHosts().get(0);
        final Pattern p = Pattern.compile("(.*)(:(\\d+))?");
        final Matcher m = p.matcher(hostWithPort);
        if (m.matches()) {
            final String host = m.group(1);
            final String port = m.group(3);
            if (host.isEmpty() == false) {
                options.put(MongoDumpOptions.HOST, host);
                if (port != null) {
                    options.put(MongoDumpOptions.PORT, port);
                }
            }
        }
    }
}