Example usage for com.mongodb MongoClientURI getURI

List of usage examples for com.mongodb MongoClientURI getURI

Introduction

In this page you can find the example usage for com.mongodb MongoClientURI getURI.

Prototype

public String getURI() 

Source Link

Document

Get the unparsed URI.

Usage

From source file:br.com.rbezerra.RegisterQueue.DAO.Session.java

public Session(MongoClientURI uri) {
    try {//  w  w  w  . j av a 2s  . c om
        client = new MongoClient(uri);
        db = client.getDB("registerqueue");
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException(uri.getURI());
    } catch (MongoException e) {
        throw new IllegalArgumentException(uri.getURI());
    }
}

From source file:com.github.nlloyd.hornofmongo.MongoRuntime.java

License:Open Source License

/**
 * Creates a newly initialized {@link MongoScope} instance with a connection
 * to the specified mongodb instance/cluster. This will use
 * {@link MongoRuntime#call(MongoAction)} to initialize the
 * {@link MongoScope} instance, possibly resulting in the global
 * {@link MongoContextFactory} being set.
 * //w ww.ja va  2 s  . com
 * After the scope is initialized a call via the mongo JS API to the
 * "connect()" method will be made to initialize the global db instance.
 * 
 * @return
 */
public static final MongoScope createMongoScope(final MongoClientURI mongoClientURI,
        boolean useMongoShellWriteConcern, boolean mimicShellExceptionBehavior) throws UnknownHostException {
    if (StringUtils.isBlank(mongoClientURI.getDatabase()))
        throw new IllegalArgumentException("mongo client uri must have a database");
    MongoScope mongoScope = createMongoScope();
    mongoScope.setUseMongoShellWriteConcern(useMongoShellWriteConcern);
    mongoScope.setStdoutMongoErrorMessages(mimicShellExceptionBehavior);

    StringBuilder connectStrBuilder = new StringBuilder("db = connect('");

    if ((mongoClientURI.getHosts().size() == 1) && (mongoClientURI.getHosts().get(0).equals("localhost")
            || mongoClientURI.getHosts().get(0).equals("localhost:27017")))
        connectStrBuilder.append(mongoClientURI.getDatabase());
    else
        connectStrBuilder.append(mongoClientURI.getURI());

    connectStrBuilder.append("', null, null);");

    call(new MongoScriptAction(mongoScope, "connect", connectStrBuilder.toString()));

    return mongoScope;
}

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.
 * /*from  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.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);/*from w w  w  .ja  va 2s  . c  o  m*/
    }

    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 av  a2 s  .  co  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.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  .  ja v a 2  s . com*/
    }

    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.jumlabs.jcr.oak.rpc.AppConfiguration.java

@Bean
public MongoConnection mongoConnection() {
    MongoClientURI uri = new MongoClientURI(
            "mongodb://" + connectionSettings.getMongoHost() + "/" + connectionSettings.getMongoDB());
    MongoConnection mongo = null;//from  w  ww  .jav a  2  s .  c o m
    try {
        mongo = new MongoConnection(uri.getURI());
    } catch (UnknownHostException ex) {
        logger.error(ex.getMessage(), ex);
    }
    return mongo;
}

From source file:org.netbeans.modules.mongodb.api.connections.ConnectionInfo.java

License:Open Source License

public void setMongoURI(MongoClientURI uri) {
    Parameters.notNull(PROPERTY_URI, uri);
    final MongoClientURI old = getMongoURI();
    if (!old.equals(uri)) {
        this.uri = uri.getURI();
        supp.firePropertyChange(PROPERTY_URI, old, uri);
    }//  w w  w . j  ava 2 s . com
}

From source file:org.netbeans.modules.mongodb.ConnectionInfo.java

License:Open Source License

public void setMongoURI(MongoClientURI uri) {
    Parameters.notNull(PREFS_KEY_URI, uri);
    final MongoClientURI old = getMongoURI();
    if (!old.equals(uri)) {
        node.put(PREFS_KEY_URI, uri.getURI());
        supp.firePropertyChange(PREFS_KEY_URI, old, uri);
    }//from  w  w  w. j a  v  a 2s .c  o  m
}

From source file:org.netbeans.modules.mongodb.properties.MongoClientURIPropertyEditor.java

License:Open Source License

@Override
public String getAsText() {
    final MongoClientURI uri = (MongoClientURI) getValue();
    return uri.getURI();
}