Example usage for com.mongodb MongoClient getDatabase

List of usage examples for com.mongodb MongoClient getDatabase

Introduction

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

Prototype

public MongoDatabase getDatabase(final String databaseName) 

Source Link

Usage

From source file:Dbconnection.java

public Connection getconnection() {

    Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
    mongoLogger.setLevel(Level.SEVERE);
    // To connect to mongodb server
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Now connect to your databases
    MongoDatabase db = mongoClient.getDatabase("mydb");
    System.out.println("Connect to database successfully");
    //boolean auth = db.authenticate("","");
    //System.out.println("Authentication: "+auth);
    // MongoCollection<Document> coll = db.getCollection("yelp");

    System.out.println("Collection yelp selected successfully");

    /*FindIterable<Document> cursor = coll.find();
                 /*from www.  j  av a  2  s  . c o m*/
         cursor.forEach(new Block<Document>() {
         @Override
         public void apply(final Document document) {
             System.out.println(document);
         }
     });*/
    //            BasicDBObject clause1 = new BasicDBObject("yelping_since", "2012-02");
    //            //clause1.put("yelping_since", "2012-02");
    //            
    //            BasicDBObject clause2 = new BasicDBObject("review_count",new BasicDBObject("$gt",500));
    //            BasicDBObject clause3 = new BasicDBObject("fans",new BasicDBObject("$gt",15)); 
    //            BasicDBObject clause4 = new BasicDBObject("average_stars",new BasicDBObject("$gt",3)); 
    //            //BasicDBObject cl5 = new BasicDBObject("$exist",true);
    //            //BasicDBObject cl6 = new BasicDBObject("$where","this.friends.length>49");
    //            //String cl = cl5.toString();
    //            //BasicDBObject c = new BasicDBObject(cl,cl6);
    //            //BasicDBObject f = new BasicDBObject("friends",new BasicDBObject("$exist",true));
    //            BasicDBObject clause5 = new BasicDBObject("friends.50",new BasicDBObject("$exists",true));
    //            //BasicDBObject cl5 = new BasicDBObject("$where","this.friends.length>3");
    //            
    //            /*BasicDBList fl = new BasicDBList();
    //            fl.add(f);
    //            fl.add(cl6);*/
    //            
    //            //clause2.put("review_count",gtquery);
    //            BasicDBList or = new BasicDBList();
    //            
    //            or.add(clause1);
    //            or.add(clause2);
    //            or.add(clause3);
    //            or.add(clause4);
    //            or.add(clause5);
    //            //or.add(fl);
    //            
    //            //fields.put("name",1);
    //            //fields.put("average_stars",1);
    //            //fields.put("fans",1);
    //            BasicDBObject query = new BasicDBObject("$and", or);
    //            
    //            
    //            FindIterable<Document> cursor = coll.find(query);
    //            System.out.println(query);
    //            cursor.forEach(new Block<Document>() {
    //                @Override
    //                public void apply(final Document document) {
    //                                System.out.println(document.get("user_id"));
    //                                System.out.println(document.get("name"));
    //                                System.out.println(document.get("fans"));
    //                                System.out.println(document.get("average_stars"));
    //                                System.out.println(document.get("friends"));
    //                                
    //                }
    //            });
    //
    //        

    mongoClient.close();
    System.out.println("Connection successfully closed");

    return null;

}

From source file:MenuDefCats.java

public static void getCats() {

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("database");
    MongoCollection<Document> elexirCollection = db.getCollection("test");

    FindIterable<Document> results = elexirCollection
            .find(new BasicDBObject("Types", new BasicDBObject("$gt", "0")));
    //FindIterable<Document> iter = elexirCollection.find(new BasicDBObject("derivProb", 2));

    for (Document doc : results) {
        List<String> conv = (List<String>) doc.get("Cats");

        String[] convArr = new String[conv.size()];
        convArr = conv.toArray(convArr);

        for (String s : convArr)
            CatsTextArea.append(s + "\n");

    }/*from   w  w w.j a v a  2 s .  c  om*/
}

From source file:MenuDefObj.java

