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:ohtu.productservice.Main.java

public static void main(String args[]) throws IOException {
    port(4568);//  w  w w.  ja v a 2  s.  c o  m
    Gson gson = new Gson();

    String configurationsUrl = System.getenv("CONF_API");
    ;

    HttpResponse hrConf = Request.Get(configurationsUrl).execute().returnResponse();

    String responseAsJson = IOUtils.toString(hrConf.getEntity().getContent(), Charset.forName("UTF-8"));

    UrlCollection urlCollection = gson.fromJson(responseAsJson, UrlCollection.class);

    String tokenUrl = urlCollection.token();
    String mongoLab = urlCollection.mongourl();

    MongoClientURI uri = new MongoClientURI(mongoLab);

    Morphia morphia = new Morphia();

    MongoClient mongo = new MongoClient(uri);

    morphia.mapPackage("ohtu.domainlib");

    Datastore datastore = morphia.createDatastore(mongo, "kanta11");

    get("/ping", (request, response) -> {
        String name = ManagementFactory.getRuntimeMXBean().getName();
        String dir = System.getProperty("user.dir");

        return "{ \"name\": \"" + name + "\", \"dir\": \"" + dir + "\" }";
    });

    before("/products", (request, response) -> {
        StrongTextEncryptor kryptoniter = new StrongTextEncryptor();
        kryptoniter.setPassword(System.getenv("OHTU_KRYPTO"));
        String encrypted_token = request.headers("Authorization");
        String decrypted_token = kryptoniter.decrypt(encrypted_token);

        System.out.println("decrypted token: " + decrypted_token);

        //trycatch thn.
        DateTimeToken dtt_auth = gson.fromJson(decrypted_token, DateTimeToken.class);

        DateTimeToken dtt_now = DateTimeToken.generate(0);

        System.out.println("auth: " + dtt_auth.toString());
        System.out.println("now: " + dtt_now.toString());
        System.out.println("auth is after now: " + dtt_auth.isAfter(dtt_now));

        if (!dtt_auth.isAfter(dtt_now)) {
            halt(401, gson.toJson(Error.withCause("missing, invalid or expired token")));
        }

        //            preFilter(request);
        //            HttpResponse hr = Request.Get(tokenUrl)
        //                    .addHeader("Authorization", request.headers("Authorization"))
        //                    .execute().returnResponse();
        //            
        //            
        //            if (EntityUtils.toString(hr.getEntity()).equals("0"))
        //            {
        //                halt(401, gson.toJson(Error.withCause("invalid token")));
        //            }

        //System.out.println("hr.getentity adasd"+EntityUtils.toString(hr.getEntity()));
    });

    get("/products", (request, response) -> {
        preFilter(request);

        return datastore.find(Product.class).asList();
    }, new JsonTransformer());

    post("/products", (request, response) -> {
        preFilter(request);

        Product product = gson.fromJson(request.body(), Product.class);

        if (product == null) {
            halt(401, gson.toJson(Error.withCause("invalid credenials")));
        }

        if (datastore.createQuery(Product.class).field("name").equal(product.name()).get() != null) {
            halt(400, gson.toJson(Error.withCause("name must be unique")));
        }

        datastore.save(product);

        return product;
    }, new JsonTransformer());

}

From source file:org.alfresco.bm.tools.BMTestRunner.java

License:Open Source License

/**
 * Execute the default test against the given MongoDB or an in-memory instance
 * //from   w  w  w. j a va 2s .  c o  m
 * @param mongoConfigHost           the MongoDB host to connect to for configuraton data or <tt>null</tt> to use an in-memory version
 * @param mongoTestHost             the MongoDB host to connect to for test data data or <tt>null</tt> to use the same database as the config
 * @param testProperties            any properties to specifically set for the test or <tt>null</tt> if there are none
 */
