예제 #1
0
  /**
   * Creates a GridFS instance for the specified bucket in the given database. Set the preferred
   * WriteConcern on the give DB with DB.setWriteConcern
   *
   * @see com.mongodb.WriteConcern
   * @param db database to work with
   * @param bucket bucket to use in the given database
   * @throws MongoException
   */
  public GridFS(DB db, String bucket) {
    _db = db;
    _bucketName = bucket;

    _filesCollection = _db.getCollection(_bucketName + ".files");
    _chunkCollection = _db.getCollection(_bucketName + ".chunks");

    // ensure standard indexes as long as collections are small
    try {
      if (_filesCollection.count() < 1000) {
        _filesCollection.ensureIndex(
            BasicDBObjectBuilder.start().add("filename", 1).add("uploadDate", 1).get());
      }
      if (_chunkCollection.count() < 1000) {
        _chunkCollection.ensureIndex(
            BasicDBObjectBuilder.start().add("files_id", 1).add("n", 1).get(),
            BasicDBObjectBuilder.start().add("unique", true).get());
      }
    } catch (MongoException e) {
      LOGGER.info(
          String.format(
              "Unable to ensure indices on GridFS collections in database %s", db.getName()));
    }
    _filesCollection.setObjectClass(GridFSDBFile.class);
  }
예제 #2
0
 public MongoConnection(DB db) {
   this.db = db;
   // TODO proper initialisation of the connection info
   connectionInfo.setMajorVersion("" + Mongo.MAJOR_VERSION);
   connectionInfo.setMinorVersion("" + Mongo.MINOR_VERSION);
   connectionInfo.setDatabase(db.getName());
 }
예제 #3
0
  /**
   * Initialises the MongoDB connection using the Mongo object provided to the endpoint
   *
   * @throws CamelMongoDbException
   */
  public void initializeConnection() throws CamelMongoDbException {
    LOG.info("Initialising MongoDb endpoint: {}", this.toString());
    if (database == null || collection == null) {
      throw new CamelMongoDbException(
          "Missing required endpoint configuration: database and/or collection");
    }
    db = mongoConnection.getDB(database);
    if (db == null) {
      throw new CamelMongoDbException(
          "Could not initialise MongoDbComponent. Database " + database + " does not exist.");
    }
    if (!createCollection && !db.collectionExists(collection)) {
      throw new CamelMongoDbException(
          "Could not initialise MongoDbComponent. Collection "
              + collection
              + " and createCollection is false.");
    }
    dbCollection = db.getCollection(collection);

    LOG.info(
        "MongoDb component initialised and endpoint bound to MongoDB collection with the following paramters. Address list: {}, Db: {}, Collection: {}",
        new Object[] {
          mongoConnection.getAllAddress().toString(), db.getName(), dbCollection.getName()
        });
  }
예제 #4
0
  @Override
  protected void updateNode() {
    label = db.getName();

    if (stats != null) {
      label += " (" + stats.getInt("objects") + "/" + stats.getInt("dataSize") + ")";
    }

    //        if (db.isAuthenticated())
    //            addOverlay("overlay/unlock.png");
  }
  /** @see DATAMONGO-306 */
  @Test
  public void setsUpMongoDbFactoryUsingAMongoUriWithoutCredentials() {

    reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-uri-no-credentials.xml"));
    BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory");
    ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();

    assertThat(constructorArguments.getArgumentCount(), is(1));
    ValueHolder argument = constructorArguments.getArgumentValue(0, MongoURI.class);
    assertThat(argument, is(notNullValue()));

    MongoDbFactory dbFactory = factory.getBean("mongoDbFactory", MongoDbFactory.class);
    DB db = dbFactory.getDb();
    assertThat(db.getName(), is("database"));
  }
  private static void assertWriteConcern(
      ClassPathXmlApplicationContext ctx, WriteConcern expectedWriteConcern) {

    SimpleMongoDbFactory dbFactory = ctx.getBean("first", SimpleMongoDbFactory.class);
    DB db = dbFactory.getDb();
    assertThat(db.getName(), is("db"));

    WriteConcern configuredConcern =
        (WriteConcern) ReflectionTestUtils.getField(dbFactory, "writeConcern");

    MyWriteConcern myDbFactoryWriteConcern = new MyWriteConcern(configuredConcern);
    MyWriteConcern myDbWriteConcern = new MyWriteConcern(db.getWriteConcern());
    MyWriteConcern myExpectedWriteConcern = new MyWriteConcern(expectedWriteConcern);

    assertThat(myDbFactoryWriteConcern, is(myExpectedWriteConcern));
    assertThat(myDbWriteConcern, is(myExpectedWriteConcern));
    assertThat(myDbWriteConcern, is(myDbFactoryWriteConcern));
  }
 @AfterClass
 public void cleanUp() {
   // super.deleteRiver();
   logger.info("Drop database " + mongoDB.getName());
   mongoDB.dropDatabase();
 }
예제 #8
0
 @Test
 public void getDb() {
   DB db = template.getCollection().getDB();
   assertEquals("junit", db.getName());
 }
예제 #9
0
  /**
   * 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="******", 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 {
      database.getCollectionNames(); // Check if the database actually requires authentication
    } 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);
  }
예제 #10
0
 private synchronized Response findOne(DB db, String coll, DBObject q) throws IOException {
   OutMessage msg = OutMessage.query(db._mongo, 0, db.getName() + "." + coll, 0, -1, q, null);
   Response res = go(msg, db.getCollection(coll), null);
   return res;
 }
 private void cleanUp() {
   super.deleteRiver();
   logger.info("Drop database " + mongoDB.getName());
   mongoDB.dropDatabase();
 }