public static void getObjects() {

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("database");
    MongoCollection<Document> elexirCollection = db.getCollection("test");

    FindIterable<Document> results = elexirCollection
            .find(new BasicDBObject("Types", new BasicDBObject("$gt", "0")));
    //FindIterable<Document> iter = elexirCollection.find(new BasicDBObject("derivProb", 2));

    for (Document doc : results) {
        List<String> conv = (List<String>) doc.get("Objects");

        String[] convArr = new String[conv.size()];
        convArr = conv.toArray(convArr);

        for (String s : convArr)
            ObjTextArea.append(s + "\n");

    }//  w w  w. j  a v  a 2 s. co  m
}

From source file:StartScreen.java

private void insertMongo() throws Exception {
    // *****This is to connect to database**//

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("database");

    MongoCollection<Document> elexirCollection = db.getCollection("test");

    // *********This is to connect to the database***********//

    //To clear out existing files from mongo
    db.getCollection("test").deleteMany(new Document());

    // *******This is to read the file into program*********//
    //String fileDirectory = chooser.getCurrentDirectory() + "";

    FileReader file = new FileReader(pathField.getText());
    BufferedReader reader = new BufferedReader(file);

    String line = reader.readLine();

    // **********This is to read the text file into program***************//

    // Creating the Array List to store types of variables
    List<String> Types = new ArrayList<String>();
    List<String> Objects = new ArrayList<String>();
    List<String> Predicates = new ArrayList<String>();
    List<String> Cats = new ArrayList<String>();
    List<String> Category = new ArrayList<String>();
    List<String> Action = new ArrayList<String>();

    List<Double> DerivProb = new ArrayList<Double>();
    List<Double> RootProb = new ArrayList<Double>();
    List<String> InitialState = new ArrayList<String>();
    List<String> FinalState = new ArrayList<String>();
    List<String> Roots = new ArrayList<String>();

    List<String> Probability = new ArrayList<String>();

    ArrayList<Document> Doc = new ArrayList<Document>();

    // initialize all types of definitions
    String type = null;//  ww  w. ja  v  a 2s  .c  om
    String object = null;
    String predicate = null;
    String cat = null;
    String category = null;
    String action = null;
    String derivProb = null;
    String rootProb = null;
    String initialState = null;
    String finalState = null;
    String roots = null;
    String probability = null;

    Document Exp = new Document();
    Document definitions = new Document();
    Document stats = new Document();

    // Read type Definitions
    while (line != null) {

        if (line.contains("Defined Type: ")) {
            int startingIndexOfType;
            String types = "Defined Type: ";
            startingIndexOfType = line.indexOf("Defined Type: ");
            int endingIndexOfType = line.indexOf(".");
            type = line.substring(startingIndexOfType + types.length(), endingIndexOfType);
            // putting the piece of string into the new string
            Types.add(type);

        }

        // Read object definitions.
        else if (line.contains("Defined Object: ")) {
            int startingIndexOfObj; // this is to split each word from its
            // spaces and print word by word
            String objects = "Defined Object: ";
            startingIndexOfObj = line.indexOf("Defined Object: ");
            int endingIndexOfObj = line.indexOf(".");
            object = line.substring(startingIndexOfObj + objects.length(), endingIndexOfObj);
            // putting the piece of string into the new string
            Objects.add(object);
        }

        // Read predicate definitions.
        else if (line.contains("Defined predicate:")) {
            String predicates = "Defined predicate:";
            int startingIndexOfPred; // this is to split each word from its
            // spaces and print word by word
            startingIndexOfPred = line.indexOf("Defined predicate:");
            int endingIndexOfPred = line.indexOf(".");
            predicate = line.substring(startingIndexOfPred + predicates.length(), endingIndexOfPred);
            // putting the piece of string into the new string
            Predicates.add(predicate);
        }

        // Defined Cat-Definition
        else if (line.contains("Defined: Cat-Definition: ")) {
            int startingIndexOfCat; // this is to split each word from its
            // spaces and print word by word
            String catDef = "Defined: Cat-Definition: ";
            startingIndexOfCat = line.indexOf("Defined: Cat-Definition: ");
            int endingIndexOfCat = line.indexOf(".", startingIndexOfCat);
            cat = line.substring(startingIndexOfCat + catDef.length(), endingIndexOfCat);
            // putting the piece of string into the new string
            Cats.add(cat);
        }

        // Defined Action Definitions

        else if (line.contains("Defined: category: ")) {
            String categ = "Defined: category: ";
            int startingIndexOfCategory = line.indexOf("Defined: category: ");
            int endingIndexOfCategory = line.indexOf(";", startingIndexOfCategory);
            category = line.substring(startingIndexOfCategory + categ.length(), endingIndexOfCategory);
            Category.add(category);

        }

        else if (line.contains("Defined: ")) {
            // this is to split each word from its
            // spaces and print word by word
            String defined = "Defined: ";
            int startingIndexOfAct = line.indexOf("Defined: ");
            int endingIndexOfAct = line.indexOf(".", startingIndexOfAct);
            action = line.substring(startingIndexOfAct + defined.length(), endingIndexOfAct);
            // putting the piece of string into the new string
            Action.add(action);

        }
        line = reader.readLine();
        definitions = new Document();
        if (line.startsWith("Read goals for query."))
            break;

    }

    definitions.append("Types", Types).append("Objects", Objects).append("Predicates", Predicates)
            .append("Cats", Cats).append("Category", Category).append("Actions", Action);

    elexirCollection.insertOne(definitions);

    while (line != null) {

        DerivProb = new ArrayList<Double>();
        RootProb = new ArrayList<Double>(); // To clear out the array so that
        InitialState = new ArrayList<String>(); // the document does not repeat with
        FinalState = new ArrayList<String>(); // roots from previous explanations
        Roots = new ArrayList<String>();

        if (line.startsWith("[Exp:")) {
            String dp = "derivProb :";
            int startingIndexOfDP;
            startingIndexOfDP = line.indexOf("derivProb: ");
            int endingIndexOfDP = line.indexOf(" root", startingIndexOfDP);
            derivProb = line.substring(startingIndexOfDP + dp.length(), endingIndexOfDP);
            DerivProb.add(Double.parseDouble(derivProb));

            String rp = "rootProb :";
            int startingIndexOfRP;
            startingIndexOfRP = line.indexOf("rootProb: ");
            int endingIndexOfRP = line.indexOf(" Initial", startingIndexOfRP);
            rootProb = line.substring(startingIndexOfRP + rp.length(), endingIndexOfRP);
            RootProb.add(Double.parseDouble(rootProb));

            String is = "Initial State:[ ";
            int startingIndexOfIS;
            startingIndexOfIS = line.indexOf("Initial State:[ ");
            int endingIndexOfIS = line.indexOf(" ]", startingIndexOfIS);
            initialState = line.substring(startingIndexOfIS + is.length(), endingIndexOfIS);
            InitialState.add(initialState);

            String fs = "Final State:[ ";
            int startingIndexOfFS;
            startingIndexOfFS = line.indexOf("Final State:[ ");
            int endingIndexOfFS = line.indexOf(" ]", startingIndexOfFS);
            finalState = line.substring(startingIndexOfFS + fs.length(), endingIndexOfFS); // capture last 
            FinalState.add(finalState);

            String rootStr = "root:[";
            for (int x = line.indexOf(rootStr); x > -1; x = line.indexOf(rootStr, ++x)) {
                int endingIndexOfRoot = line.indexOf("]", x);
                roots = line.substring(x + rootStr.length(), endingIndexOfRoot);

                Roots.add(roots);

            }

            Exp = new Document();
            Exp.append("derivProb", Arrays.asList(derivProb)).append("rootProb", Arrays.asList(rootProb))
                    .append("initialState", Arrays.asList(initialState))
                    .append("finalState", Arrays.asList(finalState)).append("Roots", Roots);

            Doc.add(Exp);
            elexirCollection.insertOne(Exp);

        }

        else if (!line.startsWith("[Exp:")) {
            //System.out.println("At first if else");
            // System.out.println(line);
            if (line.contains("Probabilites:")) {
                //System.out.println("At line equals prob");
                while (!line.contains("*** Done with problem. ***")) {
                    //System.out.println("Reached while loop");
                    //read each line and save here

                    probability += line + "\n";

                    //System.out.println(probability);

                    line = reader.readLine();

                }

                Probability.add(probability);
                stats.append("Probability", Probability);
                elexirCollection.insertOne(stats);
            }

        }

        line = reader.readLine();
    } // end while    

    FindIterable<Document> iter = elexirCollection.find();
    System.out.println("Your Documents have been stored into mongoDB ");

}

