org.bson.codecs.pojo.PojoCodecProvider Java Examples

The following examples show how to use org.bson.codecs.pojo.PojoCodecProvider. 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: Mongo.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * Get default mongodb database reference or initiate it if not initialized.
 *
 * @param connectionString MongoDB standard connection string
 * @param database         mongodb database name
 * @return MongoDB mongodb client database reference.
 */
public static MongoDatabase getOrInitDefaultDatabase(String connectionString, String database) {
    if (DEFAULT_DATABASE == null) {
        synchronized (LOCK) {
            if (DEFAULT_DATABASE == null) {
                if (!StringUtil.isEmpty(connectionString)) {
                    DEFAULT_CLIENT = MongoClients.create(connectionString);
                    CodecRegistry pojoCodecRegistry = fromRegistries(
                            /*fromCodecs(new StringCodecExt()),*/
                            MongoClientSettings.getDefaultCodecRegistry(),
                            fromProviders(PojoCodecProvider.builder().automatic(true).build()));
                    DEFAULT_DATABASE = DEFAULT_CLIENT.getDatabase(database).withCodecRegistry(pojoCodecRegistry);
                } else {
                    throw new RuntimeException("No datasource configuration found for mongodb.");
                }
            }
        }
    }
    return DEFAULT_DATABASE;
}
 
Example #2
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 #3
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 #4
Source File: NewsServiceApp.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Bean
MongoClient mongoClient(MongoProperties properties) {
    ConnectionString connectionString = new ConnectionString(properties.determineUri());
    MongoClientSettings.Builder builder = MongoClientSettings
            .builder()
            .streamFactoryFactory(NettyStreamFactory::new)
            .applyToClusterSettings(b -> b.applyConnectionString(connectionString))
            .applyToConnectionPoolSettings(b -> b.applyConnectionString(connectionString))
            .applyToServerSettings(b -> b.applyConnectionString(connectionString))
            .applyToSslSettings(b -> b.applyConnectionString(connectionString))
            .applyToSocketSettings(b -> b.applyConnectionString(connectionString))
            .codecRegistry(fromRegistries(
                MongoClients.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder()
                                               .automatic(true)
                                               .register(News.class)
                                               .build())
            ));

    if (connectionString.getReadPreference() != null) {
        builder.readPreference(connectionString.getReadPreference());
    }
    if (connectionString.getReadConcern() != null) {
        builder.readConcern(connectionString.getReadConcern());
    }
    if (connectionString.getWriteConcern() != null) {
        builder.writeConcern(connectionString.getWriteConcern());
    }
    if (connectionString.getApplicationName() != null) {
        builder.applicationName(connectionString.getApplicationName());
    }
    return MongoClients.create(builder.build());
}
 
Example #5
Source File: WithEmbeddedMongo.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
default MongoClient mongoClient() {
    ConnectionString connectionString = new ConnectionString("mongodb://localhost/news");
    MongoClientSettings.Builder builder = MongoClientSettings.builder()
            .streamFactoryFactory(NettyStreamFactory::new)
            .applyToClusterSettings((cs) -> cs
                    .applyConnectionString(connectionString))
            .applyToConnectionPoolSettings(cps -> cps
                    .applyConnectionString(connectionString))
            .applyToServerSettings(ss -> ss
                    .applyConnectionString(connectionString))
          // TODO: Do not work with JDK11 without the next line being commented (null is not allowed)
          //.credential(connectionString.getCredential())
            .applyToSslSettings(ss -> ss
                    .applyConnectionString(connectionString))
            .applyToSocketSettings(ss -> ss
                    .applyConnectionString(connectionString))
            .codecRegistry(fromRegistries(
                    MongoClients.getDefaultCodecRegistry(),
                    fromProviders(PojoCodecProvider.builder()
                            .automatic(true)
                            .register(News.class)
                            .build())
            ));

    if (connectionString.getReadPreference() != null) {
        builder.readPreference(connectionString.getReadPreference());
    }
    if (connectionString.getReadConcern() != null) {
        builder.readConcern(connectionString.getReadConcern());
    }
    if (connectionString.getWriteConcern() != null) {
        builder.writeConcern(connectionString.getWriteConcern());
    }
    if (connectionString.getApplicationName() != null) {
        builder.applicationName(connectionString.getApplicationName());
    }

    return MongoClients.create(builder.build());
}
 
