Exemple #1
0
  public static void main(String[] args) {

    System.setProperty("javax.net.ssl.trustStore", args[0]);
    System.setProperty("javax.net.ssl.trustStorePassword", args[1]);
    MongoClientOptions.Builder options = builder().sslEnabled(true).sslInvalidHostNameAllowed(true);
    String uri = "mongodb://127.0.0.1:27017/";
    MongoClientURI connectionString = new MongoClientURI(uri, options);
    MongoClient mongoClient = new MongoClient(connectionString);

    // with username and password

    char[] pwd = "mypasswrd!".toCharArray();

    MongoCredential credential =
        MongoCredential.createCredential(
            "myadmin", "admin", pwd); // user "myadmin" on admin database

    List<MongoCredential> credentials = Collections.singletonList(credential);

    List<ServerAddress> hosts =
        Arrays.asList(
            new ServerAddress("mongodb01.host.dblayer.com:10054"),
            new ServerAddress("mongodb02.host.1.dblayer.com:10071"));

    mongoClient = new MongoClient(hosts, credentials, options.build());
    MongoDatabase foxtrot = mongoClient.getDatabase("foxtrot");
    MongoIterable<String> collectionNames = foxtrot.listCollectionNames();
  }
 /**
  * Retrieves the names of the collections in a database.
  *
  * @param databaseName the name of the database
  * @return a {@link Set} of collection names
  */
 protected Set<String> getCollectionNames(final String databaseName) {
   final MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
   final Set<String> collectionSet = new HashSet<>();
   final MongoCursor<String> cursor = mongoDatabase.listCollectionNames().iterator();
   while (cursor.hasNext()) {
     collectionSet.add(cursor.next());
   }
   return collectionSet;
 }
 /**
  * Creates indices for faster lookups in the database
  *
  * @since 1.12.15
  */
 public static void createIndices() {
   MongoDatabase lettersdb = mongoClient.getDatabase(databaseName);
   for (final String name : lettersdb.listCollectionNames()) {
     System.out.println("collection:" + name);
     if (name.startsWith(prefixCollectionPrefix)) {
       MongoCollection<Document> prefixCollection = lettersdb.getCollection(name);
       prefixCollection.createIndex(ascending(prefixAttribute));
     }
   }
   MongoCollection<Document> wordCollection = lettersdb.getCollection(wordCollectionName);
   wordCollection.createIndex(ascending(wordAttribute));
 }