From source file:MenuProb.java

public static void getProbability() {

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("database");
    MongoCollection<Document> elexirCollection = db.getCollection("test");

    FindIterable<Document> results = elexirCollection
            .find(new BasicDBObject("Probability", new BasicDBObject("$gt", "0")));
    //FindIterable<Document> iter = elexirCollection.find(new BasicDBObject("derivProb", 2));

    for (Document doc : results) {

        List<String> conv = (List<String>) doc.get("Probability");

        String[] convArr = new String[conv.size()];
        convArr = conv.toArray(convArr);

        for (String s : convArr)
            ProbTextArea.append(s + "\n");

    }/*  w w  w  . j ava  2s . co  m*/
}

From source file:MenuDefAct.java

public static void getActions() {

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("database");
    MongoCollection<Document> elexirCollection = db.getCollection("test");

    FindIterable<Document> results = elexirCollection
            .find(new BasicDBObject("Types", new BasicDBObject("$gt", "0")));
    //FindIterable<Document> iter = elexirCollection.find(new BasicDBObject("derivProb", 2));

    for (Document doc : results) {

        List<String> conv = (List<String>) doc.get("Actions");

        String[] convArr = new String[conv.size()];
        convArr = conv.toArray(convArr);

        for (String s : convArr)
            ActTextArea.append(s + "\n");

    }/*from   ww  w .  j a va 2 s.  c om*/
}

