Example usage for com.mongodb MongoClientOptions builder

List of usage examples for com.mongodb MongoClientOptions builder

Introduction

In this page you can find the example usage for com.mongodb MongoClientOptions builder.

Prototype

public static Builder builder() 

Source Link

Document

Creates a builder instance.

Usage

From source file:com.torodb.testing.mongodb.docker.SingleMongod.java

License:Apache License

public SingleMongod(Version version) {
    this(version, MongoClientOptions.builder().build());
}

From source file:com.vidico.jsp.listener.MongoDBContextListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {/*from   w w w. j  a va 2s . c  om*/
        ServletContext ctx = sce.getServletContext();

        MongoClientURI uri = null;
        uri = new MongoClientURI("mongodb://vishal:vishal@ds057066.mlab.com:57066/vidico",
                MongoClientOptions.builder().cursorFinalizerEnabled(false));
        MongoClient mongo = new MongoClient(uri);

        //            MongoClient mongo = new MongoClient(
        //                    ctx.getInitParameter("MONGODB_HOST"),
        //                    Integer.parseInt(ctx.getInitParameter("MONGODB_PORT")));
        System.out.println("MongoClient initialized successfully");
        sce.getServletContext().setAttribute("MONGO_CLIENT", mongo);
    } catch (Exception e) {
        throw new RuntimeException("MongoClient init failed " + e.getMessage());
    }
}

From source file:de.anycook.db.drafts.mongo.Mongo.java

License:Open Source License

protected Mongo() {
    logger = LogManager.getLogger(getClass());

    final CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(new DraftCodecProvider()), MongoClient.getDefaultCodecRegistry());
    final MongoClientOptions options = MongoClientOptions.builder().codecRegistry(codecRegistry).build();
    client = new MongoClient(new ServerAddress(), options);
}

From source file:de.taimos.dvalin.mongo.MongoClientOptionsFactory.java

License:Apache License

@Override
public MongoClientOptions.Builder getObject() throws Exception {
    Builder builder = MongoClientOptions.builder();
    builder.socketTimeout(this.socketTimeout);
    builder.connectTimeout(this.connectTimeout);
    return builder;
}

From source file:de.taimos.dvalin.mongo.MongoClientOptionsFactory.java

License:Apache License

@Override
public Class<?> getObjectType() {
    return MongoClientOptions.Builder.class;
}

From source file:demo.MongoTestSupport.java

License:Apache License

/**
 * Try to obtain and validate a resource. Implementors should either set the {@link #resource} field with a valid
 * resource and return normally, or throw an exception.
 *///from   w ww .  j  a  v a2s . c  om
protected void obtainResource() throws Exception {
    this.resource = new MongoClient("localhost", MongoClientOptions.builder().connectTimeout(300).build());
    this.resource.getDatabaseNames();
}

From source file:DutyDatabase.DutyScheduleDB.java

License:Open Source License

/**
 * Creates a connection to a running MongoDB instance using the required codecs.
 *//*from  w  w w.  j a  v a  2  s  .c  o  m*/
public DutyScheduleDB() {
    //Create codec registry with LocalDateCodec.
    CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
            CodecRegistries.fromCodecs(new LocalDateCodec()),
            CodecRegistries.fromProviders(new RaCodecProvider(), new DutyBlockCodecProvider(),
                    new ScheduledDutyCodecProvider()),
            MongoClient.getDefaultCodecRegistry());
    MongoClientOptions options = MongoClientOptions.builder().codecRegistry(codecRegistry).build();
    mongoClient = new MongoClient(new ServerAddress(), options);
    db = mongoClient.getDatabase("DutySchedulerDB");
}

From source file:ec.edu.espe.persistence.PersistenceManager.java

