Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient(final MongoClientURI uri) 

Source Link

Document

Creates a Mongo described by a URI.

Usage

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 {//from  w  w  w  .  j  a  v  a  2 s  . co  m
        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//ww  w .j  a v a2s.c  o  m
@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/*from   ww  w.j ava 2 s . c o m*/
@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//from  ww w .  jav a  2 s  .c o  m
@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  .ja  va2  s . c o m*/
@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  w w  w.  j a  v a 2  s .com*/
    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();
    }
}

From source file:com.jive.myco.seyren.mongo.MongoStore.java

License:Apache License

@Inject
public MongoStore(SeyrenConfig seyrenConfig) {
    try {//from   ww w.  j a  v  a 2  s  . com
        String uri = seyrenConfig.getMongoUrl();
        MongoClientURI mongoClientUri = new MongoClientURI(uri);
        MongoClient mongoClient = new MongoClient(mongoClientUri);
        DB mongo = mongoClient.getDB(mongoClientUri.getDatabase());
        mongo.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        this.mongo = mongo;
        bootstrapMongo();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.joowon.returnA.classifier.db.MongoDbManager.java

License:Open Source License

private MongoDbManager(String host) {
    // Morphia setup
    final Morphia morphia = new Morphia();
    morphia.mapPackage("com.joowon.returnA.classifier.db.dto");
    datastore = morphia.createDatastore(new MongoClient(host), DB_ReturnA);

    //     datastore.ensureIndexes();
}

From source file:com.khubla.cbean.mongokv.MongoPoolableObjectFactoryImpl.java

License:Open Source License

@Override
public MongoClient makeObject() throws Exception {
    return new MongoClient(hostname);
}

From source file:com.korpacz.testproject.HelloWorldMongoDBSparkFreemarkerStyle.java

public static void main(String... args) throws UnknownHostException {
    //ssssss// w w w  .  j  a  va  2 s . c  o  m

    final Configuration config = new Configuration();
    config.setClassForTemplateLoading(HelloWorldSparkFreemarkerStyle.class, "/");

    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));
    DB database = client.getDB("test");
    final DBCollection collection = database.getCollection("names");

    Spark.get("/", new Route() {

        @Override
        public Object handle(Request rqst, Response rspns) throws Exception {

            Template helloTemplete = config.getTemplate("hello.ftl");
            StringWriter writter = new StringWriter();

            DBObject object = collection.findOne();

            helloTemplete.process(object, writter);

            System.out.println(writter);

            return writter;
        }
    });

}