Example usage for com.mongodb MongoClientURI getDatabase

List of usage examples for com.mongodb MongoClientURI getDatabase

Introduction

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

Prototype

@Nullable
public String getDatabase() 

Source Link

Document

Gets the database name

Usage

From source file:SparkToMongo.java

License:Apache License

private static void dropDatabase(final String connectionString) {
    MongoClientURI uri = new MongoClientURI(connectionString);
    new MongoClient(uri).dropDatabase(uri.getDatabase());
}

From source file:JavaSimpleExample.java

License:MIT License

public static void main(String[] args) throws UnknownHostException {

    // Create seed data

    final BasicDBObject[] seedData = createSeedData();

    // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname

    MongoClientURI uri = new MongoClientURI("mongodb://user:pass@host:port/db");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());

    /*/*from  w  ww.  j  a v  a 2  s .  com*/
     * First we'll add a few songs. Nothing is required to create the
     * songs collection; it is created automatically when we insert.
     */

    DBCollection songs = db.getCollection("songs");

    // Note that the insert method can take either an array or a document.

    songs.insert(seedData);

    /*
     * Then we need to give Boyz II Men credit for their contribution to
     * the hit "One Sweet Day".
     */

    BasicDBObject updateQuery = new BasicDBObject("song", "One Sweet Day");
    songs.update(updateQuery,
            new BasicDBObject("$set", new BasicDBObject("artist", "Mariah Carey ft. Boyz II Men")));

    /*
     * Finally we run a query which returns all the hits that spent 10 
     * or more weeks at number 1.
     */

    BasicDBObject findQuery = new BasicDBObject("weeksAtOne", new BasicDBObject("$gte", 10));
    BasicDBObject orderBy = new BasicDBObject("decade", 1);

    DBCursor docs = songs.find(findQuery).sort(orderBy);

    while (docs.hasNext()) {
        DBObject doc = docs.next();
        System.out.println("In the " + doc.get("decade") + ", " + doc.get("song") + " by " + doc.get("artist")
                + " topped the charts for " + doc.get("weeksAtOne") + " straight weeks.");
    }

    // Since this is an example, we'll clean up after ourselves.

    songs.drop();

    // Only close the connection when your app is terminating

    client.close();
}

From source file:ch.qos.logback.contrib.mongodb.MongoDBAppenderBase.java

License:Open Source License

/**
 * If appender starts, create a new MongoDB connection and authenticate
 * user. A MongoDB database and collection in {@link #setUri(String)} is
 * mandatory, username and password are optional.
 *///from   w ww. j  a  v  a  2 s  .c o m
@Override
public void start() {
    try {
        if (uri == null) {
            addError("Please set a non-null MongoDB URI.");
            return;
        }
        MongoClientURI mongoURI = new MongoClientURI(uri);
        String database = mongoURI.getDatabase();
        String collection = mongoURI.getCollection();
        if (database == null || collection == null) {
            addError("Error connecting to MongoDB URI: " + uri + " must contain a database and a collection."
                    + " E.g. mongodb://localhost/database.collection");
            return;
        }
        mongoClient = mongoClientFactory.createMongoClient(mongoURI);

        DB db = this.mongoClient.getDB(database);
        eventsCollection = db.getCollection(collection);
        super.start();
    } catch (Exception exception) {
        addError("Error connecting to MongoDB URI: " + uri, exception);
    }
}

From source file:com.aankam.servlet.MongoCrudServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w w w .ja v a 2  s .  c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    MongoClientURI uri = new MongoClientURI("mongodb://Username:Pasword@ds061721.mongolab.com:61721/cs612");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());

    response.setContentType("text/html;charset=UTF-8");

    String serialNo = request.getParameter("serialNo");
    String name = request.getParameter("name");
    String emailId = request.getParameter("emailId");
    String operation = request.getParameter("operation");

    BasicDBObject customer;
    BasicDBObject updateQuery;
    BasicDBObject deleteQuery;
    BasicDBObject searchQuery;
    DBCollection customersCollection;
    customersCollection = db.getCollection("Customers");
    DBObject searchResult = null;
    boolean flag = false;
    DBCursor cursor;
    switch (operation) {
    case "create":
        customer = new BasicDBObject();
        customer.put("serialNo", serialNo);
        customer.put("name", name);
        customer.put("emailId", emailId);
        customersCollection.insert(customer);
        break;
    case "update":
        updateQuery = new BasicDBObject();
        updateQuery.append("serialNo", serialNo);
        cursor = customersCollection.find(updateQuery);
        customer = new BasicDBObject();
        customer.put("serialNo", serialNo);
        customer.put("name", name);
        customer.put("emailId", emailId);
        if (cursor.hasNext()) {
            customersCollection.update(updateQuery, customer);
            flag = true;
        }

        break;
    case "delete":
        deleteQuery = new BasicDBObject();
        deleteQuery.append("serialNo", serialNo);
        customersCollection.remove(deleteQuery);
        break;
    case "search":
        searchQuery = new BasicDBObject();
        searchQuery.append("serialNo", serialNo);
        cursor = customersCollection.find(searchQuery);
        while (cursor.hasNext()) {
            searchResult = cursor.next();
        }
        break;
    default:
        break;

    }
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet MongoCrudServlet</title>");
        out.println("</head>");
        out.println("<body>");

        switch (operation) {
        case "create":
            out.println("<h3>Customer was successfully created.</h3>");
            break;
        case "update":
            if (flag == true) {
                out.println("<h3>Customer was successfully updated.</h3>");
            } else {
                out.println("<h3>Customer was not found to update.</h3>");
            }

            break;
        case "delete":
            out.println("<h3>Customer was successfully deleted.</h3>");
            break;
        case "search":
            if (searchResult != null) {
                out.println("<h3>The following customer was found:</h3>");
                out.println("<h4>Serial No :" + searchResult.get("serialNo") + "</h4>");
                out.println("<h4>Name :" + searchResult.get("name") + "</h4>");
                out.println("<h4>Email Id :" + searchResult.get("emailId") + "</h4>");
            } else {
                out.println("<h3>Customer not found.</h3>");
            }
            break;
        default:
            break;
        }
        out.println("<a href=\"index.html\">Back to Main Form</a>");
        out.println("</body>");
        out.println("</html>");
    }
}

