Example usage for com.mongodb MongoClient getDB

List of usage examples for com.mongodb MongoClient getDB

Introduction

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

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:Entry_OR_Exit.java

private void Exit_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Exit_buttonActionPerformed
    // TODO add your handling code here:

    try {//from   www.  java  2s . c om
        MongoClient mc = new MongoClient("localhost", 27017);
        DB db = mc.getDB("parking_system");
        DBCollection collection = db.getCollection("vehicle_count");

        if (radio_vehicle_check == -99)
            JOptionPane.showMessageDialog(null, "Please Chhose Vehicle Type");
        else {
            if (radio_vehicle_check == 2) {
                int count_bike;
                BasicDBObject query = new BasicDBObject();
                BasicDBObject field = new BasicDBObject();
                field.put("wheeler_2", 1);
                DBCursor cursor = collection.find(query, field);

                BasicDBObject obj = (BasicDBObject) cursor.next();
                count_bike = obj.getInt("wheeler_2");
                System.out.println(count_bike);

                if (count_bike == 0) {
                    JOptionPane.showMessageDialog(null, "No 2 Wheelers in the Parking!");
                } else {
                    setVisible(false);
                    new Vehicle_exit(radio_vehicle_check).setVisible(true);
                }
            }

            else if (radio_vehicle_check == 4) {
                int count_car;

                BasicDBObject query = new BasicDBObject();
                BasicDBObject field = new BasicDBObject();
                field.put("wheeler_4", 1);
                DBCursor cursor = collection.find(query, field);

                BasicDBObject obj = (BasicDBObject) cursor.next();
                count_car = obj.getInt("wheeler_4");
                System.out.println(count_car);

                if (count_car == 0) {
                    JOptionPane.showMessageDialog(null, "No 4 Wheelers in the Parking!");
                } else {
                    setVisible(false);
                    new Vehicle_exit(radio_vehicle_check).setVisible(true);
                }
            } else {
                int count_other;

                BasicDBObject query = new BasicDBObject();
                BasicDBObject field = new BasicDBObject();
                field.put("other", 1);
                DBCursor cursor = collection.find(query, field);

                BasicDBObject obj = (BasicDBObject) cursor.next();
                count_other = obj.getInt("other");
                System.out.println(count_other);

                if (count_other == 0) {
                    JOptionPane.showMessageDialog(null, "No Others in the Parking!");
                } else {
                    setVisible(false);
                    new Vehicle_exit(radio_vehicle_check).setVisible(true);
                }
            }
        }
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:login_page.java

private void LoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginActionPerformed
    // TODO add your handling code here:
    try {//from w w w  .j  a v a  2 s. com
        int check = 0;
        userid = UserID.getText();
        password = Password.getText();
        submit = Login.getActionCommand();

        if (radio_check == -99)
            JOptionPane.showMessageDialog(null, "Please Chhose Admin/Employee");
        else {
            if (radio_check == 0) {
                if ((userid.equals("admin")) && (password.equals("password123"))) {
                    System.out.println("Done");

                    //TO connect theses two pages..
                    setVisible(false);
                    new Admin_rights().setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, "Invalid Admin Login");
                }
            } else {
                MongoClient mc = new MongoClient("localhost", 27017);
                DB db = mc.getDB("parking_system");
                DBCollection collection = db.getCollection("employee_info");
                /*ISERT DOCUMENT 
                BasicDBObject doc = new BasicDBObject("userid",userid).append("password",password);
                collection.insert(doc);
                */
                DBCursor cursor = collection.find();
                DBObject obj;

                String temp_user, temp_pass;

                while (cursor.hasNext()) {
                    obj = (DBObject) cursor.next();

                    temp_user = obj.get("_id").toString();
                    temp_pass = obj.get("password").toString();

                    if ((userid.equals(temp_user)) && (password.equals(temp_pass))) {
                        System.out.println("Done");

                        //TO connect theses two pages..
                        setVisible(false);
                        /*new Vehicle_type_check().setVisible(true);*/
                        new Entry_OR_Exit().setVisible(true);
                        check = 1;
                        break;
                    }
                }
                if (check != 1) {
                    JOptionPane.showMessageDialog(null, "Authentication Failed!\nInvalid Login");
                }
            }
        }
    } catch (Exception e) {

    }
}

From source file:admin_Add_newEmp.java

private void Add_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Add_buttonActionPerformed
    // TODO add your handling code here:

    try {//  ww w.j  av  a 2 s  .  c  o m

        MongoClient mc = new MongoClient("localhost", 27017);
        DB db = mc.getDB("parking_system");
        DBCollection collection = db.getCollection("employee_info");

        name = name_field.getText();
        lname = lname_field.getText();
        mobno = mobno_field.getText().toCharArray();

        //userid = userid_field.getText();
        //password = password_field.getText();
        //mobno = Integer.parseInt(mobno_field.getText());
        //mobno = mobno_field.getText();
        String mobnoStr = new String(mobno);

        BasicDBObject doc = new BasicDBObject("_id", userid).append("name", name).append("lname", lname)
                .append("password", password).append("mobileno", mobnoStr);

        collection.insert(doc);

        JOptionPane.showMessageDialog(null, "Added!");

        setVisible(false);
        new Admin_rights().setVisible(true);

    } catch (Exception e) {

    }
}