From source file:UnitTest3.java

License:Open Source License

public static void testgridfs2() throws FileNotFoundException, IOException {

    long time1;/*from  w  w  w  .j  ava  2 s.c  o  m*/
    long time2;
    long time3;
    long time4;
    String fileName = "makezip3.rar";

    MongoClient mongo = new MongoClient("localhost", 27017);
    //DB db = mongo.getDB("JFileDB");
    MongoDatabase db = mongo.getDatabase("JFileDB");
    GridFSBucket gridFSBucket = GridFSBuckets.create(db);

    // Get the input stream
    time1 = System.currentTimeMillis();
    InputStream streamToUploadFrom = new FileInputStream("/home/anees/workspace/testdata/in/" + fileName);

    // Create some custom options
    GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024 * 1024)
            .metadata(new Document("type", "class"));

    ObjectId fileId = gridFSBucket.uploadFromStream(fileName, streamToUploadFrom, options);
    streamToUploadFrom.close();
    time2 = System.currentTimeMillis();

    time3 = System.currentTimeMillis();
    Date date = new Date();

    FileOutputStream streamToDownloadTo = new FileOutputStream(
            "/home/anees/workspace/testdata/out/" + fileName + "_" + date.toString());
    // latest file with same name in DB
    GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(-1);
    //original file with same file name in DB GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0);

    //downloadOptions.
    gridFSBucket.downloadToStreamByName(fileName, streamToDownloadTo, downloadOptions);
    streamToDownloadTo.close();
    time4 = System.currentTimeMillis();

    System.out.println("The fileId of the uploaded file is: " + fileId.toHexString());
    System.out.println("Upload time taken : time2 - time1 : " + (time2 - time1));
    System.out.println("Download time taken : time4 - time3 : " + (time4 - time3));

    /*
     Set the revision of the file to retrieve.
            
    Revision numbers are defined as follows:
            
    0 = the original stored file
    1 = the first revision
    2 = the second revision
    etc..
    -2 = the second most recent revision
    -1 = the most recent revision
            
     */

    mongo.close();

}

From source file:UnitTest3.java

License:Open Source License

