Example usage for com.mongodb MongoClientURI MongoClientURI

List of usage examples for com.mongodb MongoClientURI MongoClientURI

Introduction

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

Prototype

public MongoClientURI(final String uri) 

Source Link

Document

Creates a MongoURI from the given string.

Usage

From source file:org.restheart.Configuration.java

License:Open Source License

/**
 * Creates a new instance of Configuration from the configuration file For
 * any missing property the default value is used.
 *
 * @param conf the key-value configuration map
 * @param silent/*from w  w  w . ja va 2s.  c o m*/
 * @throws org.restheart.ConfigurationException
 */
public Configuration(Map<String, Object> conf, boolean silent) throws ConfigurationException {
    this.silent = silent;

    httpsListener = getAsBooleanOrDefault(conf, HTTPS_LISTENER, true);
    httpsPort = getAsIntegerOrDefault(conf, HTTPS_PORT_KEY, DEFAULT_HTTPS_PORT);
    httpsHost = getAsStringOrDefault(conf, HTTPS_HOST_KEY, DEFAULT_HTTPS_HOST);

    httpListener = getAsBooleanOrDefault(conf, HTTP_LISTENER_KEY, false);
    httpPort = getAsIntegerOrDefault(conf, HTTP_PORT_KEY, DEFAULT_HTTP_PORT);
    httpHost = getAsStringOrDefault(conf, HTTP_HOST_KEY, DEFAULT_HTTP_HOST);

    ajpListener = getAsBooleanOrDefault(conf, AJP_LISTENER_KEY, false);
    ajpPort = getAsIntegerOrDefault(conf, AJP_PORT_KEY, DEFAULT_AJP_PORT);
    ajpHost = getAsStringOrDefault(conf, AJP_HOST_KEY, DEFAULT_AJP_HOST);

    instanceName = getAsStringOrDefault(conf, INSTANCE_NAME_KEY, DEFAULT_INSTANCE_NAME);

    String _defaultRepresentationFromat = getAsStringOrDefault(conf, REPRESENTATION_FORMAT_KEY,
            DEFAULT_REPRESENTATION_FORMAT.name());

    REPRESENTATION_FORMAT rf = REPRESENTATION_FORMAT.PLAIN_JSON;
    ;

    try {
        rf = REPRESENTATION_FORMAT.valueOf(_defaultRepresentationFromat);
    } catch (IllegalArgumentException iar) {
        LOGGER.warn("wrong value for {}. allowed values are {}; " + "setting it to {}",
                REPRESENTATION_FORMAT_KEY, REPRESENTATION_FORMAT.values(), REPRESENTATION_FORMAT.PLAIN_JSON);
    } finally {
        defaultRepresentationFromat = rf;
    }

    useEmbeddedKeystore = getAsBooleanOrDefault(conf, USE_EMBEDDED_KEYSTORE_KEY, true);
    keystoreFile = getAsStringOrDefault(conf, KEYSTORE_FILE_KEY, null);
    keystorePassword = getAsStringOrDefault(conf, KEYSTORE_PASSWORD_KEY, null);
    certPassword = getAsStringOrDefault(conf, CERT_PASSWORD_KEY, null);

    try {
        mongoUri = new MongoClientURI(getAsStringOrDefault(conf, MONGO_URI_KEY, DEFAULT_MONGO_URI));
    } catch (IllegalArgumentException iae) {
        throw new ConfigurationException("wrong parameter " + MONGO_URI_KEY, iae);
    }

    List<Map<String, Object>> mongoMountsDefault = new ArrayList<>();
    Map<String, Object> defaultMongoMounts = new HashMap<>();
    defaultMongoMounts.put(MONGO_MOUNT_WHAT_KEY, "*");
    defaultMongoMounts.put(MONGO_MOUNT_WHERE_KEY, "/");
    mongoMountsDefault.add(defaultMongoMounts);

    mongoMounts = getAsListOfMaps(conf, MONGO_MOUNTS_KEY, mongoMountsDefault);

    applicationLogicMounts = getAsListOfMaps(conf, APPLICATION_LOGIC_MOUNTS_KEY, new ArrayList<>());

    staticResourcesMounts = getAsListOfMaps(conf, STATIC_RESOURCES_MOUNTS_KEY, new ArrayList<>());

    metadataNamedSingletons = getAsListOfMaps(conf, METADATA_NAMED_SINGLETONS_KEY, new ArrayList<>());

    Map<String, Object> idm = getAsMap(conf, IDM_KEY);
    Map<String, Object> am = getAsMap(conf, ACCESS_MANAGER_KEY);

    idmImpl = getAsStringOrDefault(idm, IMPLEMENTATION_CLASS_KEY, DEFAULT_IDM_IMPLEMENTATION_CLASS);
    idmArgs = idm;

    amImpl = getAsStringOrDefault(am, IMPLEMENTATION_CLASS_KEY, DEFAULT_AM_IMPLEMENTATION_CLASS);
    amArgs = am;

    logFilePath = getAsStringOrDefault(conf, LOG_FILE_PATH_KEY,
            URLUtils.removeTrailingSlashes(System.getProperty("java.io.tmpdir"))
                    .concat(File.separator + "restheart.log"));
    String _logLevel = getAsStringOrDefault(conf, LOG_LEVEL_KEY, "INFO");
    logToConsole = getAsBooleanOrDefault(conf, ENABLE_LOG_CONSOLE_KEY, true);
    logToFile = getAsBooleanOrDefault(conf, ENABLE_LOG_FILE_KEY, true);

    Level level;

    try {
        level = Level.valueOf(_logLevel);
    } catch (Exception e) {
        if (!silent) {
            LOGGER.info("wrong value for parameter {}: {}. using its default value {}", "log-level", _logLevel,
                    "INFO");
        }
        level = Level.INFO;
    }

    logLevel = level;

    requestsLimit = getAsIntegerOrDefault(conf, REQUESTS_LIMIT_KEY, 100);

    localCacheEnabled = getAsBooleanOrDefault(conf, LOCAL_CACHE_ENABLED_KEY, true);
    localCacheTtl = getAsLongOrDefault(conf, LOCAL_CACHE_TTL_KEY, (long) 1000);

    schemaCacheEnabled = getAsBooleanOrDefault(conf, SCHEMA_CACHE_ENABLED_KEY, true);
    schemaCacheTtl = getAsLongOrDefault(conf, SCHEMA_CACHE_TTL_KEY, (long) 1000);

    ioThreads = getAsIntegerOrDefault(conf, IO_THREADS_KEY, 2);
    workerThreads = getAsIntegerOrDefault(conf, WORKER_THREADS_KEY, 32);
    bufferSize = getAsIntegerOrDefault(conf, BUFFER_SIZE_KEY, 16384);
    buffersPerRegion = getAsIntegerOrDefault(conf, BUFFERS_PER_REGION_KEY, 20);
    directBuffers = getAsBooleanOrDefault(conf, DIRECT_BUFFERS_KEY, true);

    forceGzipEncoding = getAsBooleanOrDefault(conf, FORCE_GZIP_ENCODING_KEY, false);

    eagerPoolSize = getAsIntegerOrDefault(conf, EAGER_POOL_SIZE, 100);
    eagerLinearSliceWidht = getAsIntegerOrDefault(conf, EAGER_LINEAR_SLICE_WIDHT, 1000);
    eagerLinearSliceDelta = getAsIntegerOrDefault(conf, EAGER_LINEAR_SLICE_DELTA, 100);
    eagerLinearSliceHeights = getAsArrayOfInts(conf, EAGER_LINEAR_HEIGHTS, new int[] { 4, 2, 1 });
    eagerRndSliceMinWidht = getAsIntegerOrDefault(conf, EAGER_RND_SLICE_MIN_WIDHT, 1000);
    eagerRndMaxCursors = getAsIntegerOrDefault(conf, EAGER_RND_MAX_CURSORS, 50);

    authTokenEnabled = getAsBooleanOrDefault(conf, AUTH_TOKEN_ENABLED, true);
    authTokenTtl = getAsIntegerOrDefault(conf, AUTH_TOKEN_TTL, 15);

    Map<String, Object> etagCheckPolicies = getAsMap(conf, ETAG_CHECK_POLICY_KEY);

    if (etagCheckPolicies != null) {
        String _dbEtagCheckPolicy = getAsStringOrDefault(etagCheckPolicies, ETAG_CHECK_POLICY_DB_KEY,
                DEFAULT_DB_ETAG_CHECK_POLICY.name());

        String _collEtagCheckPolicy = getAsStringOrDefault(etagCheckPolicies, ETAG_CHECK_POLICY_COLL_KEY,
                DEFAULT_COLL_ETAG_CHECK_POLICY.name());

        String _docEtagCheckPolicy = getAsStringOrDefault(etagCheckPolicies, ETAG_CHECK_POLICY_DOC_KEY,
                DEFAULT_DOC_ETAG_CHECK_POLICY.name());

        ETAG_CHECK_POLICY validDbValue;
        ETAG_CHECK_POLICY validCollValue;
        ETAG_CHECK_POLICY validDocValue;

        try {
            validDbValue = ETAG_CHECK_POLICY.valueOf(_dbEtagCheckPolicy);
        } catch (IllegalArgumentException iae) {
            LOGGER.warn("wrong value for parameter {} setting it to default value {}", ETAG_CHECK_POLICY_DB_KEY,
                    DEFAULT_DB_ETAG_CHECK_POLICY);
            validDbValue = DEFAULT_DB_ETAG_CHECK_POLICY;
        }

        dbEtagCheckPolicy = validDbValue;

        try {

            validCollValue = ETAG_CHECK_POLICY.valueOf(_collEtagCheckPolicy);
        } catch (IllegalArgumentException iae) {
            LOGGER.warn("wrong value for parameter {} setting it to default value {}",
                    ETAG_CHECK_POLICY_COLL_KEY, DEFAULT_COLL_ETAG_CHECK_POLICY);
            validCollValue = DEFAULT_COLL_ETAG_CHECK_POLICY;
        }

        collEtagCheckPolicy = validCollValue;

        try {
            validDocValue = ETAG_CHECK_POLICY.valueOf(_docEtagCheckPolicy);
        } catch (IllegalArgumentException iae) {
            LOGGER.warn("wrong value for parameter {} setting it to default value {}",
                    ETAG_CHECK_POLICY_COLL_KEY, DEFAULT_COLL_ETAG_CHECK_POLICY);
            validDocValue = DEFAULT_DOC_ETAG_CHECK_POLICY;
        }

        docEtagCheckPolicy = validDocValue;
    } else {
        dbEtagCheckPolicy = DEFAULT_DB_ETAG_CHECK_POLICY;
        collEtagCheckPolicy = DEFAULT_COLL_ETAG_CHECK_POLICY;
        docEtagCheckPolicy = DEFAULT_DOC_ETAG_CHECK_POLICY;
    }

    logExchangeDump = getAsIntegerOrDefault(conf, LOG_REQUESTS_LEVEL_KEY, 0);

    connectionOptions = getAsMap(conf, CONNECTION_OPTIONS_KEY);
}

