If you are building a Java program that requires the ability to execute native commands on the machine which require sudo it requires some additional considerations other than just writing the Java code.
The problem is that sudo, by default, requires a tty for executing sudo such that a password can entered. Even if you configure sudoers to grant NOPASSWD access to a specific command you will still get the following error
sudo: sorry, you must have a tty to run sudo
In my case, I was writing a set of integration tests in Java that needed to be able to start and stop a service to run a test.
I settled on adding an additional sudoers config file in /etc/sudoers.d. This ended up be the cleanest and most encapsulated change that did not then require any special considerations in the Java code.
The change simply involved adding a file with the following contents to /etc/sudoers.d which indicates that running sudo for the rchapin
user does NOT require a tty and then grants access to the specific commands.
Defaults:rchapin !requiretty
rchapin ALL=(root) NOPASSWD: /bin/systemctl stop rabbitmq-server.service
rchapin ALL=(root) NOPASSWD: /bin/systemctl start rabbitmq-server.service