Example #6
Source File: Main.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args   ) {
    LOG.info("MongoDB demo starting ...");
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    MongoClient mongoClient = new MongoClient( Utils.SERVER_HOSTNAME, MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
    MongoDatabase database = mongoClient.getDatabase(Utils.DB_NAME);
    RoleService roleService = new RoleServiceImpl(database);
    Collection<Role> roles = roleService.getRoles();
    LOG.info("Roles: {}", roles.size());
    LOG.info("MongoDB demo done.");
}
 
Example #7
Source File: RoleServiceITTest.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void init() throws DataException {
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    mongoClient = new MongoClient( Utils.SERVER_HOSTNAME, MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
    database = mongoClient.getDatabase(Utils.DB_NAME);
    roleService = new RoleServiceImpl(database);
    roleService.removeAll();
}
 
Example #8
Source File: MongoDbDAO.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public void init() throws SQLException {

		CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),fromProviders(PojoCodecProvider.builder().automatic(true).build()));
			client = new MongoClient(new ServerAddress(getString(SERVERNAME), getInt(SERVERPORT)),MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
			db = client.getDatabase(getString(DB_NAME)).withCodecRegistry(pojoCodecRegistry);
			createDB();
			logger.info("init " + getName() + " done");
		
	}
 
Example #9
Source File: MongoConfig.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@Override
@Bean
public com.mongodb.client.MongoClient mongoClient() {
	final CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
			fromProviders(PojoCodecProvider.builder().automatic(true).build()));

	final String connectionsString = String.format("mongodb://%s:%s@%s:%s", this.username, this.password, this.host, this.port);
	final MongoClientSettings settings = MongoClientSettings.builder()
			.codecRegistry(pojoCodecRegistry)
			.applyConnectionString(new ConnectionString(
					connectionsString))
			.build();

	return MongoClients.create(settings);
}
 
Example #10
Source File: MongoConfig.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoClient legacyMongoClient() {
	final CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
			fromProviders(PojoCodecProvider.builder().automatic(true).build()));
	final MongoClientOptions options = MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build();

	final MongoCredential credentials = MongoCredential.createScramSha1Credential(this.username, "admin", this.password.toCharArray());
	return new MongoClient(new ServerAddress(this.host, NumberUtils.toInt(this.port)), credentials, options);
}
 
Example #11
Source File: PojoQuickTour.java    From xian with Apache License 2.0 4 votes vote down vote up
/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 */
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = MongoClients.create();
    } else {
        mongoClient = MongoClients.create(args[0]);
    }

    // create codec registry for POJOs
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(pojoCodecRegistry);

    // get a handle to the "people" collection
    MongoCollection<Person> collection = database.getCollection("people", Person.class);

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
    System.out.println("Original Person Model: " + ada);
    collection.insertOne(ada);

    // Person will now have an ObjectId
    System.out.println("Mutated Person Model: " + ada);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Person somebody = collection.find().first();
    System.out.println(somebody);

    // now, lets add some more people so we can explore queries and cursors
    List<Person> people = asList(
            new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")),
            new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")),
            new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null))
    );

    collection.insertMany(people);
    System.out.println("total # of people " + collection.countDocuments());

    System.out.println("");
    // lets get all the documents in the collection and print them out
    Block<Person> printBlock = new Block<Person>() {
        @Override
        public void apply(final Person person) {
            System.out.println(person);
        }
    };

    collection.find().forEach(printBlock);

    System.out.println("");
    // now use a query to get 1 document out
    somebody = collection.find(eq("address.city", "Wimborne")).first();
    System.out.println(somebody);

    System.out.println("");
    // now lets find every over 30
    collection.find(gt("age", 30)).forEach(printBlock);

    System.out.println("");
    // Update One
    collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace")));

    System.out.println("");
    // Update Many
    UpdateResult updateResult = collection.updateMany(not(eq("zip", null)), set("zip", null));
    System.out.println(updateResult.getModifiedCount());

    System.out.println("");
    // Replace One
    updateResult = collection.replaceOne(eq("name", "Ada Lovelace"), ada);
    System.out.println(updateResult.getModifiedCount());

    // Delete One
    collection.deleteOne(eq("address.city", "Wimborne"));

    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(eq("address.city", "London"));
    System.out.println(deleteResult.getDeletedCount());

    // Clean up
    database.drop();

    // release resources
    mongoClient.close();
}