From source file:org.seasr.meandre.components.tools.db.mongodb.MongoDBClient.java

License:Open Source License

@Override
public void initializeCallBack(ComponentContextProperties ccp) throws Exception {
    String location = getPropertyOrDieTrying(PROP_MONGODB_SERVER_LOCATION, ccp);
    String readPreference = getPropertyOrDieTrying(PROP_MONGODB_READ_PREFERENCE, ccp);

    console.fine(String.format("Got mongo server location %s", location));

    try {// ww w . j  av  a 2  s.  c o  m
        mongoClientURI = new MongoClientURI(location);
        mongoClient = new MongoClient(mongoClientURI);
    } catch (IllegalArgumentException e) {
        console.warning(String.format(
                "Could not interpret %s as a mongo URI, interpreting as a server:port string.", location));
        console.warning(String.format("Exception reason: %s", e.getMessage()));
        mongoClient = new MongoClient(location);
    }
    if (readPreference != "")
        mongoClient.setReadPreference(ReadPreference.valueOf(readPreference));
    //mongoClient.logger.
    if (Boolean.parseBoolean(getPropertyOrDieTrying(PROP_MONGODB_RESTRICT_LOGGING, ccp))) {
        Logger.getLogger("com.mongodb.ReplicaSetStatus").setLevel(Level.SEVERE);
    }

    console.fine(String.format("Connected to mongodb with URI/location %s ", location));
}