public static void testgridfs3() throws FileNotFoundException, IOException {

    long time1;//from  w  ww .  ja  va 2s  .  c o  m
    long time2;
    long time3;
    long time4;
    int n = 0;
    // "/home/anees/workspace/testdata/in/App3.class"
    String fileName = "makezip4.rar";

    MongoClient mongo = new MongoClient("localhost", 27017);
    //DB db = mongo.getDB("JFileDB");
    MongoDatabase db = mongo.getDatabase("JFileDB");
    GridFSBucket gridFSBucket = GridFSBuckets.create(db);

    // Get the input stream
    time1 = System.currentTimeMillis();
    InputStream streamToUploadFrom = new FileInputStream("/home/anees/workspace/testdata/in/" + fileName);

    // Create some custom options
    GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024 * 1024)
            .metadata(new Document("type", "class"));

    byte data[] = new byte[64 * 1024 * 1024];
    GridFSUploadStream uploadStream = gridFSBucket.openUploadStream(fileName, options);

    while ((n = streamToUploadFrom.read(data)) > 0) {
        uploadStream.write(data, 0, n);
    }
    uploadStream.close();
    time2 = System.currentTimeMillis();

    time3 = System.currentTimeMillis();
    Date date = new Date();
    FileOutputStream streamToDownloadTo = new FileOutputStream(
            "/home/anees/workspace/testdata/out/" + fileName + "_" + date.toString());
    GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(-1);

    GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStreamByName(fileName, downloadOptions);
    long fileLength = downloadStream.getGridFSFile().getLength();
    byte[] bytesToWriteTo = new byte[64 * 1024 * 1024];

    while ((n = downloadStream.read(bytesToWriteTo)) > 0) {
        streamToDownloadTo.write(bytesToWriteTo, 0, n);
    }
    downloadStream.close();
    time4 = System.currentTimeMillis();

    System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString());
    System.out.println("Upload time taken : time2 - time1 : " + (time2 - time1));
    System.out.println("Download time taken : time4 - time3 : " + (time4 - time3));

    streamToDownloadTo.close();
    streamToUploadFrom.close();
    mongo.close();
}

From source file:UnitTest3.java

License:Open Source License

public static void testgridfs4() throws FileNotFoundException, IOException {

    MongoClient mongo = new MongoClient("localhost", 27017);
    //DB db = mongo.getDB("JFileDB");
    MongoDatabase db = mongo.getDatabase("JFileDB");
    GridFSBucket gridFSBucket = GridFSBuckets.create(db);

    // Get the input stream
    InputStream streamToUploadFrom = new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8));

    // Create some custom options
    GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024)
            .metadata(new Document("type", "file"));

    ObjectId fileId = gridFSBucket.uploadFromStream("test", streamToUploadFrom, options);
    streamToUploadFrom.close();/*from   w ww.j a v  a2s .  com*/
    System.out.println("The fileId of the uploaded file is: " + fileId.toHexString());

    // Get some data to write
    byte[] data = "some data to upload into GridFS".getBytes(StandardCharsets.UTF_8);

    GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sample_data");
    uploadStream.write(data);
    uploadStream.close();
    System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString());

    /*
    gridFSBucket.find().forEach(new Block<GridFSFile>() {
            
    public void apply(final GridFSFile gridFSFile) {
        System.out.println(gridFSFile.getFilename());
    }
    });
    */

    /*
    gridFSBucket.find(eq("metadata.contentType", "image/png")).forEach(
        new Block<GridFSFile>() {
                    
            public void apply(final GridFSFile gridFSFile) {
                System.out.println(gridFSFile.getFilename());
            }
        });
    */

    FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/test.txt");
    gridFSBucket.downloadToStream(fileId, streamToDownloadTo);
    streamToDownloadTo.close();

    streamToDownloadTo = new FileOutputStream("/tmp/test.txt");
    GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0);
    gridFSBucket.downloadToStreamByName("test", streamToDownloadTo, downloadOptions);
    streamToDownloadTo.close();

    GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId);
    int fileLength = (int) downloadStream.getGridFSFile().getLength();
    byte[] bytesToWriteTo = new byte[fileLength];
    downloadStream.read(bytesToWriteTo);
    downloadStream.close();

    System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));

    downloadStream = gridFSBucket.openDownloadStreamByName("sample_data");
    fileLength = (int) downloadStream.getGridFSFile().getLength();
    bytesToWriteTo = new byte[fileLength];
    downloadStream.read(bytesToWriteTo);
    downloadStream.close();

    System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));

    gridFSBucket.rename(fileId, "test2");

    gridFSBucket.delete(fileId);
    mongo.close();
}

From source file:MenuDefTyp.java

public static void getTypes() {

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("database");
    MongoCollection<Document> elexirCollection = db.getCollection("test");

    FindIterable<Document> results = elexirCollection
            .find(new BasicDBObject("Objects", new BasicDBObject("$gt", ".0001")));
    //FindIterable<Document> iter = elexirCollection.find(new BasicDBObject("derivProb", 2));

    for (Document doc : results) {
        // do something with each result

        List<String> conv = (List<String>) doc.get("Types");

        String[] convArr = new String[conv.size()];
        convArr = conv.toArray(convArr);

        for (String s : convArr)
            TypTextArea.append(s + "\n");

    }//from w ww .  j  av  a 2s .  co m
}