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:com.gs.obevo.mongodb.impl.MongoClientFactory.java

License:Apache License

public MongoClient getMongoClient(String mongoClientURI) {
    return getMongoClient(new MongoClientURI(mongoClientURI));
}

From source file:com.hazelcast.loader.MongoMapStore.java

License:Open Source 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");
    String collectionName = (String) properties.get("mongo.collection");
    this.mongoClient = new MongoClient(new MongoClientURI(mongoUrl));
    this.collection = mongoClient.getDatabase(dbName).getCollection(collectionName);
}

From source file:com.hurence.logisland.service.mongodb.AbstractMongoDBControllerService.java

License:Apache License

protected final void createClient(ControllerServiceInitializationContext context) throws IOException {
    if (mongoClient != null) {
        closeClient();//ww w .  j av a2  s  . c  o  m
    }

    getLogger().info("Creating MongoClient");

    // Set up the client for secure (SSL/TLS communications) if configured to do so
    /*final SSLContextService sslService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    final String rawClientAuth = context.getProperty(CLIENT_AUTH).getValue();*/
    final SSLContext sslContext = null;

    /* if (sslService != null) {
    final SSLContextService.ClientAuth clientAuth;
    if (StringUtils.isBlank(rawClientAuth)) {
        clientAuth = SSLContextService.ClientAuth.REQUIRED;
    } else {
        try {
            clientAuth = SSLContextService.ClientAuth.valueOf(rawClientAuth);
        } catch (final IllegalArgumentException iae) {
            throw new ProviderCreationException(String.format("Unrecognized client auth '%s'. Possible values are [%s]",
                    rawClientAuth, StringUtils.join(SslContextFactory.ClientAuth.values(), ", ")));
        }
    }
    sslContext = sslService.createSSLContext(clientAuth);
     } else {
    sslContext = null;
     }*/

    try {
        if (sslContext == null) {
            mongoClient = new MongoClient(new MongoClientURI(getURI(context)));
        } else {
            mongoClient = new MongoClient(new MongoClientURI(getURI(context), getClientOptions(sslContext)));
        }
    } catch (Exception e) {
        getLogger().error("Failed to schedule {} due to {}", new Object[] { this.getClass().getName(), e }, e);
        throw e;
    }
}

From source file:com.ibm.haac.hx.engine.tool.mongodb.MongoDBAccess.java

License:Open Source License

public MongoDBAccess() throws Exception {

    try {//from   www.j a v a 2s.  c o  m

        if (mongoUri != null && !mongoUri.trim().equals("")) {
            System.out.println("Use mongo connection uri");
            mongoUri = mongoUri.trim();
            // http://stackoverflow.com/questions/15052074/connecting-a-mongodb-created-in-mongolab-through-a-java-application
            MongoClientURI uri = new MongoClientURI(mongoUri);
            this.mongoClient = new MongoClient(uri);
            int index = mongoUri.lastIndexOf("/");
            dbName = mongoUri.substring(index + 1);
        } else {
            System.out.println("Use mongo database connection properties");
            MongoCredential credential = MongoCredential.createMongoCRCredential(userName, dbName,
                    pwd.toCharArray());

            // connect to the server
            this.mongoClient = new MongoClient(new ServerAddress(serverIP, serverPort),
                    Arrays.asList(credential));
        }
        // attach to the database
        this.db = this.mongoClient.getDB(dbName);

        morphia = new Morphia();
        if (morphiaDatastore == null)
            morphiaDatastore = morphia.createDatastore(this.mongoClient, dbName);

        ensureEntities();

        this.mongoConnected = true;

    } catch (MongoException e) {
        throw new Exception("MongoDB exception: " + e.getMessage());
    } catch (UnknownHostException e) {
        throw new Exception("MongoDB UnknownHostException exception: " + e.getMessage());
    }
}

From source file:com.imos.sample.SampleMongoDB.java