From source file:org.sglover.alfrescoextensions.common.MongoDbFactory.java

License:Open Source License

public DB createInstance() throws Exception {
    DB db = null;/* w ww .ja v a  2  s. c  o m*/

    try {
        if (enabled) {
            if (embedded) {
                Mongo mongo = newMongo();
                //                    Mongo mongo = mongoFactory.newMongo();
                if (dbName != null) {
                    db = mongo.getDB(dbName);
                } else {
                    db = mongo.getDB(UUID.randomUUID().toString());
                }
            } else {
                if (mongoURI == null || dbName == null) {
                    throw new RuntimeException("Must provide mongoURI and dbName or a mongo object");
                }
                MongoClientURI uri = new MongoClientURI(mongoURI);
                MongoClient mongoClient = new MongoClient(uri);
                db = mongoClient.getDB(dbName);
            }

            if (db == null) {
                throw new InstantiationException("Could not instantiate a Mongo DB instance");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Instatiated DB object for dbName '" + db.getName() + "'");
            }
            CommandResult stats = db.getStats();
            if (logger.isTraceEnabled()) {
                stats = db.getStats();
                for (String key : stats.keySet()) {
                    logger.trace("\t" + key + " = " + stats.get(key).toString());
                }
            }
        }
    } catch (MongoException.Network e) {
        throw new MongoDbUnavailableException("Mongo network exception, database down?", e);
    } catch (UnknownHostException e) {
        throw new MongoDbUnavailableException("Mongo host not found", e);
    }
    return db;
}

