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, final MongoDriverInformation mongoDriverInformation) 

Source Link

Document

Creates a Mongo described by a URI.

Usage

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 {/*  w  ww.  j ava2  s. c o  m*/
        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 {//  w  w w  . j a  v a2 s .  co  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:DataBaseInteraction.java

public void connectToClient() {
    mongoClient = new MongoClient(getHost(), getPort());
}

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 ww. j ava 2  s .  c o  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.server.BingCacheMongoDB.java

License:Open Source License

public void init() {
    try {//from   ww w.j a v a2  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:actor4j.core.persistence.connectors.MongoDBPersistenceConnector.java

License:Open Source License

@Override
public void open() {
    if (client == null)
        client = new MongoClient(host, port);
}

From source file:analisissentimientos.SentimentAnnotated.java

public static void procesarDatasetAnotado() {
    File archivo = null;//w  ww  .  j a v  a2  s. com
    FileReader fr = null;
    BufferedReader br = null;
    List<Document> jArray = new ArrayList<Document>();
    try {
        archivo = new File(
                "D:\\Deisy universidad\\Big Data\\data\\01_debate08_sentiment_tweets\\debate08_sentiment_tweets_procesar.tsv");
        fr = new FileReader(archivo);
        br = new BufferedReader(fr);

        // Lectura del fichero
        String linea;
        while ((linea = br.readLine()) != null) {
            String[] csvValues = linea.toString().split("\t");

            Document json = new Document();
            json.put("idTweet", csvValues[0]);
            json.put("date", csvValues[1]);
            json.put("content", csvValues[2]);
            json.put("authorName", csvValues[3]);
            json.put("authorNickname", csvValues[4]);

            int j = 1;
            String nameAttribute = "";
            LinkedHashMap<Integer, Integer> ratings = new LinkedHashMap<Integer, Integer>();
            for (int i = 5; i < csvValues.length; i++) {
                nameAttribute = "rating" + j;
                int rating = Integer.parseInt(csvValues[i]);
                ratings.put(rating, ratings.containsKey(rating) ? (ratings.get(rating) + 1) : 1);
                json.put(nameAttribute, csvValues[i]);
                j++;
            }

            int score = 1;
            int maxValueInMap = (Collections.max(ratings.values()));
            for (Map.Entry<Integer, Integer> entry : ratings.entrySet()) {
                if (entry.getValue() == maxValueInMap) {
                    score = entry.getKey();
                    break;
                }
            }

            switch (score) {
            case 1:
                json.put("sentiment_score_annoted", "Negative");
                break;
            case 2:
                json.put("sentiment_score_annoted", "Positive");
                break;
            case 3:
                json.put("sentiment_score_annoted", "Mixed");
                break;
            case 4:
                json.put("sentiment_score_annoted", "Other");
                break;
            }

            //Mongo connection
            jArray.add(json);
        }

        MongoDatabase mongoDB = new MongoClient(DB_SERVER, DB_PORT).getDatabase(DB_NAME);
        MongoCollection mongoCollection = mongoDB.getCollection(COLLECTION_NAME);
        mongoCollection.insertMany(jArray);
        fr.close();
        br.close();
        ///tweet.id   pub.date.GMT   content   author.name   author.nickname   rating.1   rating.2   rating.3   rating.4   rating.5   rating.6   rating.7   rating.8

    } catch (Exception ex) {
        System.out.println("analisissentimientos.SentimentAnnotated.main() Error --->" + ex.toString());
    }
}

From source file:analisissentimientos.SentimentAnnotated.java

public static void consultarDatasetsAnotados() {

    MongoDatabase mongoDB = new MongoClient(DB_SERVER, DB_PORT).getDatabase(DB_NAME);
    MongoCollection mongoCollection = mongoDB.getCollection(COLLECTION_NAME);

    AggregateIterable<Document> result = mongoCollection.aggregate(Arrays.asList(new Document("$group",
            new Document("_id", "$sentiment_score_annoted").append("count", new Document("$sum", 1)))));

    for (Document doc : result) {
        System.out.println(doc);//w w w.  j  ava  2 s. com
    }
}

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  .  j  a va  2 s  .  co  m
    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:anuncius.singleton.MongoHandler.java

public final MongoClient connectToDatabase() {
    if (secureMode) {
        //If MongoDB in secure mode, authentication is required.
        //... missing procedure
        System.out.println("Connecting to Mongo DB instance on " + MONGO_HOST + " at " + MONGO_PORT
                + " using user " + USERNAME);
        MongoCredential credential = MongoCredential.createCredential(USERNAME, database,
                PASSWORD.toCharArray());
        mongo = new MongoClient(new ServerAddress(MONGO_HOST), Arrays.asList(credential));
    } else {//  w w  w  .  j av a  2  s  .co  m
        // Since 2.10.0, uses MongoClient
        System.out.println("Connecting to Mongo DB instance on " + MONGO_HOST + " at " + MONGO_PORT);
        mongo = new MongoClient(MONGO_HOST, MONGO_PORT);
    }
    return mongo;
}