/*
Build a new MongoDB ObjectId
throw an exception from photon namespace instead of MongoDB
765905
static public function createObjectID($id=null)
    {
        if ($id === null) {
            return new \MongoDB\BSON\ObjectId;
        }

        try {
            return new \MongoDB\BSON\ObjectId($id);
        } catch(\MongoDB\Driver\Exception\InvalidArgumentException $e) {
        }

        throw new Exception('Invalid ObjectId');
    }
263430
public void updateObjectId(String objectId) {
        if (configForVM != null) {
            configForVM.withObjectId(objectId);
        } else {
            configForAppService.withObjectId(objectId);
        }
    }
1168318
protected MongoClient buildMongoClient() {
        String connectionString = getConnectionString();
        if (StringUtils.isBlank(connectionString)) {
            throw new IllegalStateException("MongoDB ConnectionString is not defined.");
        }
        MongoClient mc = MongoClients.create(connectionString);
        return mc;
    }
214938
MongoCollection<BsonDocument> getLocalCollection(final MongoNamespace namespace) {
    return getLocalCollection(
        namespace,
        BsonDocument.class,
        MongoClientSettings.getDefaultCodecRegistry());
  }
738203
function getCollection(key, collectionName, database, options, callback) {
    getDatabaseCached(database, options, getOrCreateCollection)

    function getOrCreateCollection(err, db) {
        if (err) {
            return callback(err)
        }

        // get the collection
        db.collection(collectionName, extend({
            safe: true
        }, options.collectionOptions), createIfNotExist)

        function createIfNotExist(err, collection) {
            // if not exist create it
            if (err && err.message.indexOf(" does not exist") !== -1) {
                return db.createCollection(collectionName, extend({
                    safe: true
                }, options.createCollectionOptions), returnCollection)
            }

            if (err) {
                return callback(err)
            }

            callback(null, collection)
        }
    }

    function returnCollection(err, col) {
        if (err) {
            return callback(err)
        }

        callback(null, col)
    }
}
1012156
function MongoDB(config) {
  
    var self = this;
    
    this.events = new EventEmitter();

    config = protos.extend({
      host: 'localhost',
      port: 27017,
      database: 'default',
      storage: null,
      username: '',
      password: '',
      safe: true
    }, config || {});
    
    if (typeof config.port != 'number') config.port = parseInt(config.port, 10);
    
    this.className = this.constructor.name;
    
    app.debug(util.format('Initializing MongoDB for %s:%s', config.host, config.port));
    
    /**
    
      config: {
        host: 'localhost',
        port: 27017,
        database: 'db_name',
        storage: 'redis'
      }

     */

    this.config = config;

    var reportError = function(err) {
      app.log(util.format("MongoDB [%s:%s] %s", config.host, config.port, err));
      self.client = null;
    }
    
    // Set db
    self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: config.safe});
    
    // Add async task
    app.addReadyTask();
    
    // Get client
    self.db.open(function(err, client) {
      
      if (err) {
        reportError(err);
      } else {
        
        // Set client
        self.client = client;
        
        // Set storage
        if (typeof config.storage == 'string') {
          self.storage = app.getResource('storages/' + config.storage);
        } else if (config.storage instanceof protos.lib.storage) {
          self.storage = config.storage;
        }
        
        // Authenticate
        if (config.username && config.password) {
          
          self.db.authenticate(config.username, config.password, function(err, success) {
            
            if (err) {
              
              var msg = util.format('MongoDB: unable to authenticate %s@%s', config.username, config.host);
              app.log(new Error(msg));
              throw err;
              
            } else {
              
              // Emit initialization event
              self.events.emit('init', self.db, self.client);
              
            }
            
          });
          
        } else {
          // Emit initialization event
          self.events.emit('init', self.db, self.client);
        }
        
      }
    });
    
    // Flush async task
    this.events.once('init', function() {
      app.flushReadyTask();
    });

    // Only set important properties enumerable
    protos.util.onlySetEnumerable(this, ['className', 'db']);
}
964929
@PostConstruct
    public void initDatabase() {
        MongoDBInit.LOGGER.info("initializing MongoDB");
        String dbName = System.getProperty("mongodb.name");
        if (dbName == null) {
            throw new RuntimeException("Missing database name; Set system property 'mongodb.name'");
        }
        MongoDatabase db = this.mongo.getDatabase(dbName);

        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:mongodb/*.ndjson");
            MongoDBInit.LOGGER.info("Scanning for collection data");
            for (Resource res : resources) {
                String filename = res.getFilename();
                String collection = filename.substring(0, filename.length() - 7);
                MongoDBInit.LOGGER.info("Found collection file: {}", collection);
                MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);
                try (Scanner scan = new Scanner(res.getInputStream(), "UTF-8")) {
                    int lines = 0;
                    while (scan.hasNextLine()) {
                        String json = scan.nextLine();
                        Object parse = JSON.parse(json);
                        if (parse instanceof DBObject) {
                            DBObject dbObject = (DBObject) parse;
                            dbCollection.insertOne(dbObject);
                        } else {
                            MongoDBInit.LOGGER.error("Invalid object found: {}", parse);
                            throw new RuntimeException("Invalid object");
                        }
                        lines++;
                    }
                    MongoDBInit.LOGGER.info("Imported {} objects into collection {}", lines, collection);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Error importing objects", e);
        }
    }
166515
function (connectionName, collectionName, obj, cb) {
        if (_.isObject(obj)) {
            try {
                var modelInstance = new this._model(obj);
                return cb(null, modelInstance);
            }
            catch (err) {
                return cb(err, null);
            }
        }
    }
1075454
public function build(): GetFileInfoRequest
	{
		$instance = new GetFileInfoRequest();
		if ($this->objectId === null) {
			throw new BuilderException('Property [objectId] is required.');
		}
		$instance->objectId = $this->objectId;
		return $instance;
	}
912642
function CreateConnection (backend) {

    backend.Debug (4, "MongoDB creating connection [%s]", backend.uid);
    MongoClient.connect(backend.uid, function (err, db) {
        if (err) {
            backend.Debug (0, "Fail to connect to MongoDB: %s err=[%s]", backend.uid, err)
        } else {
            backend.Debug (4, "Connected to MongoDB: %s", backend.uid)
            backend.base = db;
        }
    });
}
1139590
public static <T extends AVObject> T createWithoutData(Class<T> clazz, String objectId) throws AVException{
    try {
      T obj = clazz.newInstance();
      obj.setClassName(Transformer.getSubClassName(clazz));
      obj.setObjectId(objectId);
      return obj;
    } catch (Exception ex) {
      throw new AVException(ex);
    }
  }
1223046
function create(connections, dataSource, callback) {
  async.waterfall([
    function validateParams(cb) {

      //If it is a deploy, the JSON can contain an _id param
      if (connections.deploy) {
        return cb(undefined, dataSource);
      }

      //Otherwise, check that it is not there.
      validate(dataSource).hasno(CONSTANTS.DATA_SOURCE_ID, function(err) {
        if (err) {
          return cb(buildErrorResponse({error: new Error("Data Source ID Should Not Be Included When Creating A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
        }

        cb(undefined, dataSource);
      });
    },
    function validateNameNotUsed(dataSource, cb) {
      //Duplicate Names Are Not Allowed.
      var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);

      DataSource.count({name: dataSource.name}, function(err, numDuplicateDSs) {
        if (numDuplicateDSs && numDuplicateDSs > 0) {
          return cb({
            userDetail: "Invalid Data To Create A Data Source" ,
            systemDetail: "A Data Source With The Name " + dataSource.name + " Already Exists",
            code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
          });
        } else {
          return cb(err, dataSource);
        }
      });
    },
    function createDataSource(dataSourceJSON, cb) {
      dataSourceJSON = misc.sanitiseJSON(dataSourceJSON);

      var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
      var newDataSource = new DataSource(dataSourceJSON);

      newDataSource.save(function(err) {
        if (err) {
          return cb(buildErrorResponse({
            error: err,
            userDetail: "Invalid Data Source Creation Data.",
            systemDetail: err.errors,
            code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
          }));
        }

        newDataSource = processDataSourceResponse(newDataSource.toJSON());

        return cb(undefined, newDataSource);
      });

    }
  ], callback);
}
1033620
public function build(): GetHeapObjectIdRequest
	{
		$instance = new GetHeapObjectIdRequest();
		if ($this->objectId === null) {
			throw new BuilderException('Property [objectId] is required.');
		}
		$instance->objectId = $this->objectId;
		return $instance;
	}
469130
function initMongo(config, callback) {
  
  var self = this;
  
  // Set db
  self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: true});
  
  // Get client
  self.db.open(function(err, client) {
    if (err) throw err;
    else {
      self.client = client;
      client.collectionNames(function(err, names) {
        if (err) throw err;
        else {
          var name = config.database + '.' + config.collection;
          var exists = names.filter(function(col) {
            if (col.name == name) return col; 
          });
          
          // Collection options
          var opts = {capped: true, size: config.logSize};
          if (config.logLimit != null) opts.max = config.logLimit;
          
          if (exists.length === 0) {
            client.createCollection(config.collection, opts, function(err, collection) {
              if (err) throw err;
              else {
                self.collection = collection;
                callback.call(self);
              }
            });
          } else {
            // Get collection
            client.collection(config.collection, function(err, collection) {
              if (err) throw err;
              else {
                self.collection = collection;
                // Get collection options » Check if collection has already been capped
                collection.options(function(err, options) {
                  if (err) {
                    throw err;
                  } else {
                    // Check if collection's options match log requirements
                    var ready = (options.capped === true && options.size === opts.size);
                    if ('max' in opts) ready = (ready && options.max === opts.max);
                    if (!ready) {
                      // Convert collection to capped if it's not match log requirements
                      var cmd = {"convertToCapped": config.collection, size: opts.size};
                      if ('max' in opts) cmd.max = opts.max;
                      client.command(cmd, function(err) {
                        if (err) throw err;
                        else {
                          callback.call(self);
                        }
                      });
                    } else {
                      callback.call(self);
                    }
                  }
                });
              }
            });
          }
        }
      });
    }
  });
}
783183
@SuppressWarnings("nls")
    private void indexEntity(String type, String id, XContentBuilder sourceEntity, boolean refresh)
            throws StorageException {
        try {
            String json = sourceEntity.string();
            JestResult response = esClient.execute(new Index.Builder(json).refresh(refresh).index(getIndexName())
                    .setParameter(Parameters.OP_TYPE, "create").type(type).id(id).build());
            if (!response.isSucceeded()) {
                throw new StorageException("Failed to index document " + id + " of type " + type + ": " + response.getErrorMessage());
            }
        } catch (StorageException e) {
            throw e;
        } catch (Exception e) {
            throw new StorageException(e);
        }
    }
264200
public function build(): GetObjectByHeapObjectIdRequest
	{
		$instance = new GetObjectByHeapObjectIdRequest();
		if ($this->objectId === null) {
			throw new BuilderException('Property [objectId] is required.');
		}
		$instance->objectId = $this->objectId;
		$instance->objectGroup = $this->objectGroup;
		return $instance;
	}
212984
public function build(): RequestNodeRequest
	{
		$instance = new RequestNodeRequest();
		if ($this->objectId === null) {
			throw new BuilderException('Property [objectId] is required.');
		}
		$instance->objectId = $this->objectId;
		return $instance;
	}