From source file:org.springframework.data.mongodb.microbenchmark.MongoResultsWriter.java

License:Apache License

@Override
public void write(Collection<RunResult> results) {

    Date now = new Date();
    StandardEnvironment env = new StandardEnvironment();

    String projectVersion = env.getProperty("project.version", "unknown");
    String gitBranch = env.getProperty("git.branch", "unknown");
    String gitDirty = env.getProperty("git.dirty", "no");
    String gitCommitId = env.getProperty("git.commit.id", "unknown");

    MongoClientURI uri = new MongoClientURI(this.uri);
    MongoClient client = new MongoClient(uri);

    String dbName = StringUtils.hasText(uri.getDatabase()) ? uri.getDatabase()
            : "spring-data-mongodb-benchmarks";
    MongoDatabase db = client.getDatabase(dbName);

    for (BasicDBObject dbo : (List<BasicDBObject>) JSON.parse(ResultsWriter.jsonifyResults(results))) {

        String collectionName = extractClass(dbo.get("benchmark").toString());

        Document sink = new Document();
        sink.append("_version", projectVersion);
        sink.append("_branch", gitBranch);
        sink.append("_commit", gitCommitId);
        sink.append("_dirty", gitDirty);
        sink.append("_method", extractBenchmarkName(dbo.get("benchmark").toString()));
        sink.append("_date", now);
        sink.append("_snapshot", projectVersion.toLowerCase().contains("snapshot"));

        sink.putAll(dbo);//from w  w w . jav  a2 s. c  o  m

        db.getCollection(collectionName).insertOne(fixDocumentKeys(sink));
    }

    client.close();
}

