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:org.apache.jackrabbit.oak.run.DataStoreCheckCommand.java

License:Apache License

@Override
public void execute(String... args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();//  ww w.j  a  v  a 2  s .  co m

    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);//from www.ja  va 2  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();
    }

}

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

License:Apache License

public static NodeStore bootstrapNodeStore(String[] args, Closer closer, String h) throws IOException {
    //TODO add support for other NodeStore flags
    OptionParser parser = new OptionParser();
    OptionSpec<Integer> clusterId = parser.accepts("clusterId", "MongoMK clusterId").withRequiredArg()
            .ofType(Integer.class).defaultsTo(0);
    OptionSpec segmentTar = parser.accepts("segment-tar", "Use oak-segment-tar instead of oak-segment");
    OptionSpec<?> help = parser.acceptsAll(asList("h", "?", "help"), "show help").forHelp();
    OptionSpec<String> nonOption = parser.nonOptions(h);

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

    if (options.has(help)) {
        parser.printHelpOn(System.out);
        System.exit(0);//from  w w  w. j a v  a2 s . c om
    }

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

    String src = nonOptions.get(0);
    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);
        }
        MongoConnection mongo = new MongoConnection(uri.getURI());
        closer.register(asCloseable(mongo));
        DocumentNodeStore store = new DocumentMK.Builder().setMongoDB(mongo.getDB()).setLeaseCheck(false)
                .setClusterId(clusterId.value(options)).getNodeStore();
        closer.register(asCloseable(store));
        return store;
    }

    if (options.has(segmentTar)) {
        return SegmentTarUtils.bootstrapNodeStore(src, closer);
    }

    return SegmentUtils.bootstrapNodeStore(src, closer);
}

From source file:org.apache.jackrabbit.oak.upgrade.cli.container.MongoNodeStoreContainer.java

License:Apache License

@Override
public void clean() throws IOException {
    MongoClientURI uri = new MongoClientURI(mongoUri);
    MongoClient client = new MongoClient(uri);
    client.dropDatabase(uri.getDatabase());
    blob.clean();// w  ww  .j  a  va  2s.c o  m
}

From source file:org.apache.storm.mongodb.common.MongoDBClient.java

License:Apache License

public MongoDBClient(String url, String collectionName) {
    //Creates a MongoURI from the given string.
    MongoClientURI uri = new MongoClientURI(url);
    //Creates a MongoClient described by a URI.
    this.client = new MongoClient(uri);
    //Gets a Database.
    MongoDatabase db = client.getDatabase(uri.getDatabase());
    //Gets a collection.
    this.collection = db.getCollection(collectionName);
}

From source file:org.basex.modules.MongoDB.java

License:BSD License

/**
 * Mongodb connection with options.//from  w  w w  .ja va2s  .c  o m
 * @param url
 * @param options
 * @return
 * @throws QueryException
 */
public Str connection(final Str url, final Map options) throws QueryException {
    MongoClientURI uri = new MongoClientURI(url.toJava());
    String handler = "mongoClient" + mongoClients.size();
    try {
        MongoClient mongoClient = new MongoClient(uri);
        mongoClients.put(handler, mongoClient);
        return mongoConnect(handler, uri.getDatabase(), uri.getUsername(), uri.getPassword(), options);
    } catch (final MongoException ex) {
        throw MongoDBErrors.mongoExceptionError(ex);
    } catch (UnknownHostException ex) {
        throw MongoDBErrors.generalExceptionError(ex);
    }
}

From source file:org.basex.modules.nosql.MongoDB.java

License:BSD License

/**
 * Mongodb connection with options./*ww w  . ja  va  2s.  c om*/
 * @param url mongodb url like: "mongodb://127.0.0.1:27017/basex"
 * @param options nosql options
 * @return Str
 * @throws QueryException query exception
 */
public Str connect(final Str url, final Map options) throws QueryException {
    MongoClientURI uri = new MongoClientURI(url.toJava());
    String handler = "mongoClient" + mongoClients.size();
    try {
        MongoClient mongoClient = new MongoClient(uri);
        mongoClients.put(handler, mongoClient);
        return mongoConnect(handler, uri.getDatabase(), uri.getUsername(), uri.getPassword(), options);
    } catch (final MongoException ex) {
        throw MongoDBErrors.mongoExceptionError(ex);
    } catch (UnknownHostException ex) {
        throw MongoDBErrors.generalExceptionError(ex);
    }
}

From source file:org.craftercms.commons.mongo.MongoClientFromUriFactoryBean.java

License:Open Source License

@Override
protected MongoClient createInstance() throws Exception {
    final MongoClientURI client = new MongoClientURI(uri);
    logger.debug("Connecting to :" + client.getDatabase());
    return new MongoClient(client);
}

From source file:org.craftercms.commons.mongo.MongoScriptRunner.java

License:Open Source License

private List<String> getCommands(final Path scriptPath) throws MongoDataException {
    List<String> commandList = new ArrayList<>();
    if (SystemUtils.IS_OS_WINDOWS) {
        commandList.add("CMD");
        commandList.add("/C");
    }/*w w  w.  j  a v a2 s .  c om*/
    if (StringUtils.isBlank(mongoClientBin)) {
        throw new MongoDataException("Unable to run scripts, mongo client bin path is not set ");
    }
    String pwd = null;
    String authSource = null;
    String user = null;
    MongoClientURI uri = new MongoClientURI(connectionStr);
    if (uri.getCredentials() != null) {
        authSource = uri.getCredentials().getSource();
        user = uri.getCredentials().getUserName();
        if (uri.getCredentials().getPassword() != null) {
            pwd = new String(uri.getCredentials().getPassword());
        }
    }
    String replicaSetName = "";
    if (uri.getHosts().size() > 1) {
        replicaSetName = uri.getOptions().getRequiredReplicaSetName() + "/";
    }
    final String host = StringUtils.trim(replicaSetName + StringUtils.join(uri.getHosts(), ","));
    commandList.add(mongoClientBin);
    commandList.add("--host");
    commandList.add(host);
    commandList.add(uri.getDatabase());
    if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(pwd) && StringUtils.isNotBlank(authSource)) {
        commandList.add("-u");
        commandList.add(user);
        commandList.add("-p");
        commandList.add(pwd);
        commandList.add("--authenticationDatabase");
        commandList.add(authSource);
    }
    commandList.add(scriptPath.toAbsolutePath().toString());
    return commandList;
}

From source file:org.culturegraph.mf.mongodb.common.SimpleMongoDBConnection.java

License:Apache License

/**
 * @param uri/*from  ww  w  .j  a v  a  2s .  c o  m*/
 *            monogdb://user:pass@host:port/database.collection?options...
 * @see MongoClientURI
 */
public SimpleMongoDBConnection(final String uri) throws UnknownHostException {
    final MongoClientURI mongoClientUri = new MongoClientURI(uri);
    mongoClient = new MongoClient(mongoClientUri);
    final DB db = mongoClient.getDB(mongoClientUri.getDatabase());
    dbCollection = db.getCollection(mongoClientUri.getCollection());
}