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:localdomain.localhost.MyServlet.java

License:Apache License

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter writer = resp.getWriter();

    writer.println("<html>");
    writer.println("<head><title>MyServlet</title></head>");
    writer.println("<body><h1>MyServlet</h1>");

    writer.println("<h2>MongoDB</h2>");

    String uriAsString = System.getProperty("MONGOHQ_URL_MYDB", "mongodb://localhost/local");

    MongoClient mongoClient = null;//from   w ww .ja va2  s .  c  o m
    try {
        writer.println("<h4>MongoClientURI</h4>");

        MongoClientURI uri = new MongoClientURI(uriAsString);
        writer.println("<p>" + "host=" + uri.getHosts() + ",username=" + uri.getUsername() + ",database="
                + uri.getDatabase() + ",collection=" + uri.getCollection() + "</p>");

        writer.println("<h4>MongoClient</h4>");

        mongoClient = new MongoClient(uri);
        writer.println("<p>" + mongoClient + "</p>");

        writer.println("<h4>Databases</h4>");

        try {
            List<String> databaseNames = mongoClient.getDatabaseNames();
            writer.println("<ul>");
            for (String databaseName : databaseNames) {
                writer.println("<li>" + databaseName
                        + (databaseName.equals(uri.getDatabase()) ? " - default database" : ""));
            }
            writer.println("</ul>");
        } catch (Exception e) {
            writer.println("<p>Could not list the databases of the MongoDB instance: <code>" + e.getMessage()
                    + "</code></p>");

        }

        writer.println("<h4>Database</h4>");

        DB db = mongoClient.getDB(uri.getDatabase());
        writer.println("<p>DB: " + db.getName() + "</p>");

        writer.println("<h4>Collections</h4>");
        Set<String> myCollections = db.getCollectionNames();
        if (myCollections.isEmpty()) {
            writer.println("<p>NO COLLECTIONS!</p>");

        } else {

            writer.println("<ul>");
            for (String collection : myCollections) {
                DBCollection dbCollection = db.getCollection(collection);
                writer.println(
                        "<li>" + dbCollection.getName() + " - " + dbCollection.getCount() + " entries</li>");
            }
            writer.println("</ul>");
        }
        writer.println("<h4>Success!</h4>");
        writer.println("SUCCESS to access the mongodb database");

    } catch (Exception e) {
        writer.println("<code><pre>");
        e.printStackTrace(writer);
        writer.println("</pre></code>");

        e.printStackTrace();
    } finally {
        if (mongoClient != null) {
            try {
                mongoClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    writer.println("</body></html>");

}

From source file:me.carbou.mathieu.tictactoe.di.ServiceBindings.java

License:Apache License

@Provides
@Singleton/* www . j a  v  a2  s  .  c  o  m*/
DB db(Clock clock) throws UnknownHostException {
    MongoClientURI mongoClientURI = new MongoClientURI(Env.MONGOLAB_URI);
    MongoClient mongoClient = new MongoClient(mongoClientURI);
    MongoJsr310.addJsr310EncodingHook();
    BSON.addEncodingHook(GString.class, o -> o instanceof GString ? o.toString() : o);
    BSON.addEncodingHook(ZoneId.class, o -> o instanceof ZoneId ? ((ZoneId) o).getId() : o);
    BSON.addEncodingHook(Enum.class, o -> o instanceof Enum ? ((Enum) o).name() : o);
    BSON.addEncodingHook(Locale.class, o -> o instanceof Locale ? o.toString() : o);
    BSON.addEncodingHook(BigDecimal.class, o -> o instanceof BigDecimal ? ((BigDecimal) o).doubleValue() : o);
    BSON.addEncodingHook(BigInteger.class, o -> o instanceof BigInteger ? ((BigInteger) o).longValue() : o);
    return new DB(mongoClient.getDB(mongoClientURI.getDatabase()), clock);
}

From source file:mx.org.cedn.avisosconagua.mongo.UpdateIssueDate.java

License:Open Source License

public static void main(String[] arg) throws Exception {
    MongoClientURI mongoClientURI = new MongoClientURI(System.getenv("MONGOHQ_URL"));
    MongoClient mongoClient = new MongoClient(mongoClientURI);
    DB mongoDB = mongoClient.getDB(mongoClientURI.getDatabase());
    String GENERATED_COL = "GeneratedFiles";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    SimpleDateFormat isoformater = new SimpleDateFormat("YYYY-MM-dd HH:mm");
    if (null != mongoClientURI.getUsername()) {
        mongoDB.authenticate(mongoClientURI.getUsername(), mongoClientURI.getPassword());
    }//  w  w  w.ja va  2  s.com
    DBCollection col = mongoDB.getCollection(GENERATED_COL);
    DBCursor cursor = col.find();
    for (DBObject obj : cursor) {
        String date = (String) obj.get("issueDate");
        Date fec = null;
        try {
            fec = sdf.parse(date);
        } catch (ParseException npe) {

        }
        if (null != fec) {
            date = isoformater.format(fec);
            DBObject act = col.findOne(obj);
            obj.put("issueDate", date);
            col.update(act, obj);
        }
    }
}

From source file:no.asgari.civilization.server.application.CivilizationApplication.java

License:Apache License

@Override
public void run(CivilizationConfiguration configuration, Environment environment) throws Exception {
    DB db;/*from   w w w  . j  ava2 s  .c o  m*/
    MongoClient mongo;
    if (!Strings.isNullOrEmpty(configuration.mongodbUser)
            && !Strings.isNullOrEmpty(configuration.mongodbPassword)) {
        MongoClientURI clientURI = new MongoClientURI("mongodb://" + configuration.mongodbUser + ":"
                + configuration.mongodbPassword + "@" + configuration.mongohost + ":" + configuration.mongoport
                + "/" + configuration.mongodb);

        mongo = new MongoClient(clientURI);
        db = mongo.getDB(clientURI.getDatabase());
    } else {
        mongo = new MongoClient(configuration.mongohost, configuration.mongoport);
        db = mongo.getDB(configuration.mongodb);
    }
    MongoManaged mongoManaged = new MongoManaged(mongo);
    environment.lifecycle().manage(mongoManaged);

    JacksonDBCollection<Player, String> playerCollection = JacksonDBCollection
            .wrap(db.getCollection(Player.COL_NAME), Player.class, String.class);
    JacksonDBCollection<PBF, String> pbfCollection = JacksonDBCollection.wrap(db.getCollection(PBF.COL_NAME),
            PBF.class, String.class);
    JacksonDBCollection<Chat, String> chatCollection = JacksonDBCollection.wrap(db.getCollection(Chat.COL_NAME),
            Chat.class, String.class);
    createUniqueIndexForPlayer(playerCollection);
    createUsernameCache(playerCollection);
    //createUniqueIndexForPBF(pbfCollection);
    createIndexForChat(chatCollection);
    //createItemCache(); //TODO Have to rewrite the code to make it work, right now everyone gets same number and same draws

    //healtcheck
    environment.healthChecks().register("MongoHealthCheck", new MongoHealthCheck(mongo));

    //Resources
    environment.jersey().register(new GameResource(db));
    environment.jersey().register(new AuthResource(db));
    environment.jersey().register(new PlayerResource(db));
    environment.jersey().register(new DrawResource(db));
    environment.jersey().register(new AdminResource(db));

    //Authenticator
    CachingAuthenticator<BasicCredentials, Player> cachingAuthenticator = new CachingAuthenticator<>(
            new MetricRegistry(), new CivAuthenticator(db), CacheBuilderSpec.parse("expireAfterWrite=120m"));

    //Authentication binder
    Binder authBinder = AuthFactory
            .binder(new BasicAuthFactory<>(cachingAuthenticator, "civilization", Player.class));

    //Authentication
    environment.jersey().register(authBinder);

    // Configure CORS parameters
    FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORSFilter", CrossOriginFilter.class);

    filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false,
            environment.getApplicationContext().getContextPath() + "api/*");
    filter.setInitParameter(ALLOWED_METHODS_PARAM, "GET,PUT,POST,OPTIONS,DELETE");
    filter.setInitParameter(ALLOWED_ORIGINS_PARAM, "*");
    filter.setInitParameter(ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,authorization");
    filter.setInitParameter(ALLOW_CREDENTIALS_PARAM, "true");
    filter.setInitParameter(EXPOSED_HEADERS_PARAM,
            "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location,Accept-Content-Encoding");
}

From source file:org.alfresco.mongo.MongoClientFactory.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.
 * /*w  ww.j  a  v  a2 s.  c o m*/
 * @param mongoClientURI            the client URI, which <b>must not</b> reference a database, username or password
 * @param username                  the username to use when connecting (<tt>null</tt> allowed and empty string is ignored)
 * @param password                  the user password for the database (<tt>null</tt> allowed and empty string is ignored)
 * 
 * @throws IllegalArgumentException if the arguments are null when not allowed or contain invalid information
 */
public MongoClientFactory(MongoClientURI mongoClientURI, String username, String password)
        throws UnknownHostException {
    validateMongoClientURI(mongoClientURI);

    if (mongoClientURI.getDatabase() != null) {
        throw new IllegalArgumentException(
                "The provided 'mongoClientURI' instance may not reference a specific database: "
                        + MongoClientFactory.toStringSafe(mongoClientURI));
    } else if (mongoClientURI.getUsername() != null) {
        throw new IllegalArgumentException(
                "The provided 'mongoClientURI' instance may not reference a specific username: "
                        + MongoClientFactory.toStringSafe(mongoClientURI));
    } else if (mongoClientURI.getPassword() != null) {
        throw new IllegalArgumentException(
                "The provided 'mongoClientURI' instance may not reference a specific password: "
                        + MongoClientFactory.toStringSafe(mongoClientURI));
    }

    // Reformat the URI if credentials were supplied
    if (username != null && username.length() > 0) {
        String userPwdCombo = username;
        if (password != null && password.length() > 0) {
            userPwdCombo = username + ":" + password;
        }
        String mongoClientURIstr = mongoClientURI.getURI().replace("mongodb://",
                "mongodb://" + userPwdCombo + "@");
        mongoClientURI = new MongoClientURI(mongoClientURIstr);
    }

    // Construct the client
    mongoClient = new MongoClient(mongoClientURI);

    // Done
    if (logger.isInfoEnabled()) {
        logger.info("New MongoDB client created using URL: " + MongoClientFactory.toStringSafe(mongoClientURI));
    }
}

From source file:org.apache.drill.exec.store.mongo.config.MongoPersistentStoreProvider.java

License:Apache License

@Override
public void start() throws IOException {
    MongoClientURI clientURI = new MongoClientURI(mongoURL);
    client = new MongoClient(clientURI);
    MongoDatabase db = client.getDatabase(clientURI.getDatabase());
    collection = db.getCollection(clientURI.getCollection()).withWriteConcern(WriteConcern.JOURNALED);
    Bson index = Indexes.ascending(pKey);
    collection.createIndex(index);//from  ww w. ja  va2 s .  com
}

From source file:org.apache.drill.exec.store.mongo.config.MongoPStoreProvider.java

License:Apache License

@Override
public void start() throws IOException {
    MongoClientURI clientURI = new MongoClientURI(mongoURL);
    client = new MongoClient(clientURI);
    DB db = client.getDB(clientURI.getDatabase());
    collection = db.getCollection(clientURI.getCollection());
    collection.setWriteConcern(WriteConcern.JOURNALED);
    DBObject index = new BasicDBObject(1).append(pKey, Integer.valueOf(1));
    collection.createIndex(index);/*w  ww. j a v a 2 s  .  co  m*/
}

From source file:org.apache.jackrabbit.oak.console.Console.java

License:Apache License

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    OptionSpec<Integer> clusterId = parser.accepts("clusterId", "MongoMK clusterId").withRequiredArg()
            .ofType(Integer.class).defaultsTo(0);
    OptionSpec quiet = parser.accepts("quiet", "be less chatty");
    OptionSpec shell = parser.accepts("shell", "run the shell after executing files");
    OptionSpec readWrite = parser.accepts("read-write", "connect to repository in read-write mode");
    OptionSpec<String> fdsPathSpec = parser.accepts("fds-path", "Path to FDS store").withOptionalArg()
            .defaultsTo("");
    OptionSpec segmentTar = parser.accepts("segment-tar", "Use oak-segment-tar instead of oak-segment");
    OptionSpec help = parser.acceptsAll(asList("h", "?", "help"), "show help").forHelp();

    // RDB specific options
    OptionSpec<String> rdbjdbcuser = parser.accepts("rdbjdbcuser", "RDB JDBC user").withOptionalArg()
            .defaultsTo("");
    OptionSpec<String> rdbjdbcpasswd = parser.accepts("rdbjdbcpasswd", "RDB JDBC password").withOptionalArg()
            .defaultsTo("");

    OptionSpec<String> nonOption = parser.nonOptions("console {<path-to-repository> | <mongodb-uri>}");

    OptionSet options = parser.parse(args);
    List<String> nonOptions = nonOption.values(options);

    if (options.has(help)) {
        parser.printHelpOn(System.out);
        System.exit(0);//w w w .  jav a2  s.  com
    }

    if (nonOptions.isEmpty()) {
        parser.printHelpOn(System.err);
        System.exit(1);
    }

    BlobStore blobStore = null;
    String fdsPath = fdsPathSpec.value(options);
    if (!"".equals(fdsPath)) {
        File fdsDir = new File(fdsPath);
        if (fdsDir.exists()) {
            FileDataStore fds = new FileDataStore();
            fds.setPath(fdsDir.getAbsolutePath());
            fds.init(null);

            blobStore = new DataStoreBlobStore(fds);
        }
    }

    boolean readOnly = !options.has(readWrite);

    NodeStoreFixture fixture;
    if (nonOptions.get(0).startsWith(MongoURI.MONGODB_PREFIX)) {
        MongoClientURI uri = new MongoClientURI(nonOptions.get(0));
        if (uri.getDatabase() == null) {
            System.err.println("Database missing in MongoDB URI: " + uri.getURI());
            System.exit(1);
        }
        MongoConnection mongo = new MongoConnection(uri.getURI());

        DocumentMK.Builder builder = new DocumentMK.Builder().setBlobStore(blobStore).setMongoDB(mongo.getDB())
                .setClusterId(clusterId.value(options));
        if (readOnly) {
            builder.setReadOnlyMode();
        }
        DocumentNodeStore store = builder.getNodeStore();
        fixture = new MongoFixture(store);
    } else if (nonOptions.get(0).startsWith("jdbc")) {
        DataSource ds = RDBDataSourceFactory.forJdbcUrl(nonOptions.get(0), rdbjdbcuser.value(options),
                rdbjdbcpasswd.value(options));
        DocumentMK.Builder builder = new DocumentMK.Builder().setBlobStore(blobStore).setRDBConnection(ds)
                .setClusterId(clusterId.value(options));
        if (readOnly) {
            builder.setReadOnlyMode();
        }
        DocumentNodeStore store = builder.getNodeStore();
        fixture = new MongoFixture(store);
    } else if (options.has(segmentTar)) {
        fixture = SegmentTarFixture.create(new File(nonOptions.get(0)), readOnly, blobStore);
    } else {
        FileStore.Builder fsBuilder = FileStore.builder(new File(nonOptions.get(0))).withMaxFileSize(256);
        if (blobStore != null) {
            fsBuilder.withBlobStore(blobStore);
        }
        FileStore store;
        if (readOnly) {
            store = fsBuilder.buildReadOnly();
        } else {
            store = fsBuilder.build();
        }
        fixture = new SegmentFixture(store);
    }

    List<String> scriptArgs = nonOptions.size() > 1 ? nonOptions.subList(1, nonOptions.size())
            : Collections.<String>emptyList();
    IO io = new IO();

    if (options.has(quiet)) {
        io.setVerbosity(IO.Verbosity.QUIET);
    }

    if (readOnly) {
        io.out.println("Repository connected in read-only mode. Use '--read-write' for write operations");
    }

    GroovyConsole console = new GroovyConsole(ConsoleSession.create(fixture.getStore()), new IO(), fixture);

    int code = 0;
    if (!scriptArgs.isEmpty()) {
        code = console.execute(scriptArgs);
    }

    if (scriptArgs.isEmpty() || options.has(shell)) {
        code = console.run();
    }

    System.exit(code);
}

From source file:org.apache.jackrabbit.oak.plugins.tika.TextExtractorMain.java

License:Apache License

private static NodeStore bootStrapNodeStore(String src, boolean segmentTar, BlobStore blobStore, Closer closer)
        throws IOException {
    if (src.startsWith(MongoURI.MONGODB_PREFIX)) {
        MongoClientURI uri = new MongoClientURI(src);
        if (uri.getDatabase() == null) {
            System.err.println("Database missing in MongoDB URI: " + uri.getURI());
            System.exit(1);//from   w  w w.  j ava2s.c  o  m
        }
        MongoConnection mongo = new MongoConnection(uri.getURI());
        closer.register(asCloseable(mongo));
        DocumentNodeStore store = new DocumentMK.Builder().setBlobStore(blobStore).setMongoDB(mongo.getDB())
                .getNodeStore();
        closer.register(asCloseable(store));
        return store;
    }

    if (segmentTar) {
        return SegmentTarUtils.bootstrap(src, blobStore, closer);
    }

    return SegmentUtils.bootstrap(src, blobStore, closer);
}

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(//  w  ww .  jav  a 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);
    }
}