List of usage examples for com.mongodb MongoURI MONGODB_PREFIX
String MONGODB_PREFIX
To view the source code for com.mongodb MongoURI MONGODB_PREFIX.
Click Source Link
From source file:com.arquivolivre.mongocom.management.CollectionManagerFactory.java
License:Apache License
/** * Create an instance of <code>Mongo</code> based on the information * provided in the configuration files located into <code>WEB-INF/conf</code>, if the instance has already been * created using the same information, so it uses the same instance. * * @param context <code>ServletContext</code> of a web application. * @return an instance of a <code>CollectionManager</code>. *//*ww w .j av a 2 s . c o m*/ public static CollectionManager setup(ServletContext context) { try { File props = getPropertiesFile(context); if (props == null) { throw new FileNotFoundException("application or database configuration file not found."); } InputStream in = new FileInputStream(props); Properties properties = new Properties(); properties.load(in); StringBuilder builder = new StringBuilder(); builder.append(MongoURI.MONGODB_PREFIX); String user, password, host, port, dbName; user = properties.containsKey("mongocom.user") ? properties.getProperty("mongocom.user") : ""; password = properties.containsKey("mongocom.password") ? properties.getProperty("mongocom.password") : ""; host = properties.containsKey("mongocom.host") ? properties.getProperty("mongocom.host") : ""; port = properties.containsKey("mongocom.port") ? properties.getProperty("mongocom.port") : ""; dbName = properties.containsKey("mongocom.database") ? properties.getProperty("mongocom.database") : ""; if (!user.equals("")) { builder.append(user).append(":").append(password).append("@"); } if (host.equals("")) { builder.append("localhost"); } else { builder.append(host); } if (!port.equals("")) { builder.append(":"); builder.append(port); } builder.append("/"); if (!dbName.equals("")) { builder.append(dbName); } LOG.log(Level.INFO, "Mongo URI: {0}", builder.toString()); MongoURI uri = new MongoURI(builder.toString()); client = MongoClient.Holder.singleton().connect(uri); return new CollectionManager(client, dbName); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } return null; }
From source file:com.edgytech.umongo.MainMenu.java
License:Apache License
public void connect() { try {/*from www . j a va 2 s . c o m*/ ConnectDialog dialog = (ConnectDialog) getBoundUnit(Item.connectDialog); ProgressDialog progress = (ProgressDialog) getBoundUnit(Item.connectProgressDialog); MongoClient mongo = null; List<String> dbs = new ArrayList<String>(); String uri = dialog.getStringFieldValue(ConnectDialog.Item.uri); if (!uri.trim().isEmpty()) { if (!uri.startsWith(MongoURI.MONGODB_PREFIX)) { uri = MongoURI.MONGODB_PREFIX + uri; } MongoClientURI muri = new MongoClientURI(uri); mongo = new MongoClient(muri); String db = muri.getDatabase(); if (db != null && !db.trim().isEmpty()) { dbs.add(db.trim()); } } else { String servers = dialog.getStringFieldValue(ConnectDialog.Item.servers); if (servers.trim().isEmpty()) { return; } String[] serverList = servers.split(","); ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>(); for (String server : serverList) { String[] tmp = server.split(":"); if (tmp.length > 1) { addrs.add(new ServerAddress(tmp[0], Integer.valueOf(tmp[1]).intValue())); } else { addrs.add(new ServerAddress(tmp[0])); } } if ("Direct".equals(dialog.getStringFieldValue(ConnectDialog.Item.connectionMode))) mongo = new MongoClient(addrs.get(0), dialog.getMongoClientOptions()); else mongo = new MongoClient(addrs, dialog.getMongoClientOptions()); String sdbs = dialog.getStringFieldValue(ConnectDialog.Item.databases); if (!sdbs.trim().isEmpty()) { for (String db : sdbs.split(",")) { dbs.add(db.trim()); } } } if (dbs.size() == 0) { dbs = null; } String user = dialog.getStringFieldValue(ConnectDialog.Item.user).trim(); String password = dialog.getStringFieldValue(ConnectDialog.Item.password); if (!user.isEmpty()) { // authenticate against all dbs if (dbs != null) { for (String db : dbs) { mongo.getDB(db).authenticate(user, password.toCharArray()); } } else { mongo.getDB("admin").authenticate(user, password.toCharArray()); } } final MongoClient fmongo = mongo; final List<String> fdbs = dbs; // doing in background can mean concurrent modification, but dialog is modal so unlikely progress.show(new ProgressDialogWorker(progress) { @Override protected void finished() { } @Override protected Object doInBackground() throws Exception { UMongo.instance.addMongoClient(fmongo, fdbs); return null; } }); } catch (Exception ex) { UMongo.instance.showError(id, ex); } }
From source file:com.zjy.mongo.splitter.MongoCollectionSplitter.java
License:Apache License
/** * Takes an existing {@link MongoClientURI} and returns a new modified URI which replaces the original's server host + port with a * supplied new server host + port, but maintaining all the same original options. This is useful for generating distinct URIs for each * mongos instance so that large batch reads can all target them separately, distributing the load more evenly. It can also be used to * force a block of data to be read directly from the shard's servers directly, bypassing mongos entirely. * * @param originalUri the URI to rewrite * @param newServerUri the new host(s) to target, e.g. server1:port1[,server2:port2,...] * @return the rewritten URI/* w w w.ja v a 2 s .c o m*/ */ protected static MongoClientURI rewriteURI(final MongoClientURI originalUri, final String newServerUri) { String originalUriString = originalUri.toString(); originalUriString = originalUriString.substring(MongoURI.MONGODB_PREFIX.length()); // uris look like: mongodb://fred:foobar@server1[,server2]/path?options // //Locate the last character of the original hostname int serverEnd; int idx = originalUriString.lastIndexOf("/"); serverEnd = idx < 0 ? originalUriString.length() : idx; //Locate the first character of the original hostname idx = originalUriString.indexOf("@"); int serverStart = idx > 0 ? idx + 1 : 0; StringBuilder sb = new StringBuilder(originalUriString); sb.replace(serverStart, serverEnd, newServerUri); return new MongoClientURI(MongoURI.MONGODB_PREFIX + sb); }
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);/* www .j a va2 s . 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. c om*/ } 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(/*from www .j a v a 2s. c o 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();/*from w ww.j av a 2s . 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 ww. j a va 2s.co 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);//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.eclipse.birt.data.oda.mongodb.impl.MongoDBDriver.java
License:Open Source License
@SuppressWarnings("unused") private static String formatMongoURI(Properties connProps) { // format a Mongo URI text from supported connection properties // Mongo URI syntax: // mongodb://[username:password@]host1[:port1]...[,hostN[:portN]][/[database][?options]] // validate that the mininum required URI part exists String serverHost = getStringPropValue(connProps, SERVER_HOST_PROP); if (serverHost == null || serverHost.isEmpty()) throw new IllegalArgumentException(Messages.mDbDriver_missingValueServerHost); StringBuffer buf = new StringBuffer(MongoURI.MONGODB_PREFIX); String username = getUserName(connProps); if (username != null && !username.isEmpty()) { String passwd = getPassword(connProps); buf.append(username);/* www . j av a2s . c om*/ buf.append(':'); buf.append(passwd); buf.append('@'); } buf.append(serverHost); Integer serverPort = getIntegerPropValue(connProps, SERVER_PORT_PROP); if (serverPort != null) { buf.append(':'); buf.append(serverPort); } String dbName = getStringPropValue(connProps, DBNAME_PROP); if (dbName != null) { buf.append('/'); buf.append(dbName); } // comment out inclusion of all options in the generated URI text, cuz // the MongoURI parser does not yet support all the options allowed in MongoOptions /* MongoOptions options = createMongoOptions( connProps ); if( options != null ) { // if database is absent, a '/' is still required if( dbName == null ) buf.append( '/' ); buf.append( '?' ); String optionsText = options.toString(); // replace the option separator ',' with ';' as required in MongoURI optionsText = optionsText.replace( ',', ';' ); buf.append( optionsText ); } */ return buf.toString(); }