List of usage examples for com.mongodb MongoClient getDatabase
public MongoDatabase getDatabase(final String databaseName)
From source file:org.flywaydb.core.internal.dbsupport.mongo.MongoDatabaseUtil.java
License:Apache License
/** * Checks whether a Mongo collection exists. * * @param client a MongoClient for connecting to the database. * @param dbName the database name.//from w w w. ja va2 s . c o m * @param name the collection name. * @return {@code true} if it does, {@code false} if not. */ public static boolean hasCollection(MongoClient client, String dbName, String name) { try { MongoDatabase mongoDb = client.getDatabase(dbName); MongoIterable<String> collectionNameIterator = mongoDb.listCollectionNames(); for (String collectionName : collectionNameIterator) { if (collectionName.equals(name)) return true; } return false; } catch (MongoException e) { throw new FlywayException("Unable to check whether collection " + name + " exists", e); } }
From source file:org.flywaydb.core.internal.dbsupport.MongoScript.java
License:Apache License
/** * Executes the MongoStatements found in this MongoScript against the database. * * @param mongoClient The MongoClient to use to execute this script. *//* www. j a v a2 s. co m*/ public void execute(final MongoClient mongoClient) { MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName); for (MongoStatement mongoStatement : mongoStatements) { LOG.debug("Executing MONGO: " + mongoStatement); try { mongoDatabase.runCommand(Document.parse(mongoStatement.getJson())); } catch (JsonParseException jpe) { MongoException e = new MongoException("Cannot parse mongo command. " + jpe.getMessage()); throw new FlywayMongoScriptException(resource, mongoStatement, e); } catch (MongoException e) { throw new FlywayMongoScriptException(resource, mongoStatement, e); } } }
From source file:org.flywaydb.core.internal.metadatatable.MongoMetaDataTable.java
License:Apache License
/** * Creates a new instance of a MongoMetaDataTable. * * @param client The MongoClient used to interact with the database. * @param dbName the database name where metadata collection will be created. * @param collectionName the metadata collection name. *//*from w w w . j a va2 s . c o m*/ public MongoMetaDataTable(MongoClient client, String dbName, String collectionName) { this.client = client; this.collectionName = collectionName; this.mongoDatabase = client.getDatabase(dbName); if (metadataCollectionExists()) { this.metadataCollection = mongoDatabase.getCollection(collectionName, BasicDBObject.class); } else { createMetadataCollection(dbName); } }
From source file:org.hillview.storage.MongoDBLoader.java
License:Open Source License
public MongoDBLoader(JdbcConnectionInformation info) { super(Converters.checkNull(info.table), null); this.info = info; assert info.database != null; assert info.password != null; MongoCredential credential = MongoCredential.createCredential(info.user, info.database, info.password.toCharArray()); ServerAddress address = new ServerAddress(info.host, info.port); MongoClientOptions options = MongoClientOptions.builder().build(); MongoClient client = new MongoClient(address); //, credential, options); this.database = client.getDatabase(info.database); //this.oldDatabase = client.getDB(info.database); }
From source file:org.immutables.mongo.fixture.ent.Ent.java
License:Apache License
public static void main(String... args) { MongoClient client = new MongoClient("localhost"); RepositorySetup setup = RepositorySetup.builder().database(client.getDatabase("test")) .executor(MoreExecutors.listeningDecorator(Executors.newCachedThreadPool())) .gson(new GsonBuilder().registerTypeAdapterFactory(new GsonAdaptersEnt()).create()).build(); EntRepository repository = new EntRepository(setup); EntRepository.Criteria where = repository.criteria().uuid("8b7a881c-6ccb-4ada-8f6a-60cc99e6aa20") .actionIn("BAN", "IPBAN"); Criteria or = where.expiresAbsent().or().with(where).expiresGreaterThan(TimeInstant.of(1467364749679L)); System.out.println(or);// w w w . j a va 2 s.c om repository.find(or).fetchAll().getUnchecked(); }
From source file:org.immutables.mongo.fixture.MongoContext.java
License:Apache License
private MongoContext(final MongoClient client) { Preconditions.checkNotNull(client, "client"); // allows to cleanup resources after each test final Closer closer = Closer.create(); closer.register(new Closeable() { @Override/* w w w .ja v a 2s. c o m*/ public void close() throws IOException { client.close(); } }); // drop database if exists (to have a clean test) if (Iterables.contains(client.listDatabaseNames(), DBNAME)) { client.getDatabase(DBNAME).drop(); } this.database = client.getDatabase(DBNAME); closer.register(new Closeable() { @Override public void close() throws IOException { database.drop(); } }); final ListeningExecutorService executor = MoreExecutors .listeningDecorator(Executors.newSingleThreadExecutor()); closer.register(new Closeable() { @Override public void close() throws IOException { MoreExecutors.shutdownAndAwaitTermination(executor, 100, TimeUnit.MILLISECONDS); } }); this.setup = RepositorySetup.builder().gson(createGson()).executor(executor).database(database).build(); this.closer = closer; }
From source file:org.jahia.services.usermanager.mongo.JahiaMongoConfig.java
License:Open Source License
/** * defines or update the context of the provider * @param context the Spring application context object * @param dictionary configuration parameters *//*from ww w . j av a 2 s .co m*/ public void setContext(final ApplicationContext context, final Dictionary<String, ?> dictionary) { final Properties userMongoProperties = new Properties(); final UserConfig userConfig = new UserConfig(); final Enumeration<String> keys = dictionary.keys(); String fileName = null; while (keys.hasMoreElements()) { final String key = keys.nextElement(); if (Constants.SERVICE_PID.equals(key) || ConfigurationAdmin.SERVICE_FACTORYPID.equals(key)) { continue; } else if ("felix.fileinstall.filename".equals(key)) { fileName = (String) dictionary.get(key); continue; } final Object value = dictionary.get(key); if (key.startsWith("user.")) { buildConfig(userMongoProperties, userConfig, key, value, true); } else { userMongoProperties.put(transformPropKeyToBeanAttr(key), value); } } try { // populate config beans BeanUtils.populate(userConfig, userMongoProperties); // handle defaults values userConfig.handleDefaults(); final String host = userConfig.getHost(); final String database = userConfig.getDatabase(); final MongoClient mongoClient = new MongoClient(host); final MongoDatabase mongoDatabase = mongoClient.getDatabase(database); if (mongoUserGroupProvider == null) { mongoUserGroupProvider = (MongoUserGroupProvider) context.getBean("mongoUserGroupProvider"); } else { // Deactivate the provider before reconfiguring it. mongoUserGroupProvider.unregister(); } mongoUserGroupProvider.setKey(providerKey); mongoUserGroupProvider.setUserConfig(userConfig); mongoUserGroupProvider.setMongoTemplateWrapper(new MongoTemplateWrapper(mongoDatabase)); // Activate (again). mongoUserGroupProvider.register(); } catch (IllegalAccessException | InvocationTargetException e) { LOGGER.error("Invalid Mongo configuration:" + fileName + ", " + "please refer to the Mongo configuration documentation", e); } }
From source file:org.jboss.as.quickstarts.kitchensink.util.Resources.java
License:Apache License
@Produces private MongoDatabase produceMongoDatabase(MongoClient mongoClient) { return mongoClient.getDatabase(System.getenv("DB_DATABASE")); }
From source file:org.jooby.mongodb.Mongodb.java
License:Apache License
protected void configure(final Env env, final Config config, final Binder binder, final BiConsumer<MongoClientURI, MongoClient> callback) { MongoClientOptions.Builder options = options(mongodb(config)); if (this.options != null) { this.options.accept(options, config); }//from w w w . ja v a 2 s .c o m MongoClientURI uri = new MongoClientURI(config.getString(db), options); String database = uri.getDatabase(); checkArgument(database != null, "Database not found: " + uri); MongoClient client = new MongoClient(uri); ServiceKey serviceKey = env.serviceKey(); serviceKey.generate(MongoClientURI.class, database, k -> binder.bind(k).toInstance(uri)); serviceKey.generate(MongoClient.class, database, k -> binder.bind(k).toInstance(client)); MongoDatabase mongodb = client.getDatabase(database); serviceKey.generate(MongoDatabase.class, database, k -> binder.bind(k).toInstance(mongodb)); env.onStop(client::close); callback.accept(uri, client); }
From source file:org.kaaproject.kaa.server.datamigration.EndpointProfileMigration.java
License:Apache License
/** * Add field use_raw_configuration_schema to endpointProfile that used to support devices using * SDK version 0.9.0// ww w.j a va2s. co m */ public void transform() { //mongo MongoClient client = new MongoClient(host); MongoDatabase database = client.getDatabase(dbName); MongoCollection<Document> endpointProfile = database.getCollection("endpoint_profile"); endpointProfile.updateMany(new Document(), eq("$set", eq("use_raw_schema", false))); //cassandra Cluster cluster = Cluster.builder().addContactPoint(host).build(); Session session = cluster.connect(dbName); session.execute("ALTER TABLE ep_profile ADD use_raw_schema boolean"); session.close(); cluster.close(); }