public void run(String mongoConfigHost, String mongoTestHost, Properties testProperties) throws Exception {
    // Secure the listeners against modification
    List<BMTestRunnerListener> listeners = new ArrayList<BMTestRunnerListener>(this.listeners);

    // If no MongoDB URL is provided, then we have to start one
    MongoDBForTestsFactory mongoDBForTestsFactory = null;
    ClassPathXmlApplicationContext ctx = null;
    try {
        // Ensure that required system properties are present
        System.setProperty(PROP_APP_CONTEXT_PATH, System.getProperty("user.dir"));
        System.setProperty(PROP_APP_DIR, System.getProperty("user.dir"));

        // Create a MongoDB for use if one has not been specified
        if (mongoConfigHost == null) {
            mongoDBForTestsFactory = new MongoDBForTestsFactory();
            String uriWithoutDB = mongoDBForTestsFactory.getMongoURIWithoutDB();
            mongoConfigHost = new MongoClientURI(uriWithoutDB).getHosts().get(0);
        }
        // Fill in the URI for the test MongoDB
        if (mongoTestHost == null) {
            mongoTestHost = mongoConfigHost;
        }

        // Fill in the properties required for the test
        Properties mongoProps = new Properties();
        mongoProps.put(PROP_MONGO_CONFIG_HOST, mongoConfigHost);

        // Construct the application context
        ctx = new ClassPathXmlApplicationContext(new String[] { PATH_APP_CONTEXT }, false);
        // Push cluster properties into the context (must be done AFTER setting parent context)
        ConfigurableEnvironment ctxEnv = ctx.getEnvironment();
        // Mongo properties come first
        ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("mongo-props", mongoProps));
        // Finally, system properties overrule them all
        ctxEnv.getPropertySources()
                .addFirst(new PropertiesPropertySource("system-props", System.getProperties()));

        // Kick it all off
        try {
            ctx.refresh();
        } catch (Exception e) {
            Throwable root = ExceptionUtils.getRootCause(e);
            if (root != null
                    && (root instanceof MongoSocketException || root instanceof UnknownHostException)) {
                // We deal with this specifically as it's a simple case of not finding the MongoDB
                logger.error("Set the configuration property '" + PROP_MONGO_CONFIG_HOST
                        + "' (<server>:<port>) as required.");
            } else {
                // Log application start failure because test frameworks might not do so nicely
                logger.error("Failed to start application.", e);
            }
            throw new RuntimeException("Failed to start application.", e);
        }

        // Get the test
        Test test = ctx.getBean(Test.class);
        String release = test.getRelease();
        Integer schema = test.getSchema();

        TestRestAPI api = ctx.getBean(TestRestAPI.class);

        // Create a new test
        TestDetails testDetails = new TestDetails();
        String testName = "BMTestRunner_" + System.currentTimeMillis();
        testDetails.setName(testName);
        testDetails.setDescription("Test created by BMTestRunner on " + new Date());
        testDetails.setRelease(release);
        testDetails.setSchema(schema);
        api.createTest(testDetails);

        // We need to tell the test which MongoDB to write data to
        PropSetBean propSet = new PropSetBean();
        propSet.setValue(mongoTestHost);
        propSet.setVersion(0);
        api.setTestProperty(testName, PROP_MONGO_TEST_HOST, propSet);

        // Now set any properties that have been explicitly passed in for the test
        if (testProperties != null) {
            for (Map.Entry<Object, Object> entry : testProperties.entrySet()) {
                String propKey = (String) entry.getKey();
                String propVal = (String) entry.getValue();

                propSet.setValue(propVal);
                propSet.setVersion(0);
                api.setTestProperty(testName, propKey, propSet);
            }
        }

        // Call listeners: the test has been created
        for (BMTestRunnerListener listener : listeners) {
            listener.testReady(ctx, testName);
        }

        // Create a new test run
        TestRunDetails testRunDetails = new TestRunDetails();
        String testRunName = "BMTestRunner_" + System.currentTimeMillis();
        testRunDetails.setName(testRunName);
        testRunDetails.setDescription("Test run created by BMTestRunner on " + new Date());
        api.createTestRun(testDetails.getName(), testRunDetails);

        // Call listeners: the test run has been created
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunReady(ctx, testName, testRunName);
        }

        // Get all the test run properties for logging
        String jsonTestRun = api.getTestRun(testName, testRunName);

        // Start the test run
        logger.info("Starting test run: " + testRunName + "\n" + jsonTestRun);
        TestRunSchedule testRunSchedule = new TestRunSchedule();
        testRunSchedule.setScheduled(System.currentTimeMillis());
        api.scheduleTestRun(testName, testRunName, testRunSchedule);

        // Call listeners: the test run has started
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunStarted(ctx, testName, testRunName);
        }

        // Wait for the test run to complete
        long timeInit = System.currentTimeMillis();
        long timeLastChange = -1L;
        String jsonLastChange = null;
        String testRunStateStr = api.getTestRunState(testName, testRunName);

        // Keep looking until the test run completes
        while (!TestRunState.COMPLETED.toString().equals(testRunStateStr)) {
            long now = System.currentTimeMillis();

            // Check that we have not exceeded the maximum time
            if (now - timeInit > maxTestTime) {
                throw new RuntimeException("Test run failed to complete in " + (int) maxTestTime / 1000 + "s.");
            }

            testRunStateStr = api.getTestRunState(testName, testRunName);

            if (TestRunState.SCHEDULED.toString().equals(testRunStateStr) && (now - timeInit) > 10000L) {
                throw new RuntimeException("Test run failed to start in 10s.");
            }

            // Check that there are updates to the test run
            String jsonNow = api.getTestRunSummary(testName, testRunName);
            if (jsonLastChange != null && jsonLastChange.equals(jsonNow)) {
                if ((now - timeLastChange) > 60000L) {
                    throw new RuntimeException("Test run has not been updated in the last 60s");
                }
            }
            // Store values for next iteration
            timeLastChange = now;
            jsonLastChange = jsonNow;

            synchronized (testRunStateStr) {
                try {
                    testRunStateStr.wait(1000L);
                } catch (InterruptedException e) {
                }
            }
        }
        // Call listeners: the test run has finished
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunFinished(ctx, testName, testRunName);
        }
    } finally {
        // Close the context
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                logger.error("Failed to shut down application context.", e);
            }
        }
        // Close the local Mongo instance
        if (mongoDBForTestsFactory != null) {
            try {
                mongoDBForTestsFactory.destroy();
            } catch (Exception e) {
                logger.error("Failed to stop in-memory MongoDB instance.", e);
            }
        }
    }
}

