1
votes

I am working on a small Java program that parses .txt files using MongoDB and displays the information nicely for analysis. So far I have had to open up cmd on windows and run the line "mongod" to start the database (I have Mongo set up in my Windows environment variables so I do not have to path to the MongoDB installation). I can then run the Java program. To stop mongod I can either close the cmd window that I started it in or I can open another cmd window and issue the following series of commands: "mongo", "use admin", "db.shutdownServer()".

I would like to be able to automate the initialization and termination of mongod from within my Java program so that when I open the jar for the program the server will automatically be started and then stopped when the program is closed. I know where I need to insert the code that will execute these commands, I simply do not know how to code them.

So far this is what I have found:

Suggestions involving "Runtime.getRuntime().exec("");" - this does work for the first command "mongod" and I believe "mongo" as well, but not for "use admin". I am guessing this is either due to the commands being issued separately (while "mongo" "use admin" and "db.shutdownServer() need to be issued together, sequentially) or due to the spaces in the line "use admin". I have also read that this approach is quite crude and shouldn't be used.

Suggestions involving "ProcessBuilder" - I do not really understand this approach. Also, all of the suggestions I have encountered for this approach do not mention having spaces in commands so that is something that would need to be figured out as well if this approach is to be taken.

Are there any other approaches, or how could I implement one of these two?

1
Look into process and process builder - efekctive

1 Answers

0
votes

p.isAlive() returns true. After destroyForcibly() killall mongod warns that no mongod exists

ProcessBuilder pb = new ProcessBuilder();
        pb.command("/XXXXX/mongo/bin/mongod", "--dbpath", "/XXXXX/mongo_data");
        Process p;
        try {
            p = pb.start();
            System.out.println(p.isAlive());
            p.destroyForcibly();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

EIDT

You can also redirect the standard streams to java streams if you want to manipulate them further.

You can pass to the builder all the options you need from:

https://docs.mongodb.com/manual/reference/program/mongo/