public static void main(String[] args) {
    MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
    MongoClient mongoClient = new MongoClient(connectionString);
    MongoDatabase database = mongoClient.getDatabase("sampledb");
    MongoCollection<Document> collection = database.getCollection("sampleLog");
    System.out.println(collection.count());
    MongoCursor<Document> cursor = collection.find().iterator();
    ObjectMapper mapper = new ObjectMapper();
    try {// ww  w  . j  a  va 2 s .c om
        while (cursor.hasNext()) {
            try {
                System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cursor.next()));
            } catch (JsonProcessingException ex) {
                Logger.getLogger(SampleMongoDB.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } finally {
        cursor.close();
    }
}

From source file:com.inflight.rest.AddFlightService.java

@SuppressWarnings("resource")
@POST//from  w  w  w .ja  v a 2 s  .  com
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_JSON)
public String signup(@FormParam("username") String username, @FormParam("confirmCode") String confirmCode,
        @FormParam("fromLocation") String fromLocation, @FormParam("toLocation") String toLocation)
        throws Exception {

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);
    String result = "";

    MongoDatabase database = mongoClient.getDatabase("inflight");
    MongoCollection<Document> collection = database.getCollection("location");

    Document doc = collection.find(or(eq("confirmCode", confirmCode), eq("toLocation", toLocation))).first();
    if (doc == null) {
        Document newDoc = new Document("username", username).append("confirmCode", confirmCode)
                .append("fromLocation", fromLocation).append("toLocation", toLocation);

        collection.insertOne(newDoc);
        result = "{\"success\": true}";
        return result;
    } else {
        result = "{\"success\": false, \"message\": \"Booking Reference or To Location already exists\"}";
        return result;
    }
}

From source file:com.inflight.rest.LoginService.java

@SuppressWarnings("resource")
@POST/* w w w. j a va2s  .c  om*/
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_JSON)
public String login(@FormParam("username") String username, @FormParam("password") String password)
        throws Exception {

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);
    String result = "";

    MongoDatabase database = mongoClient.getDatabase("inflight");
    MongoCollection<Document> collection = database.getCollection("users");

    Document doc = collection.find(eq("username", username)).first();

    if (doc != null) {
        String actualPass = doc.get("password").toString();
        if (Password.check(password, actualPass)) {
            result = "{\"success\": true}";
            return result;
        } else {
            result = "{\"success\": false, \"message\": \"Invalid Password\"}";
            return result;
        }
    } else {
        result = "{\"success\": false, \"message\": \"Invalid Username\"}";
        return result;
    }

}

From source file:com.inflight.rest.SignUpService.java

@SuppressWarnings("resource")
@POST/* w  w  w . j  a v  a 2  s  .  c  om*/
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_JSON)
public String signup(@FormParam("username") String username, @FormParam("password") String password,
        @FormParam("email") String email) throws Exception {

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);
    String result = "";

    MongoDatabase database = mongoClient.getDatabase("inflight");
    MongoCollection<Document> collection = database.getCollection("users");

    Document doc = collection.find(or(eq("username", username), eq("email", email))).first();
    if (doc == null) {
        Document newDoc = new Document("username", username)
                .append("password", Password.getSaltedHash(password)).append("email", email);

        collection.insertOne(newDoc);
        result = "{\"success\": true}";
        return result;
    } else {
        result = "{\"success\": false, \"message\": \"Username or Email already exists\"}";
        return result;
    }

}

From source file:com.inflight.rest.ViewPlaces.java

@SuppressWarnings("resource")
@GET/*from  w  w w .  j  av a  2  s  .  c om*/
@Path("/all")
@Produces(MediaType.APPLICATION_JSON)
public String getLocations() {

    JSONArray jsonArr = new JSONArray();

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);

    MongoDatabase database = mongoClient.getDatabase("inflight");

    MongoCollection<Document> collection = database.getCollection("location");

    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            jsonArr.put(cursor.next());

        }
    } finally {
        cursor.close();
    }

    return jsonArr.toString();
}

From source file:com.jaeksoft.searchlib.crawler.cache.MongoDbCrawlCache.java

License:Open Source License

@Override
public void init(String configString) throws IOException {
    rwl.w.lock();//from   ww  w .  j a v a  2 s.  c  om
    try {
        closeNoLock();
        final MongoClientURI connectionString = new MongoClientURI(configString);
        mongoClient = new MongoClient(connectionString);
        final MongoDatabase database = mongoClient.getDatabase(
                connectionString.getDatabase() == null ? DEFAULT_DATABASE : connectionString.getDatabase());
        metaCollection = database.getCollection(META_COLLECTION);
        metaCollection.createIndex(Document.parse("{\"uri\":1}"));
        indexedCollection = database.getCollection(INDEXED_COLLECTION);
        indexedCollection.createIndex(Document.parse("{\"uri\":1}"));
        contentGrid = GridFSBuckets.create(database);
    } finally {
        rwl.w.unlock();
    }
}