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:nosqltools.MainForm.java

private void jList2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList2MouseClicked
    final AddUsersDialog dlg_addusers = new AddUsersDialog(this);
    ActionListener al3 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dlg_addusers.setVisible(true);
            viewUsersMenuItem.doClick();
            Text_MessageBar.setText(jList2.getSelectedValue().toString());
        }/*from   w ww.j a v a 2 s . c o m*/
    };

    ActionListener al1 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Text_MessageBar.setText(jList2.getSelectedValue().toString());
                MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
                DB db = mongoClient.getDB(DBList.getSelectedValue().toString()); //To arrange to be the database which is connected to.
                db.removeUser(jList2.getSelectedValue().toString());
                viewUsersMenuItem.setEnabled(true);
                viewUsersMenuItem.doClick();
                viewUsersMenuItem.setEnabled(false);
            } catch (Exception ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };

    //Create the JPopupMenu with three options.
    final JPopupMenu popupMenu = new JPopupMenu();
    JMenuItem item1 = new JMenuItem("Delete");
    item1.addActionListener(al1);
    popupMenu.add(item1);
    popupMenu.add(new JPopupMenu.Separator());
    JMenuItem item3 = new JMenuItem("Add");
    item3.addActionListener(al3);
    popupMenu.add(item3);

    jList2.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent me) {
            if (SwingUtilities.isRightMouseButton(me) // if right mouse button clicked
                    && !jList2.isSelectionEmpty() // and list selection is not empty
                    && jList2.locationToIndex(me.getPoint()) // and clicked point is
            == jList2.getSelectedIndex()) { // inside selected item bounds
                //Text_MessageBar.setText(jList2.getSelectedValue().toString() + " RIGHT");
                Text_MessageBar.setForeground(Color.blue);
                popupMenu.show(jList2, me.getX(), me.getY());
            } else {
                //Text_MessageBar.setText(jList2.getSelectedValue().toString() + " LEFT");
                Text_MessageBar.setForeground(Color.MAGENTA);
            }
        }
    });
}

From source file:oopproject1.MakaleDaoImpl.java