public PersistenceManager() {
    MongoClientOptions mongoOptions = MongoClientOptions.builder().socketTimeout(60000).connectTimeout(60000)
            .build();/*  w ww.  j  a v a2  s  .co  m*/

    try {

        //mongoClient = new MongoClient(new ServerAddress("ds038739.mlab.com:38739"), mongoOptions);
        String textUri = "mongodb://xmatch:xmatch@ds038739.mlab.com:38739/xmatch";
        MongoClientURI uri = new MongoClientURI(textUri);
        mongoClient = new MongoClient(uri);
    } catch (Exception e) {

        throw new RuntimeException("Error", e);
    }

    mongoClient.setWriteConcern(WriteConcern.SAFE);
    mongoClient.setReadPreference(ReadPreference.primary());
    morphia = new Morphia();

    morphia.mapPackage(DB_PACKAGE, true);
    mds = morphia.createDatastore(mongoClient, DB_NAME);
    mds.ensureIndexes();
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

private MongoClient client() {
    mutex.lock();/*from w ww  .  j  a v a2s  . co m*/
    try {
        if (__client == null) {
            final MongoClientOptions options = MongoClientOptions.builder()
                    .readPreference(ReadPreference.nearest()).writeConcern(WriteConcern.ACKNOWLEDGED).build();
            final Splitter splitter = on(':').trimResults().omitEmptyStrings().limit(2);
            final List<ServerAddress> seeds = from(CONFIG_MANAGER.getDbHosts())
                    .transform(new Function<String, ServerAddress>() {
                        @Override
                        public ServerAddress apply(final String entry) {
                            ServerAddress seed = null;
                            try {
                                final List<String> tokens = splitter.splitToList(entry);
                                switch (tokens.size()) {
                                case 1:
                                    seed = new ServerAddress(tokens.get(0), 27017);
                                    break;
                                case 2:
                                    int port = parseInt(tokens.get(1));
                                    seed = new ServerAddress(tokens.get(0), port);
                                    break;
                                default:
                                    break;
                                }
                            } catch (Exception e) {
                                LOGGER.error("Invalid host", e);
                            }
                            return seed;
                        }
                    }).filter(notNull()).toList();
            // enable/disable authentication (requires MongoDB server to be configured to support authentication)
            final List<MongoCredential> credentials = newArrayList();
            if (!CONFIG_MANAGER.isAnonymousDbAccess()) {
                credentials.add(createMongoCRCredential(CONFIG_MANAGER.getDbUsername(),
                        CONFIG_MANAGER.getDbName(), CONFIG_MANAGER.getDbPassword().toCharArray()));
            }
            __client = new MongoClient(seeds, credentials, options);
            // check class attributes accessed by reflection
            try {
                final Field metadataField = BaseFile.class.getDeclaredField(METADATA_ATTR);
                checkNotNull(metadataField, "Metadata property (" + METADATA_ATTR + ") not found in file base: "
                        + BaseFile.class.getCanonicalName());
                final Class<?> metadataType = metadataField.getType();
                checkState(Versionable.class.isAssignableFrom(metadataType),
                        "Metadata does not implements versionable: " + metadataType.getCanonicalName());
                checkNotNull(Versionable.class.getDeclaredField(IS_LATEST_VERSION_ATTR),
                        "Version property (" + IS_LATEST_VERSION_ATTR + ") not found in versionable: "
                                + Versionable.class.getCanonicalName());
                checkNotNull(metadataType.getDeclaredField(OPEN_ACCESS_LINK_ATTR),
                        "Open access link property (" + OPEN_ACCESS_LINK_ATTR + ") not found in metadata: "
                                + metadataType.getCanonicalName());
                checkNotNull(metadataType.getDeclaredField(OPEN_ACCESS_DATE_ATTR),
                        "Open access date property (" + OPEN_ACCESS_DATE_ATTR + ") not found in metadata: "
                                + metadataType.getCanonicalName());
            } catch (Exception e) {
                throw new IllegalStateException(
                        "Object versioning needs a compatible version of the LVL core library, but none is available",
                        e);
            }
        }
        return __client;
    } finally {
        mutex.unlock();
    }
}

From source file:example.GSSAPICredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    // Set this property to avoid the default behavior where the program prompts on the command line for username/password
    //        Security.setProperty("auth.login.defaultCallbackHandler", "example.DefaultSecurityCallbackHandler");

    String server = args[0];/*from  w  ww.  j  av a  2 s  .  co  m*/
    String user = args[1];
    String databaseName = args[2];

    System.out.println("javax.security.auth.useSubjectCredsOnly: "
            + System.getProperty("javax.security.auth.useSubjectCredsOnly"));
    System.out.println("java.security.krb5.realm: " + System.getProperty("java.security.krb5.realm"));
    System.out.println("java.security.krb5.kdc: " + System.getProperty("java.security.krb5.kdc"));
    System.out.println(
            "auth.login.defaultCallbackHandler: " + Security.getProperty("auth.login.defaultCallbackHandler"));
    System.out.println("login.configuration.provider: " + Security.getProperty("login.configuration.provider"));
    System.out.println(
            "java.security.auth.login.config: " + Security.getProperty("java.security.auth.login.config"));
    System.out.println("login.config.url.1: " + Security.getProperty("login.config.url.1"));
    System.out.println("login.config.url.2: " + Security.getProperty("login.config.url.2"));
    System.out.println("login.config.url.3: " + Security.getProperty("login.config.url.3"));

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("database: " + databaseName);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            asList(MongoCredential.createGSSAPICredential(user).withMechanismProperty("SERVICE_NAME",
                    "mongodb")),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongoClient.getDB(databaseName);

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));
    System.out.println("Count: " + testDB.getCollection("test").count());
}