Search in sources :

Example 86 with MongoClient

use of com.mongodb.MongoClient in project jackrabbit-oak by apache.

the class MongoNodeStoreContainer method testMongoAvailability.

private static boolean testMongoAvailability() {
    Mongo mongo = null;
    try {
        MongoClientURI uri = new MongoClientURI(MONGO_URI + "?connectTimeoutMS=3000");
        mongo = new MongoClient(uri);
        mongo.getDatabaseNames();
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}
Also used : MongoClient(com.mongodb.MongoClient) Mongo(com.mongodb.Mongo) MongoClientURI(com.mongodb.MongoClientURI) IOException(java.io.IOException)

Example 87 with MongoClient

use of com.mongodb.MongoClient in project jackrabbit-oak by apache.

the class MongoFactory method getDB.

private DB getDB(Closer closer) throws UnknownHostException {
    String db;
    if (uri.getDatabase() == null) {
        // assume an author instance
        db = "aem-author";
    } else {
        db = uri.getDatabase();
    }
    MongoClient client = new MongoClient(uri);
    closer.register(asCloseable(client));
    return client.getDB(db);
}
Also used : MongoClient(com.mongodb.MongoClient)

Example 88 with MongoClient

use of com.mongodb.MongoClient in project logging-log4j2 by apache.

the class MongoDbProvider method createNoSqlProvider.

/**
     * Factory method for creating a MongoDB provider within the plugin manager.
     *
     * @param collectionName The name of the MongoDB collection to which log events should be written.
     * @param writeConcernConstant The {@link WriteConcern} constant to control writing details, defaults to
     *                             {@link WriteConcern#ACKNOWLEDGED}.
     * @param writeConcernConstantClassName The name of a class containing the aforementioned static WriteConcern
     *                                      constant. Defaults to {@link WriteConcern}.
     * @param databaseName The name of the MongoDB database containing the collection to which log events should be
     *                     written. Mutually exclusive with {@code factoryClassName&factoryMethodName!=null}.
     * @param server The host name of the MongoDB server, defaults to localhost and mutually exclusive with
     *               {@code factoryClassName&factoryMethodName!=null}.
     * @param port The port the MongoDB server is listening on, defaults to the default MongoDB port and mutually
     *             exclusive with {@code factoryClassName&factoryMethodName!=null}.
     * @param userName The username to authenticate against the MongoDB server with.
     * @param password The password to authenticate against the MongoDB server with.
     * @param factoryClassName A fully qualified class name containing a static factory method capable of returning a
     *                         {@link DB} or a {@link MongoClient}.
     * @param factoryMethodName The name of the public static factory method belonging to the aforementioned factory
     *                          class.
     * @return a new MongoDB provider.
     */
@PluginFactory
public static MongoDbProvider createNoSqlProvider(@PluginAttribute("collectionName") final String collectionName, @PluginAttribute("writeConcernConstant") final String writeConcernConstant, @PluginAttribute("writeConcernConstantClass") final String writeConcernConstantClassName, @PluginAttribute("databaseName") final String databaseName, @PluginAttribute(value = "server", defaultString = "localhost") @ValidHost final String server, @PluginAttribute(value = "port", defaultString = "" + DEFAULT_PORT) @ValidPort final String port, @PluginAttribute("userName") final String userName, @PluginAttribute(value = "password", sensitive = true) final String password, @PluginAttribute("factoryClassName") final String factoryClassName, @PluginAttribute("factoryMethodName") final String factoryMethodName) {
    DB database;
    String description;
    if (Strings.isNotEmpty(factoryClassName) && Strings.isNotEmpty(factoryMethodName)) {
        try {
            final Class<?> factoryClass = LoaderUtil.loadClass(factoryClassName);
            final Method method = factoryClass.getMethod(factoryMethodName);
            final Object object = method.invoke(null);
            if (object instanceof DB) {
                database = (DB) object;
            } else if (object instanceof MongoClient) {
                if (Strings.isNotEmpty(databaseName)) {
                    database = ((MongoClient) object).getDB(databaseName);
                } else {
                    LOGGER.error("The factory method [{}.{}()] returned a MongoClient so the database name is " + "required.", factoryClassName, factoryMethodName);
                    return null;
                }
            } else if (object == null) {
                LOGGER.error("The factory method [{}.{}()] returned null.", factoryClassName, factoryMethodName);
                return null;
            } else {
                LOGGER.error("The factory method [{}.{}()] returned an unsupported type [{}].", factoryClassName, factoryMethodName, object.getClass().getName());
                return null;
            }
            description = "database=" + database.getName();
            final List<ServerAddress> addresses = database.getMongo().getAllAddress();
            if (addresses.size() == 1) {
                description += ", server=" + addresses.get(0).getHost() + ", port=" + addresses.get(0).getPort();
            } else {
                description += ", servers=[";
                for (final ServerAddress address : addresses) {
                    description += " { " + address.getHost() + ", " + address.getPort() + " } ";
                }
                description += "]";
            }
        } catch (final ClassNotFoundException e) {
            LOGGER.error("The factory class [{}] could not be loaded.", factoryClassName, e);
            return null;
        } catch (final NoSuchMethodException e) {
            LOGGER.error("The factory class [{}] does not have a no-arg method named [{}].", factoryClassName, factoryMethodName, e);
            return null;
        } catch (final Exception e) {
            LOGGER.error("The factory method [{}.{}()] could not be invoked.", factoryClassName, factoryMethodName, e);
            return null;
        }
    } else if (Strings.isNotEmpty(databaseName)) {
        final List<MongoCredential> credentials = new ArrayList<>();
        description = "database=" + databaseName;
        if (Strings.isNotEmpty(userName) && Strings.isNotEmpty(password)) {
            description += ", username=" + userName + ", passwordHash=" + NameUtil.md5(password + MongoDbProvider.class.getName());
            credentials.add(MongoCredential.createCredential(userName, databaseName, password.toCharArray()));
        }
        try {
            final int portInt = TypeConverters.convert(port, int.class, DEFAULT_PORT);
            description += ", server=" + server + ", port=" + portInt;
            database = new MongoClient(new ServerAddress(server, portInt), credentials).getDB(databaseName);
        } catch (final Exception e) {
            LOGGER.error("Failed to obtain a database instance from the MongoClient at server [{}] and " + "port [{}].", server, port);
            return null;
        }
    } else {
        LOGGER.error("No factory method was provided so the database name is required.");
        return null;
    }
    try {
        // Check if the database actually requires authentication
        database.getCollectionNames();
    } catch (final Exception e) {
        LOGGER.error("The database is not up, or you are not authenticated, try supplying a username and password to the MongoDB provider.", e);
        return null;
    }
    final WriteConcern writeConcern = toWriteConcern(writeConcernConstant, writeConcernConstantClassName);
    return new MongoDbProvider(database, writeConcern, collectionName, description);
}
Also used : ServerAddress(com.mongodb.ServerAddress) Method(java.lang.reflect.Method) MongoClient(com.mongodb.MongoClient) WriteConcern(com.mongodb.WriteConcern) ArrayList(java.util.ArrayList) List(java.util.List) DB(com.mongodb.DB) PluginFactory(org.apache.logging.log4j.core.config.plugins.PluginFactory)

Example 89 with MongoClient

use of com.mongodb.MongoClient in project jackrabbit-oak by apache.

the class ResetClusterIdCommand method execute.

@Override
public void execute(String... args) throws Exception {
    OptionParser parser = new OptionParser();
    OptionSet options = parser.parse(args);
    if (options.nonOptionArguments().isEmpty()) {
        System.out.println("usage: resetclusterid {<path>|<mongo-uri>}");
        System.exit(1);
    }
    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 {
            store = SegmentTarUtils.bootstrapNodeStore(source, closer);
        }
        deleteClusterId(store);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}
Also used : Closer(com.google.common.io.Closer) MongoClient(com.mongodb.MongoClient) DocumentNodeStore(org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore) NodeStore(org.apache.jackrabbit.oak.spi.state.NodeStore) MongoClientURI(com.mongodb.MongoClientURI) NodeBuilder(org.apache.jackrabbit.oak.spi.state.NodeBuilder) DocumentNodeStore(org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore) OptionSet(joptsimple.OptionSet) OptionParser(joptsimple.OptionParser)

Example 90 with MongoClient

use of com.mongodb.MongoClient in project jackrabbit-oak by apache.

the class CheckpointsCommand method execute.

@Override
public void execute(String... args) throws Exception {
    OptionParser parser = new OptionParser();
    OptionSet options = parser.parse(args);
    if (options.nonOptionArguments().isEmpty()) {
        System.out.println("usage: checkpoints {<path>|<mongo-uri>} [list|rm-all|rm-unreferenced|rm <checkpoint>|info <checkpoint>|set <checkpoint> <name> [<value>]] [--segment]");
        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) && !"info".equals(op) && !"set".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 {
            cps = Checkpoints.onSegmentTar(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.");
                }
            }
        } else if ("info".equals(op)) {
            if (options.nonOptionArguments().size() < 3) {
                failWith("Missing checkpoint id");
            } else {
                String cp = options.nonOptionArguments().get(2).toString();
                Map<String, String> info = cps.getInfo(cp);
                if (info != null) {
                    for (Map.Entry<String, String> e : info.entrySet()) {
                        System.out.println(e.getKey() + '\t' + e.getValue());
                    }
                } else {
                    failWith("Checkpoint '" + cp + "' not found.");
                }
            }
        } else if ("set".equals(op)) {
            if (options.nonOptionArguments().size() < 4) {
                failWith("Missing checkpoint id");
            } else {
                List<?> l = options.nonOptionArguments();
                String cp = l.get(2).toString();
                String name = l.get(3).toString();
                String value = null;
                if (l.size() >= 5) {
                    value = l.get(4).toString();
                }
                long time = System.currentTimeMillis();
                int cnt = cps.setInfoProperty(cp, name, value);
                time = System.currentTimeMillis() - time;
                if (cnt != 0) {
                    if (cnt == 1) {
                        System.out.println("Updated 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);
    }
}
Also used : Closer(com.google.common.io.Closer) Checkpoints(org.apache.jackrabbit.oak.checkpoint.Checkpoints) MongoClientURI(com.mongodb.MongoClientURI) DocumentNodeStore(org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore) OptionParser(joptsimple.OptionParser) Timestamp(java.sql.Timestamp) MongoClient(com.mongodb.MongoClient) List(java.util.List) OptionSet(joptsimple.OptionSet) File(java.io.File) Map(java.util.Map)

Aggregations

MongoClient (com.mongodb.MongoClient)126 Test (org.junit.Test)31 MongoClientURI (com.mongodb.MongoClientURI)29 Document (org.bson.Document)26 ServerAddress (com.mongodb.ServerAddress)21 MongoDatabase (com.mongodb.client.MongoDatabase)21 Before (org.junit.Before)20 BasicDBObject (com.mongodb.BasicDBObject)11 ArrayList (java.util.ArrayList)11 MongoCredential (com.mongodb.MongoCredential)9 MongoException (com.mongodb.MongoException)8 DB (com.mongodb.DB)7 DBCollection (com.mongodb.DBCollection)7 UnknownHostException (java.net.UnknownHostException)7 MongoTemplate (org.springframework.data.mongodb.core.MongoTemplate)7 DBObject (com.mongodb.DBObject)6 MongoClientOptions (com.mongodb.MongoClientOptions)6 IOException (java.io.IOException)5 List (java.util.List)5 MongoDbFactory (org.springframework.data.mongodb.MongoDbFactory)5