@Override
public ArrayList<Makale> getAllMakale() {
    ArrayList<Makale> makaledb = new ArrayList<Makale>();
    try {// w w  w .j  a v a2 s . co m
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("testdb");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("makale");
        System.out.println("Collection mycol selected successfully");

        DBCursor cursor = coll.find();
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            //do your thing
            System.out.println(obj.get("id"));
            Makale mak = new Makale();
            mak.setId((String) obj.get("id"));
            mak.setTitle((String) obj.get("title"));
            mak.setAuthors((String) obj.get("author"));
            mak.setVenue((String) obj.get("venue"));
            mak.setYear((String) obj.get("year"));
            mak.setContent((String) obj.get("content"));
            mak.setFrequencies((Map<String, Integer>) obj.get("frequencies"));
            makaledb.add(mak);
        }
    } catch (UnknownHostException ex) {
        Logger.getLogger(MakaleDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    return makaledb;
}

From source file:oopproject1.MakaleDaoImpl.java

public void UpdateMakale(Makale m1) {

    MongoClient mongo;
    try {/*from   ww  w .  ja va  2 s  .c om*/
        mongo = new MongoClient("localhost", 27017);
        DB db = mongo.getDB("testdb");
        DBCollection table = db.getCollection("makale");
        BasicDBObject document = new BasicDBObject();
        BasicDBObject searchQuery = new BasicDBObject().append("id", m1.getId());
        document.put("id", m1.getId());
        document.put("title", m1.getTitle());
        document.put("author", m1.getAuthors());
        document.put("venue", m1.getVenue());
        document.put("year", m1.getYear());
        document.put("content", m1.getContent());
        document.put("frequencies", m1.getFrequencies()); //iinde map<> o yzden veri tabanna nasl aktarlacak.
        table.insert(document);
    } catch (UnknownHostException ex) {
        Logger.getLogger(MakaleDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:oopproject1.MakaleDaoImpl.java

@Override
public Makale getMakale(String id) {

    Makale m1 = new Makale();
    m1 = null;// w w  w.j  av  a 2  s .c  om

    MongoClient mongo;
    try {
        mongo = new MongoClient("localhost", 27017);
        DB db = mongo.getDB("testdb");
        DBCollection table = db.getCollection("makale");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("id", id);
        DBCursor cursor = table.find(searchQuery);
        while (cursor.hasNext()) {
            DBObject smt = cursor.next();
            System.out.println(smt);
            //    m1.setId(id);
        }

    } catch (UnknownHostException ex) {
        Logger.getLogger(MakaleDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return m1;
}

From source file:org.alfresco.cacheserver.dao.mongo.MongoDbFactory.java

License:Open Source License

public DB createInstance() throws Exception {
    DB db = null;/*from   www  . j a v a2s. co m*/
    //        try
    //        {
    if (enabled) {
        if (mongo != null) {
            if (dbName != null) {
                db = mongo.getDB(dbName);
            } else {
                db = mongo.getDB(UUID.randomUUID().toString());
            }
        } else {
            if (mongoURI == null || dbName == null) {
                throw new RuntimeException("Must provide mongoURI and dbName or a mongo object");
            }
            MongoClientURI uri = new MongoClientURI(mongoURI);
            MongoClient mongoClient = new MongoClient(uri);
            db = mongoClient.getDB(dbName);
        }

        if (db == null) {
            throw new InstantiationException("Could not instantiate a Mongo DB instance");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Instatiated DB object for dbName '" + db.getName() + "'");
        }
        CommandResult stats = db.getStats();
        if (logger.isTraceEnabled()) {
            stats = db.getStats();
            for (String key : stats.keySet()) {
                logger.trace("\t" + key + " = " + stats.get(key).toString());
            }
        }
    }
    //        }
    //        catch(MongoException.Network e)
    //        {
    //            throw new MongoDbUnavailableException("Mongo network exception, database down?", e);
    //        }
    //        catch(UnknownHostException e)
    //        {
    //            throw new MongoDbUnavailableException("Mongo host not found", e);
    //        }
    return db;
}

From source file:org.alfresco.mongo.MongoDBFactory.java

License:Open Source License

/**
 * Create an instance of the factory.  The URI given must not contain a database name or user/password details.
 * This forces the client URI to be an instance that can be shared between instances of this factory.
 * //from   www  .j a  va  2 s  . c om
 * @param mongoClient               the mongo client
 * @param database                  the database to connect to (never <tt>null</tt>)
 * 
 * @throws IllegalArgumentException if the arguments are null when not allowed or contain invalid information
 */
public MongoDBFactory(MongoClient mongoClient, String database) {
    if (mongoClient == null || database == null) {
        throw new IllegalArgumentException("'mongoClientURI' and 'database' arguments may not be null.");
    }

    // Get the database
    this.db = mongoClient.getDB(database);
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.replica.NodeCollectionProvider.java

License:Apache License

@SuppressWarnings("deprecation")
public DBCollection get(String hostname) throws UnknownHostException {
    if (collections.containsKey(hostname)) {
        return collections.get(hostname);
    }/*from  w ww. j  a v a  2  s  .  c  o  m*/

    MongoClient client;
    if (originalMongoUri == null) {
        MongoClientURI uri = new MongoClientURI("mongodb://" + hostname);
        client = new MongoClient(uri);
    } else {
        client = prepareClientForHostname(hostname);
    }

    DB db = client.getDB(dbName);
    db.getMongo().slaveOk();
    DBCollection collection = db.getCollection(Collection.NODES.toString());
    collections.put(hostname, collection);
    return collection;
}

From source file:org.apache.jackrabbit.oak.run.CheckpointsCommand.java

License:Apache License

@Override
public void execute(String... args) throws Exception {
    OptionParser parser = new OptionParser();
    OptionSpec segmentTar = parser.accepts("segment-tar", "Use oak-segment-tar instead of oak-segment");
    OptionSet options = parser.parse(args);

    if (options.nonOptionArguments().isEmpty()) {
        System.out.println(/*from  www .  j  ava 2  s . co m*/
                "usage: checkpoints {<path>|<mongo-uri>} [list|rm-all|rm-unreferenced|rm <checkpoint>] [--segment-tar]");
        System.exit(1);
    }

    boolean success = false;
    Checkpoints cps;
    Closer closer = Closer.create();
    try {
        String op = "list";
        if (options.nonOptionArguments().size() >= 2) {
            op = options.nonOptionArguments().get(1).toString();
            if (!"list".equals(op) && !"rm-all".equals(op) && !"rm-unreferenced".equals(op)
                    && !"rm".equals(op)) {
                failWith("Unknown command.");
            }
        }

        String connection = options.nonOptionArguments().get(0).toString();
        if (connection.startsWith(MongoURI.MONGODB_PREFIX)) {
            MongoClientURI uri = new MongoClientURI(connection);
            MongoClient client = new MongoClient(uri);
            final DocumentNodeStore store = new DocumentMK.Builder().setMongoDB(client.getDB(uri.getDatabase()))
                    .getNodeStore();
            closer.register(Utils.asCloseable(store));
            cps = Checkpoints.onDocumentMK(store);
        } else if (options.has(segmentTar)) {
            cps = Checkpoints.onSegmentTar(new File(connection), closer);
        } else {
            cps = Checkpoints.onSegment(new File(connection), closer);
        }

        System.out.println("Checkpoints " + connection);
        if ("list".equals(op)) {
            int cnt = 0;
            for (Checkpoints.CP cp : cps.list()) {
                System.out.printf("- %s created %s expires %s%n", cp.id, new Timestamp(cp.created),
                        new Timestamp(cp.expires));
                cnt++;
            }
            System.out.println("Found " + cnt + " checkpoints");
        } else if ("rm-all".equals(op)) {
            long time = System.currentTimeMillis();
            long cnt = cps.removeAll();
            time = System.currentTimeMillis() - time;
            if (cnt != -1) {
                System.out.println("Removed " + cnt + " checkpoints in " + time + "ms.");
            } else {
                failWith("Failed to remove all checkpoints.");
            }
        } else if ("rm-unreferenced".equals(op)) {
            long time = System.currentTimeMillis();
            long cnt = cps.removeUnreferenced();
            time = System.currentTimeMillis() - time;
            if (cnt != -1) {
                System.out.println("Removed " + cnt + " checkpoints in " + time + "ms.");
            } else {
                failWith("Failed to remove unreferenced checkpoints.");
            }
        } else if ("rm".equals(op)) {
            if (options.nonOptionArguments().size() < 3) {
                failWith("Missing checkpoint id");
            } else {
                String cp = options.nonOptionArguments().get(2).toString();
                long time = System.currentTimeMillis();
                int cnt = cps.remove(cp);
                time = System.currentTimeMillis() - time;
                if (cnt != 0) {
                    if (cnt == 1) {
                        System.out.println("Removed checkpoint " + cp + " in " + time + "ms.");
                    } else {
                        failWith("Failed to remove checkpoint " + cp);
                    }
                } else {
                    failWith("Checkpoint '" + cp + "' not found.");
                }
            }
        }
        success = true;
    } catch (Throwable t) {
        System.err.println(t.getMessage());
    } finally {
        closer.close();
    }
    if (!success) {
        System.exit(1);
    }
}

From source file:org.apache.jackrabbit.oak.run.DataStoreCheckCommand.java

License:Apache License

@Override
public void execute(String... args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();//  w w w.jav  a 2 s .com

    String helpStr = "datastorecheck [--id] [--ref] [--consistency] [--store <path>|<mongo_uri>] "
            + "[--s3ds <s3ds_config>|--fds <fds_config>] [--dump <path>]";

    Closer closer = Closer.create();
    try {
        // Options for operations requested
        OptionSpecBuilder idOp = parser.accepts("id", "Get ids");
        OptionSpecBuilder refOp = parser.accepts("ref", "Get references");
        OptionSpecBuilder consistencyOp = parser.accepts("consistency", "Check consistency");

        // Node Store - needed for --ref, --consistency
        ArgumentAcceptingOptionSpec<String> store = parser.accepts("store", "Node Store")
                .requiredIf(refOp, consistencyOp).withRequiredArg().ofType(String.class);
        // Optional argument to specify the dump path
        ArgumentAcceptingOptionSpec<String> dump = parser.accepts("dump", "Dump Path").withRequiredArg()
                .ofType(String.class);
        OptionSpec segmentTar = parser.accepts("segment-tar", "Use oak-segment-tar instead of oak-segment");

        OptionSpec<?> help = parser.acceptsAll(asList("h", "?", "help"), "show help").forHelp();

        // Required rules (any one of --id, --ref, --consistency)
        idOp.requiredUnless(refOp, consistencyOp);
        refOp.requiredUnless(idOp, consistencyOp);
        consistencyOp.requiredUnless(idOp, refOp);

        OptionSet options = null;
        try {
            options = parser.parse(args);
        } catch (Exception e) {
            System.err.println(e);
            parser.printHelpOn(System.err);
            return;
        }

        if (options.has(help)) {
            parser.printHelpOn(System.out);
            return;
        }

        String dumpPath = JAVA_IO_TMPDIR.value();
        if (options.has(dump)) {
            dumpPath = options.valueOf(dump);
        }

        GarbageCollectableBlobStore blobStore = null;
        BlobReferenceRetriever marker = null;
        if (options.has(store)) {
            String source = options.valueOf(store);
            if (source.startsWith(MongoURI.MONGODB_PREFIX)) {
                MongoClientURI uri = new MongoClientURI(source);
                MongoClient client = new MongoClient(uri);
                DocumentNodeStore nodeStore = new DocumentMK.Builder()
                        .setMongoDB(client.getDB(uri.getDatabase())).getNodeStore();
                closer.register(Utils.asCloseable(nodeStore));
                blobStore = (GarbageCollectableBlobStore) nodeStore.getBlobStore();
                marker = new DocumentBlobReferenceRetriever(nodeStore);
            } else if (options.has(segmentTar)) {
                marker = SegmentTarUtils.newBlobReferenceRetriever(source, closer);
            } else {
                FileStore fileStore = openFileStore(source);
                closer.register(Utils.asCloseable(fileStore));
                marker = new SegmentBlobReferenceRetriever(fileStore.getTracker());
            }
        }

        // Initialize S3/FileDataStore if configured
        GarbageCollectableBlobStore dataStore = Utils.bootstrapDataStore(args, closer);
        if (dataStore != null) {
            blobStore = dataStore;
        }

        // blob store still not initialized means configuration not supported
        if (blobStore == null) {
            System.err.println("Operation not defined for SegmentNodeStore without external datastore");
            parser.printHelpOn(System.err);
            return;
        }

        FileRegister register = new FileRegister(options);
        closer.register(register);

        if (options.has(idOp) || options.has(consistencyOp)) {
            retrieveBlobIds(blobStore, register.createFile(idOp, dumpPath));
        }

        if (options.has(refOp) || options.has(consistencyOp)) {
            retrieveBlobReferences(blobStore, marker, register.createFile(refOp, dumpPath));
        }

        if (options.has(consistencyOp)) {
            checkConsistency(register.get(idOp), register.get(refOp),
                    register.createFile(consistencyOp, dumpPath));
        }
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        closer.close();
    }
}

From source file:org.apache.jackrabbit.oak.run.ResetClusterIdCommand.java

License:Apache License

@Override
public void execute(String... args) throws Exception {
    OptionParser parser = new OptionParser();
    OptionSpec segmentTar = parser.accepts("segment-tar", "Use oak-segment-tar instead of oak-segment");
    OptionSet options = parser.parse(args);

    if (options.nonOptionArguments().isEmpty()) {
        System.out.println("usage: resetclusterid {<path>|<mongo-uri>}");
        System.exit(1);/* w  w w .  j a  va2 s.  c o  m*/
    }

    String source = options.nonOptionArguments().get(0).toString();

    Closer closer = Closer.create();
    try {
        NodeStore store;
        if (args[0].startsWith(MongoURI.MONGODB_PREFIX)) {
            MongoClientURI uri = new MongoClientURI(source);
            MongoClient client = new MongoClient(uri);
            final DocumentNodeStore dns = new DocumentMK.Builder().setMongoDB(client.getDB(uri.getDatabase()))
                    .getNodeStore();
            closer.register(Utils.asCloseable(dns));
            store = dns;
        } else if (options.has(segmentTar)) {
            store = SegmentTarUtils.bootstrapNodeStore(source, closer);
        } else {
            FileStore fs = openFileStore(source);
            closer.register(Utils.asCloseable(fs));
            store = SegmentNodeStore.builder(fs).build();
        }

        deleteClusterId(store);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }

}