From source file:com.apifest.oauth20.MongoUtil.java

License:Apache License

public static MongoClient getMongoClient() {
    if (mongoClient == null) {
        try {//from  w  ww.  j a v a  2  s. c  o  m
            MongoClientOptions.Builder options = new MongoClientOptions.Builder().connectionsPerHost(100)
                    .connectTimeout(2).threadsAllowedToBlockForConnectionMultiplier(1);
            final MongoClientURI mongoClientURI = new MongoClientURI(OAuthServer.getDbURI(), options);
            mongoClient = new MongoClient(mongoClientURI);

            if (mongoClientURI.getDatabase() != null) {
                database = mongoClientURI.getDatabase();
            }
        } catch (UnknownHostException e) {
            log.error("Cannot connect to DB", e);
        }
    }
    return mongoClient;
}

From source file:com.apifest.oauth20.persistence.mongodb.MongoUtil.java

License:Apache License

public static MongoClient getMongoClient(String uri) {
    if (mongoClient == null) {
        try {/*w w  w  . ja v  a2  s. c o  m*/
            MongoClientOptions.Builder options = new MongoClientOptions.Builder().connectionsPerHost(100)
                    .connectTimeout(2000).threadsAllowedToBlockForConnectionMultiplier(1);
            final MongoClientURI mongoClientURI = new MongoClientURI(uri, options);
            mongoClient = new MongoClient(mongoClientURI);

            if (mongoClientURI.getDatabase() != null) {
                database = mongoClientURI.getDatabase();
            }
        } catch (UnknownHostException e) {
            log.error("Cannot connect to DB", e);
        }
    }
    return mongoClient;
}

From source file:com.bluedragon.mongo.MongoDSN.java

License:Open Source License

public synchronized void open() throws Exception {

    if (mongouri == null) {

        if (clientMongoMap.containsKey(ip + port)) {
            mdb = clientMongoMap.get(ip + port).open().getDatabase(db);
        } else {/*from  ww w . ja  va  2  s .  c  o m*/
            mongoclient = newClient(server + ":" + port, user, pass, db);
            MongoClientWrapper mcw = new MongoClientWrapper(mongoclient);
            clientMongoMap.put(ip + port, mcw);
            mdb = mcw.open().getDatabase(db);
        }

    } else {
        MongoClientURI clientURI = new MongoClientURI(mongouri);
        mongoclient = new MongoClient(clientURI);
        mdb = mongoclient.getDatabase(clientURI.getDatabase());
    }

    lastUsed = System.currentTimeMillis();
}

From source file:com.cloudbees.demo.beesshop.util.MongodbDBFactoryBean.java

License:Apache License

@Override
public void afterPropertiesSet() throws Exception {
    MongoClientURI mongoDbUri = new MongoClientURI(uri);
    logger.info("host=" + mongoDbUri.getHosts() + ",username=" + mongoDbUri.getUsername() + ",database="
            + mongoDbUri.getDatabase() + ",collection=" + mongoDbUri.getCollection());

    mongoClient = new MongoClient(mongoDbUri);
    db = mongoClient.getDB(mongoDbUri.getDatabase());
}

From source file:com.connection.Connection.java

private void establishConnection() {
    if (mongoClient == null) {
        MongoClientURI uri = new MongoClientURI("mongodb://352634:cs-120@ds023418.mlab.com:23418/example");
        try {/*from  www .j  ava 2s  . c o m*/
            mongoClient = new MongoClient(uri);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        dbname = uri.getDatabase();
        //  mongoClient = new MongoClient("localhost", 27017);
        mongoDB = mongoClient.getDB(dbname);

    }
}

From source file:com.dianping.swallow.web.dao.SimMongoDbFactory.java

License:Apache License

/**
 * Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClientURI}.
 * //w w w  . jav a  2s .c om
 * @param uri must not be {@literal null}.
 * @throws UnknownHostException
 * @since 1.7
 */
public SimMongoDbFactory(MongoClientURI uri) throws UnknownHostException {
    this(new MongoClient(uri), uri.getDatabase(), true);
}