2

I've got a running Java, Scala web-application running on a server. How do I make a cli interface for accessing/querying the running application? At the mininum I only need to call the running application's method and retrieve a string that it returns, all from the command line. How would I do that?

Note: Apache Thrift seems to relate to my problem, but it feels like an overkill. I'd love to just write a bash script or a small java program, that could 'hook' into the already running application.

Dominykas Mostauskis
  • 7,797
  • 3
  • 48
  • 67
  • What for? Debugging? If yes, use jdb. Ow I can't really see any reasonable causes and the method most probably depends on the internal state of the program, unless its totally invariant. – zeller Sep 05 '13 at 09:56
  • @zeller, yes, debugging and maintenace. The interface-to-be is only for the server admin. Method to call depends and alters program's state. – Dominykas Mostauskis Sep 05 '13 at 09:58
  • Sorry.. I din't get the proper question at first – TechSpellBound Sep 06 '13 at 09:44

2 Answers2

2

Use JMX

Considering your requirements, the easiest solution is most likely to use JMX. It's exactly what it's made for, as it's the Java Management eXtensions API.

You can find a nicely detailed tutorial trail in the Java Tutorial. It's relatively simple. Your Java program will listen for connections from JMX clients, and allow you to query your own Management Beans (MBean).

Administrators would then be able to use a JMX compatible client (for instance jconsole) or a custom client. See here for a custom JMX client example.

Another good - though somewhat ancient now - tutorial is Getting Started with MBeans.


If what you want is to intercept the return value of a particular function, not to create your own extension points for monitoring and administration, then you're more likely to want to use a debugger.

Also, you may be interested in these SO questions:

Community
  • 1
  • 1
haylem
  • 22,460
  • 3
  • 67
  • 96
1

Your program can use the attach API to locate the running JVM and connect to it.

http://docs.oracle.com/javase/7/docs/jdk/api/attach/spec/

Then you can tell it to load an agent into the JVM. See the java.lang.instrument package description, chapter “Starting Agents After VM Startup” to see how such an agent can be implemented.

This agent can call the desired method in the target JVM. Note that there already exists the JMX agent for a lot of operations you might want to perform when dealing with managing another application. It’s worth studying it.

Holger
  • 285,553
  • 42
  • 434
  • 765