From source file:org.alfresco.cacheserver.dao.mongo.MongoDbFactory.java

License:Open Source License

public DB createInstance() throws Exception {
    DB db = null;/*ww w  .  ja va 2s. c o m*/
    //        try
    //        {
    if (enabled) {
        if (mongo != null) {
            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.alfresco.mongo.MongoClientFactory.java

License:Open Source License

/**
 * Create an instance of the factory.  The URI given must not contain a database name or user/password details.
 * This forces the client URI to be an instance that can be shared between instances of this factory.
 * //from w ww  . j  a  v a 2  s. co m
 * @param mongoClientURI            the client URI, which <b>must not</b> reference a database, username or password
 * @param username                  the username to use when connecting (<tt>null</tt> allowed and empty string is ignored)
 * @param password                  the user password for the database (<tt>null</tt> allowed and empty string is ignored)
 * 
 * @throws IllegalArgumentException if the arguments are null when not allowed or contain invalid information
 */
public MongoClientFactory(MongoClientURI mongoClientURI, String username, String password)
        throws UnknownHostException {
    validateMongoClientURI(mongoClientURI);

    if (mongoClientURI.getDatabase() != null) {
        throw new IllegalArgumentException(
                "The provided 'mongoClientURI' instance may not reference a specific database: "
                        + MongoClientFactory.toStringSafe(mongoClientURI));
    } else if (mongoClientURI.getUsername() != null) {
        throw new IllegalArgumentException(
                "The provided 'mongoClientURI' instance may not reference a specific username: "
                        + MongoClientFactory.toStringSafe(mongoClientURI));
    } else if (mongoClientURI.getPassword() != null) {
        throw new IllegalArgumentException(
                "The provided 'mongoClientURI' instance may not reference a specific password: "
                        + MongoClientFactory.toStringSafe(mongoClientURI));
    }

    // Reformat the URI if credentials were supplied
    if (username != null && username.length() > 0) {
        String userPwdCombo = username;
        if (password != null && password.length() > 0) {
            userPwdCombo = username + ":" + password;
        }
        String mongoClientURIstr = mongoClientURI.getURI().replace("mongodb://",
                "mongodb://" + userPwdCombo + "@");
        mongoClientURI = new MongoClientURI(mongoClientURIstr);
    }

    // Construct the client
    mongoClient = new MongoClient(mongoClientURI);

    // Done
    if (logger.isInfoEnabled()) {
        logger.info("New MongoDB client created using URL: " + MongoClientFactory.toStringSafe(mongoClientURI));
    }
}

From source file:org.alfresco.mongo.MongoDBForTestsFactory.java

License:Open Source License

/**
 * Get a Mongo host string e.g. <b>127.0.0.1:51932</b>
 *//*  w  w  w. j  av  a2s . co  m*/
public String getMongoHost() {
    MongoClientURI mongoClientURI = new MongoClientURI(getMongoURIWithoutDB());
    return mongoClientURI.getHosts().get(0);
}

From source file:org.ang.streaming.SpeedStreaming.SpeedStreamingPerrosParques.java

private static void saveToMongo(String jsonData) throws Exception {
    try {// w w  w .j  a  v a2  s .c  o  m
        //toFile("Method: saveToMongo: Trace: " + "** BEGIN EXEC ** ", LOG_PATH);
        //MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://10.1.1.110:27017"));
        MongoClient mongoClient = new MongoClient(new MongoClientURI(MONGODB));
        MongoDatabase db = mongoClient.getDatabase("kml_db");
        //toFile("Method: saveToMongo: Trace: " + "db: " + db.getName(), LOG_PATH);
        //toFile("Method: saveToMongo: Trace: " + "db: " + db.listCollections(), LOG_PATH);
        JSONArray array = JsonDecode(jsonData);
        //toFile("Method: saveToMongo: Trace: " + "JSONArray: " + array.toString(), LOG_PATH);
        //toFile("Method: saveToMongo: Trace: " + "JSONObject: " + array.get(0).toString(), LOG_PATH);
        JSONObject data = (JSONObject) array.get(0);
        //toFile("Method: saveToMongo: Trace: " + "Data: " + data.toJSONString(), LOG_PATH);
        Document key = new Document("id_collar", data.get("id"));
        Document doc = new Document();
        doc.putAll(data);
        doc.append("id_collar", data.get("id")).append("createdAt", System.currentTimeMillis());
        //.append("createdAt", System.currentTimeMillis()).remove("id");
        //toFile("Method: saveToMongo: Trace: " + "key: " + key.toJson(), LOG_PATH);
        //toFile("Method: saveToMongo: Trace: " + "Data Exists: " + db.getCollection("perros_loc").find(key).first(), SpeedStreamingPerrosParques.LOG_PATH);
        if (db.getCollection("perros_loc").find(key).first() == null) {
            db.getCollection("perros_loc").insertOne(doc);
        } else {
            db.getCollection("perros_loc").updateOne(key, new Document("$set", doc));
        }
        //toFile("Method: saveToMongo: Trace: " + "** END EXEC ** ", LOG_PATH);
    } catch (Exception e) {
        toFile("Method: saveToMongo, Exception: " + e.getMessage(), LOG_PATH);
    }
}

From source file:org.apache.drill.exec.store.mongo.config.MongoPersistentStoreProvider.java

License:Apache License

@Override
public void start() throws IOException {
    MongoClientURI clientURI = new MongoClientURI(mongoURL);
    client = new MongoClient(clientURI);
    MongoDatabase db = client.getDatabase(clientURI.getDatabase());
    collection = db.getCollection(clientURI.getCollection()).withWriteConcern(WriteConcern.JOURNALED);
    Bson index = Indexes.ascending(pKey);
    collection.createIndex(index);// w ww .  jav  a  2s.com
}

From source file:org.apache.drill.exec.store.mongo.config.MongoPStoreProvider.java

License:Apache License

@Override
public void start() throws IOException {
    MongoClientURI clientURI = new MongoClientURI(mongoURL);
    client = new MongoClient(clientURI);
    DB db = client.getDB(clientURI.getDatabase());
    collection = db.getCollection(clientURI.getCollection());
    collection.setWriteConcern(WriteConcern.JOURNALED);
    DBObject index = new BasicDBObject(1).append(pKey, Integer.valueOf(1));
    collection.createIndex(index);//from w  ww.j  ava 2 s.c om
}

From source file:org.apache.drill.exec.store.mongo.MongoStoragePlugin.java

License:Apache License

public MongoStoragePlugin(MongoStoragePluginConfig mongoConfig, DrillbitContext context, String name)
        throws IOException, ExecutionSetupException {
    this.context = context;
    this.mongoConfig = mongoConfig;
    this.clientURI = new MongoClientURI(this.mongoConfig.getConnection());
    this.addressClientMap = CacheBuilder.newBuilder().expireAfterAccess(24, TimeUnit.HOURS)
            .removalListener(new AddressCloser()).build();
    this.schemaFactory = new MongoSchemaFactory(this, name);
}

From source file:org.apache.drill.exec.store.mongo.MongoStoragePluginConfig.java

License:Apache License

@JsonCreator
public MongoStoragePluginConfig(@JsonProperty("connection") String connection) {
    this.connection = connection;
    this.clientURI = new MongoClientURI(connection);
}