Using monit with java - java

I am using the tool monit to start/stop a process. I have a java file as follows:
class test {
public void start()
{
//do something
}
public void stop()
{
//do something
}
}
I want to call the start func when a start command is issued from monit and vice versa. I cannot seem to find a good tutorial explaining what steps I need to take for executing the start and stop method. do I need to write a bash script? and monit will call the bash script which in turn calls the java method?

The entry point into a java program is the main method.
public static void main(String [] args)
{
// args carry the command line arguments.
}
In your case, you should create an instance of test and call start() method on that instance.
public static void main(String [] args)
{
test obj = new test();
obj.start();
}
Java's Runtime class provides an option to add a shutdown hook that gets called when the java program is being terminated. You write a simple thread class that has access to the test instance created in the main method above so that when the shutdown hook thread's run method is called, you delegate it to test instance's stop method.
Hope this helps.

Related

call a java method using runtime.exec()

In my java code there is class A that has the following line:
Process localProcess = Runtime.getRuntime().exec(myString);
where myString is user supplied input and is passed to exec() at runtime.
Also there is a public method doSomething() in class A.
Can I somehow invoke doSomething() (through reflection, jdwp etc.) using exec() at runtime ?
Starting a new JVM just to call a single method? First, that would be really slow. And second, it would be highly unnecessary!
Reflection is what you want I guess. Here's some sample code.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
Class<Main> c = Main.class; // First get the class
try {
Method method = c.getMethod("doSomething"); // get the method by its name
method.invoke(new Main()); // call it on a new instance of Main
} catch (NoSuchMethodException e) {
System.out.println("Method is not found"); // print something when the method is not found
}
}
public void doSomething() {
System.out.println("I have done something!");
}
}
That would mean starting a whole new JVM just to make a method call.
If you are already "within" class A; what prevents you from calling doSomething() directly? Probably: only your lack of skills. If so, then work on your skills; and don't go for the next best solution you heard somebody mention how things might be done!
In essence: a self-claimed geek should always understand each and any concept he is using in his programs. If you want to use reflection, then study what reflection is about.
And please note: letting your users pass in arbitrary strings to have them executed, is a huge security NO GO. You should have mentioned in your question that you want to do this on purpose; and that you are fully aware of the potential consequences of doing so!
EDIT; given your latest comments.
In this case, a solution could be as simple as:
A) you write a new class, like
public class Invoker {
public static void main(String[] args) {
A.doSomething();
or if doSomething isn't static, you will need
A someA = new A( ... however you can create instances of A
A.doSomething()
B) Compile that, and then you can simply send a command like
java -cp WHATEVER Invoker
into your existing application. Of course, you have to work out the details; like providing a valid classpath to that call to java (that classpath has to include the location where Invoker.class lives; and of course A.class; and all of the dependencies that A has).
But keep in mind: doSomething() is executed in the scope of a different JVM. That means that most likely, it will not at all affect class A in that JVM where you trigger the call to exec!

how to print "hello world" without MAIN method and also without using STATIC and FINAL key word in java

class a {
public static void main(String args[]) {
}
}
i want to print "hello world" without touch or use above code and also without use of static and final keyword......
What are the different ways to initiate code execution.
Use public static void main(String args[]) { ... }
Use your static class initializer static { ... }. Problem: You need to get the class to load first. Solution: attempt to start the main method, but that means you need to have at least an empty main. However - OP states we cannot use 'static'.
Use an instance initializer { ... }. Problem: How do you instantiate an instance. Solution: initialize a static field with a class instance. However - OP states we cannot use static fields.
So what is left. I assume that we can use the empty main posted by the OP. From there on we build up a 4th solution:
public enum Play {
PLAY;
{ System.out.println("Hello World!"); }
public static void main(String args[]) { }
}
This should fulfill the conditions:
we do not modify the static main method, although we need the empty body just to get the class loaded.
we do not use a static initializer, we use an instance initializer instead.
to instantiate, and get the instance initializer started, we use an enum. Enum's start the initializer for each instance, meaning for each of the enum constants.
Also note the output when you try to execute a class without a main:
$ java -classpath . Play
Error: Main method not found in class Play, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
So that leaves us also the clue that we potentially can use javafx.application.Application. I did not investigate this trail any further.
You can create a JavaFX application, which is usually for displaying a GUI, and use it to output hello, world to the console and immediately shut the JavaFX GUI system down. JavaFX applications are executed by a special launch path in the java launcher. JavaFX applications do not need a main, static and final keywords.
The following snippet is just for demo purposes, I wouldn't recommend writing a JavaFX application unless you actually wish to display a GUI.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
public class PlayApp extends Application {
#Override
public void start(Stage stage) {
System.out.println("hello, world");
Platform.exit();
}
}
// Totally useless code from the original question
// goes below the real app code and is just ignored
// and never used when the application runs.
class a {
public static void main(String args[]) {
}
}
You need to use Oracle Java 8+ to compile and execute the JavaFX application as below:
javac PlayApp.java
java PlayApp
The a class is in the PlayApp.java file only to meet the original poster's requirement from a comment:
it means the above code is fixed, you can't modify the above code but yes u can write anything to print "hello world" above or belove this code
Really, if you are writing a console application, just use a standard app format (with a static main method) instead:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Unrelated advice on asking questions
In future, if you post such questions, I suggest that you also supply the reason for the question and why the bizarre constraints are placed on solutions. Also, address concerns such as WorldEnder's first comment on your question: "is this a code challenge? If not.. why?"
You can't just print "hello world" without MAIN method and also without using STATIC and FINAL key word in java because the main method is a function required you don't have to apply any rocket science in that thing if u are using intelliJ IDEA or any other IDE anyways this is the code
public class Basics_Of_Java {
public static void main(String[] args) {
System.out.println("Hello world");
basics of java in 1st line is the name of the java file you may have another name.

Can we execute a program without main() method?

Can we execute a program without main method and how in java tell me any example. have you done that kind of example.
Yes, it's possible:
public class MyClass {
static {
Runnable r = new Runnable() {
public void run() {
// whatever you like
}
};
Thread t = new Thread(r)
t.start();
t.join();
}
}
Now you run java passing this class to the command. Java loads the class before attempting to run its main (which doesn't exist), but in loading the class, it fires the static block, which halts until the thread finishes.
If the thread finishes without exiting, java will complain there's no main method, but by that time the thread could have run anything for any duration.
You'll have to catch some exceptions in there, but it will work.
public class TestWithoutMain {
// static block executes first
static{
System.out.println("Program without main");
System.exit(0);
}
}
Note : This works well in JDK1.7 old versions(build 1.7.0-ea-b19)
from jdk 1.7(build1.7.0-ea-b85),It gives run time Exception
Yes, sequence is as follows:
jvm loads class
executes static blocks
looks for main method and invokes it
So, if there's code in a static block, it will be executed. But there's no point in doing that.
How to test that:
public final class Test {
static {
System.out.println("FOO");
}
}
Then if you try to run the class (either form command line with java Test or with an IDE), the result is:
Error will be this.
FOO
java.lang.NoSuchMethodError: main
and ans is that no you can not execute program without main method but the thing is that u can use it either way means partial.
and how ever you can achieve by using static block like this.
static{
System.out.println("Program without main executing into the environment.");
System.exit(0);
}
In Java 9 and beyond you can use JShell to execute Java code without requiring a main method. Not suitable for a stand alone application, but great for quickly testing your code and prototyping changes.
Unless its is web application, I don't think that is possible for any stand alone application which is being self executable, the Runtime should know the entry point, The runtime design such a way that main method is an entry point.

Java Command Line when daemon is running

We all know what the code below does
class Demo{
public static void main(String b[]){
System.out.println("Argument one = "+b[0]);
System.out.println("Argument two = "+b[1]);
}
}
My question (infact curiosity) is, if this application is a daemon that is running and java based server waiting for clients to do socket stuff with it, can I run the application again, and pass new parameters to it ? Basically I am looking at not implementing a cli kinda thing. I need it simple.
Edit : I want to change / add more parameters at runtime. But if I run the app with new parameters, wont it start another instance ?
No, you can't modify the arguments passed after the application started.
The array used to retreive the parameters is populated when it starts and cannot be altered.
If the application is a server, you should be able to implement a CLI rather easily with a simple thread waiting for input.
Seems like you have an existing application that is being run as a command line application right now. It is being invoked as and when required from command line passing the appropriate command line parameters. And now what you would like to do is host this same application as a daemon service which gets invoked as and when the parameters come over a port it is listening to.
Assuming your goal is the above and for whatever reason you want to retain the above main() signature, the key is to realize that the main() method is also like any other static method which can be invoked by a class reference. So the following is possible:
class SocketListener extends Thread {
public void run() {
// Code for listening to socket that calls invokeDemo()
// method below once it detects the appropriate args.
}
private void invokeDemo(String[] args) {
// You can invoke the main method as any other static method.
Demo.main(args);
}
}
This would just treat Demo class as part of a library it is using and not launch any other application. If you do want to launch it as an application (because of some special reason), you would need to use the Process and Runtime classes of java.

How to unit test a method that simply starts a thread with jUnit?

As in the title, I want to test a method like this:
public void startThread()
{
new Thread()
{
public void run()
{
myLongProcess();
}
}.start();
}
EDIT:
Judging by comments I guess it is not very common to test if a thread starts or not. So I've to adjust the question... if my requirement is 100% code coverage do I need to test if that thread starts or not? If so do I really need an external framework?
This can be done elegantly with Mockito. Assuming the class is named ThreadLauncher you can ensure the startThread() method resulted in a call of myLongProcess() with:
public void testStart() throws Exception {
// creates a decorator spying on the method calls of the real instance
ThreadLauncher launcher = Mockito.spy(new ThreadLauncher());
launcher.startThread();
Thread.sleep(500);
// verifies the myLongProcess() method was called
Mockito.verify(launcher).myLongProcess();
}
If you need 100% coverage, you will need to call startThread which will kick off a thread. I recommend doing some sort of verification that the thread was stared (by verifying that something in myLongProcess is happening, then clean up the thread. Then you would probably do the remainder of the testing for myLongProcess by invoking that method directly from your unit test.

Categories