From source file:ChangeUserRole.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Access-Control-Allow-Origin", "*");
    try {//from w  w w. j  a v  a2  s  .  co  m
        out = response.getWriter();
        String id = request.getParameter("id");
        status = request.getParameter("type");
        System.out.println("id received : " + id);
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        // Now connect to your databases
        DB db = mongoClient.getDB("XHiring");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("users");
        System.out.println("Collection users selected successfully");
        //read example
        try {
            BasicDBObject query = new BasicDBObject("_id", new ObjectId(id));
            BasicDBObject update;
            if (status != null && status.equalsIgnoreCase(" ")) {
                update = new BasicDBObject("isAdmin", "true");
            } else {
                update = new BasicDBObject("isAdmin", "false");
            }
            coll.update(query, update);
            success = new JSONObject();
            success.put("message", "document updated");
            out.println(success);
        } catch (NullPointerException ex) {
            error = new JSONObject();
            error.put("message", "No result found");
            out.println(error);
        }
        System.out.println("Document updated successfully");
    } catch (Exception e) {
        exception = new JSONObject();
        try {
            exception.put("message", "exception");
            out.println(exception);
        } catch (JSONException ex) {
            Logger.getLogger(ChangeUserRole.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:act.installer.reachablesexplorer.FreemarkerRenderer.java

License:Open Source License

private void init(String dbHost, Integer dbPort, String dbName, String dnaCollection, String pathwayCollection)
        throws IOException {
    cfg = new Configuration(Configuration.VERSION_2_3_23);

    cfg.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(),
            "/act/installer/reachablesexplorer/templates");
    cfg.setDefaultEncoding("UTF-8");

    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(true);/*from  www.j ava 2s .c  om*/

    reachableTemplate = cfg.getTemplate(reachableTemplateName);
    pathwayTemplate = cfg.getTemplate(pathwayTemplateName);

    // TODO: move this elsewhere.
    MongoClient client = new MongoClient(new ServerAddress(dbHost, dbPort));
    DB db = client.getDB(dbName);

    dnaDesignCollection = JacksonDBCollection.wrap(db.getCollection(dnaCollection), DNADesign.class,
            String.class);
    Cascade.setCollectionName(pathwayCollection);
}

From source file:act.installer.reachablesexplorer.Loader.java

License:Open Source License

/**
 * Constructor for Loader. Instantiates connexions to Mongo databases
 * and Virtuoso triple store (Pubchem synonyms only)
 * @param host The host for the target Reachables MongoDB
 * @param port The port for the target Reachables MongoDB
 * @param targetDB The database for the target Reachables MongoDB
 * @param targetCollection The collection for the target Reachables MongoDB
 * @param targetSequenceCollection The collection for the target SequenceData MongoDB
 * @param renderingCache A directory where rendered images should live
 *//* ww w . ja  v  a2  s  . com*/
public Loader(String host, Integer port, String sourceDB, String targetDB, String targetCollection,
        String targetSequenceCollection, String renderingCache) {
    // when the caller does not intend to touch the sourceDB, it can pass null as a param and we
    // won't setup a "source" connection. Creating a connection with "dummy" params leads mongod
    // to create (!) those dummy collections, mucking up our database with empty dbs/collections
    if (sourceDB != null) {
        sourceDBconn = new MongoDB(host, port, sourceDB);
        wordCloudGenerator = new WordCloudGenerator(host, port, sourceDB, renderingCache);
    }
    pubchemSynonymsDriver = new PubchemMeshSynonyms();
    moleculeRenderer = new MoleculeRenderer(new File(renderingCache));

    MongoClient mongoClient;
    try {
        mongoClient = new MongoClient(new ServerAddress(host, port));
    } catch (UnknownHostException e) {
        LOGGER.error(
                "Connection to MongoClient failed. Please double check the target database's host and port.");
        throw new RuntimeException(e);
    }
    DB reachables = mongoClient.getDB(targetDB);

    // TODO: this unsafe initialization does not belong in the constructor.
    try {
        calculator = new PhysiochemicalPropertiesCalculator.Factory().build();
    } catch (PluginException e) {
        LOGGER.error("Unable to initialize physiochemical calculator: %s", e.getMessage());
        throw new RuntimeException(e);
    }

    if (targetCollection != null) {
        jacksonReachablesCollection = JacksonDBCollection.wrap(reachables.getCollection(targetCollection),
                Reachable.class, String.class);
        jacksonReachablesCollection.ensureIndex(new BasicDBObject(Reachable.INCHI_FIELD_NAME, "hashed"));
    }

    if (targetSequenceCollection != null) {
        jacksonSequenceCollection = JacksonDBCollection.wrap(reachables.getCollection(targetSequenceCollection),
                SequenceData.class, String.class);
        jacksonSequenceCollection.createIndex(new BasicDBObject(SequenceData.SEQUENCE_FIELD_NAME, "hashed"));
        jacksonSequenceCollection.createIndex(new BasicDBObject(SequenceData.ORGANISM_FIELD_NAME, 1));
    }
}

From source file:act.server.BingCacheMongoDB.java

License:Open Source License

public void init() {
    try {//  w  ww  . j  a v a  2  s  .c  o  m
        MongoClient mongo = new MongoClient(hostname, port);
        mongoDB = mongo.getDB(database);

    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("Invalid host for Mongo Bing Cache server.");
    } catch (MongoException e) {
        throw new IllegalArgumentException("Could not initialize Mongo driver.");
    }
    if (!mongoDB.getCollectionNames().contains(BING_CACHE_COLLECTION_NAME)
            || mongoDB.getCollection(BING_CACHE_COLLECTION_NAME).count() == 0) {
        System.out.println(WARNING_MESSAGE);
        if (!askConfirmationWhenCacheEmpty()) {
            System.out.println("Aborting the run.");
            System.exit(1);
        }
    }
    this.dbBingCache = mongoDB.getCollection(BING_CACHE_COLLECTION_NAME);
}

From source file:amazonwebcrawler.Mongo.java

private DBCollection queryDb(String[] args) {
    try {//  ww w .  j  ava  2s  .  com

        /**** Connect to MongoDB ****/
        // Since 2.10.0, uses MongoClient
        MongoClientURI uri = new MongoClientURI(
                "mongodb://heroku_73s67dx7:2d6hshk9a78f2dlfkachg486t7@ds011399.mlab.com:11399/heroku_73s67dx7");
        MongoClient mongo = new MongoClient(uri);

        /**** Get database ****/
        // if database doesn't exists, MongoDB will create it for you
        DB db = mongo.getDB("heroku_73s67dx7");

        /**** Get collection / table from 'testdb' ****/
        // if collection doesn't exists, MongoDB will create it for you
        DBCollection table = db.getCollection("products");
        return table;
    } catch (MongoException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Analytical.Parser.java

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

    //Init connect mongodb
    MongoClient mongoClient = new MongoClient(MongoDb.Config.HOST, MongoDb.Config.defaultPort);
    DB db = mongoClient.getDB(MongoDb.Config.Schema);

    //Insert category and subCategory
    Main.insertCategoryAndSubCategory();
    //Connect// w w w  .  jav  a 2s  .  com
    MongoDBController demo = new MongoDBController(mongoClient, db);
    DBCollection category = db.getCollection("Category");
    DBCollection subCategoryCol = db.getCollection("subCategory");
    DBCollection product = db.getCollection("Production");
    DBCollection featureImageCol = db.getCollection("featureImage");
    DBCollection productInforCol = db.getCollection("ProductDetailInformation");
    DBCollection compareProductCol = db.getCollection("compareProduction");

    List CategoriesList = Parser.getJSONCategory();
    CategoriesList.forEach(new Consumer() {
        @Override
        public void accept(Object CategoriesList1) {
            JSONObject category = (JSONObject) CategoriesList1;
            try {
                JSONArray subCategoryList = (JSONArray) category.get("subList");
                String categoryName = category.get("categoryName").toString();//==================//

                for (int i = 0; i < subCategoryList.length(); i++) {

                    JSONObject subCategory = subCategoryList.getJSONObject(i);

                    String subCategoryName = subCategory.get("subname").toString();//==================//
                    String suburl = subCategory.get("suburl").toString();

                    ////Su li tiep vao day nhe
                    List bigList = Parser.getAllDetailUrlProductOfSubCotegory(suburl);
                    for (int j = 0; j < bigList.size(); j++) {
                        List smallList = (List) bigList.get(j);
                        for (int k = 0; k < smallList.size(); k++) {
                            if (!smallList.get(k).toString().contains("direct.htm")) {
                                try {
                                    JSONObject json = Parser.getDetailProduct(categoryName, subCategoryName,
                                            smallList.get(k).toString());
                                    if (json != null) {
                                        System.out.println(json);
                                        MongoDBController.addAProduct(json, mongoClient, db, demo, product,
                                                subCategoryCol, featureImageCol, productInforCol,
                                                compareProductCol);

                                    }
                                } catch (Exception e) {

                                }
                            }
                        }
                    }

                }

            } catch (JSONException ex) {
                Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });//      System.out.println(Parser.getAllDetailUrlProductOfSubCotegory("https://websosanh.vn/dien-thoai-smartphone/cat-82.htm"));
    //     
}

From source file:at.ac.tuwien.dsg.smartcom.manager.messaging.logging.dao.MongoDBLoggingDAO.java

License:Apache License

public MongoDBLoggingDAO(MongoClient client, String database, String collection) {
    coll = client.getDB(database).getCollection(collection);
}