@ 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 ) ; } }
init database with demo data