From source file:org.teiid.resource.adapter.mongodb.MongoDBManagedConnectionFactory.java

License:Open Source License

protected MongoClientURI getConnectionURI() {
    String serverlist = getRemoteServerList();
    if (serverlist.startsWith("mongodb://")) { //$NON-NLS-1$       
        return new MongoClientURI(getRemoteServerList());
    }/*ww w  .  jav a  2  s . c  om*/
    return null;
}

From source file:org.trade.core.hazelcast.AMongoStore.java

License:Apache License

@Override
public void init(HazelcastInstance hazelcastInstance, Properties properties, String mapName) {
    String mongoUrl = (String) properties.get("mongo.url");
    String dbName = (String) properties.get("mongo.db");

    Morphia morphia = new Morphia();

    // Map model classes to db collections
    morphia.mapPackage("org.trade.core.model.data");

    // create the datastore connecting to mongo
    this.store = morphia.createDatastore(new MongoClient(new MongoClientURI(mongoUrl)), dbName);
    this.store.ensureIndexes();
}

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public byte[] loadBinaryData(String collectionName, String identifier) throws Exception {
    byte[] data = new byte[0];

    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    Document doc = db.getCollection(collectionName).find(Filters.eq(IDENTIFIER_FIELD, identifier)).limit(1)
            .first();//from w  ww. j  a  v a2s. c o m

    if (doc != null) {
        if (doc.containsKey(DATA_FIELD)) {
            data = ((Binary) doc.get(DATA_FIELD)).getData();
        } else {
            logger.info("Model object '{}' from model collection '{}' does not have any associated data at the "
                    + "moment.", identifier, collectionName);
        }
    } else {
        logger.info("The database does not know the specified model object '{}' from model collection '{}'",
                identifier, collectionName);
    }

    client.close();

    return data;
}

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public void storeBinaryData(byte[] data, String collectionName, String identifier) throws Exception {
    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    MongoCollection<Document> collection = db.getCollection(collectionName);
    Document doc = collection.find(Filters.eq(IDENTIFIER_FIELD, identifier)).limit(1).first();

    if (data == null) {
        // We assume that if the value is set to null, we should delete also the corresponding database entry
        if (doc != null) {
            collection.deleteOne(Filters.eq(IDENTIFIER_FIELD, identifier));
        }//from   w  w  w  .j a  va 2 s  .  c om
    } else {
        // Check if the document already exists and update it
        if (doc != null) {
            collection.updateOne(Filters.eq(IDENTIFIER_FIELD, identifier),
                    Updates.combine(Updates.set(DATA_FIELD, data), Updates.currentDate("lastModified")));
        } else {
            Document document = new Document(IDENTIFIER_FIELD, identifier).append(DATA_FIELD, data)
                    .append("lastModified", new Date());
            collection.insertOne(document);
        }
    }

    client.close();
}

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public void deleteBinaryData(String collectionName, String identifier) throws Exception {
    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    Document doc = db.getCollection(collectionName).findOneAndDelete(Filters.eq(IDENTIFIER_FIELD, identifier));

    if (doc != null) {
        logger.info("Model object '{}' from model collection '{}' and its associated data successfully deleted "
                + "from DB.", identifier, collectionName);
    } else {//ww  w .  j av  a 2  s  .c  o m
        logger.info("The database does not know the specified model object '{}' from model collection '{}'",
                identifier, collectionName);
    }

    client.close();
}

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

private void initializeMorphiaMapping() {
    // Check if the mapping is already initialized, if not trigger the mapping
    if (!isMorphiaMappingInitialized) {
        Morphia morphia = new Morphia();
        morphia.getMapper().getOptions().setMapSubPackages(true);

        // Map model classes to db collections
        morphia.mapPackage("org.trade.core.model.data");

        // create the datastore connecting to mongo
        this.store = morphia.createDatastore(new MongoClient(new MongoClientURI(mongoUrl)), dbName);
        this.store.ensureIndexes();
    }/*from www  . j  a  v a  2 s .  co m*/
}