I’ve been trying, for some time now, to create a local process that will act as a CLI for my server. The idea is similar to what Drush does for Drupal servers.
I haven’t created the CLI interface yet (will probably use a 3rd party code) but I wanted to share my solution to my biggest obstacle in the matter: Transferring messages between a local process to my running and active server without using REST services because they add security risk with some commands.
Note: This code is written in Scala but can be converted to Java
First we’ll need to create a servlet class that extends HttpServlet. The servlet class, for every GET request, will check if our thread (explained later) is open and if not tries to start it up. Note that we are using a try catch with the start method because if the state of the thread is TERMINATED isAlive will return true (I have no idea why).
I’m also implementing the destroy method to kill our thread if the servlet dies. I’m not sure what happens to running threads if the servlet dies but just in case…
Servlet.scala:
Our thread (CLIThread) is scala object extending the Thread class.
CLIThread has 2 methods, pool & shutdown, and both of them are passed to our Runnable implementation.
CLIRunnable is the Runnable implemented object that is passed to the Thread constructor.
CLIRunnable has a nulled ServerSocket (listener), Socket (socket) & InputStream (in), a true Boolean (keepAlive) and an empty String (_pool) as variables.
The run method:
The pool method:
The shutdown method:
CLIThread.scala
CLI.scala
CliAddr.scala
CliPort.scala