Eclipse executing java application in a loop - java

Does enyone know if it is possible to launch a java application in Eclipse but in a loop.
I need to execute a application all the night.
If I try tu run it in win console, it is complicated, I have ti specify a bunch a parameters.

Wrap your main in a call to Runtime.exec and put that in a loop.
public static void main(String args[]){
while(true){
Process proc = Runtime.getRuntime().exec("java yourclasshere");
try{
proc.waitFor();
} catch (InterruptedException e) {}
}
}

Just run the way you would run a regular Java program, in a loop:
public class MyProgram {
public static void main(String[] args) {
// your infite, of finite loop goes here
}
}
And then, just run it, and if there are not unhandled exceptions, it will run all night indeed.

Eclipse is a development environment, not an application manager. It's not well suited for what you're asking to do. It might be best to learn what those parameters are and why you need them, and write a batch file to handle them for you. There might be a better answer if you provide more details.

Related

Regarding manual termination of the program in eclipse java?

public class Test {
public static void main(String[] args)
{
while(true) {
System.out.println("1 ");
}
}
}
What this code does is run for infinite till the program is terminated manually for example give the picture below.
What my requirement is when I manually terminate the execution
my output should be like below
1
1
1
Program terminated manually
thank you
The above 2 lines of output after I manually terminate the program.
Why I need this is I am storing the serializable objects in the file. My code flow is when I working on the program there will be a lot of modifications in the object at end of execution I serialize the updated object into the file. So when I terminate the program manually serialization of the updated object is not done. So I need Serialization should be done even at manual termination.
You can add a hook to the shutdown event:
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
//Do something here
}));
Edit: This doesn't work with eclipse, according to greg-449

How to return non-zero exit codes if Java file throws exceptions

I am using below script(.sh file) to run a java code in an UNIX system,but even if Java is giving exception or terminated successfully in both cases,
exit code coming as 0, I want to return non zero exit codes from script, if Java run throwing an exception, so that I can add if-then check in script,to print success or failure messages.
#!/bin/sh
echo 'processing started -->>'
LOC=/opt/appl/Mapping/
export JAVA_HOME=/usr/java6
export PATH=/usr/java6/bin
LD_LIBRARY_PATH=/opt/appl/JARS/
export LD_LIBRARY_PATH
java -classpath $LOC/ojdbc6-11.2.0.3.0.jar:$LOC/ds35-02.00.11.jar:$LOC/log4j-1.2.17.jar:$LOC/TestClasses.jar:$LOC/db2jcc_license_cisuz-3.0.0.jar:$LOC/db2jcc_license_cu-3.0.0.jar:$LOC/db2jcc-3.0.0.jar -Xms256M -Xmx512M com.home.backfill.TestRun
I can use Try-catch in Java file and use System.exit(1) at catch block, but I am looking for any good generic approach, as My code could be very long, not sure if it would be good idea to put System.exit(1) in every catch block.
If you want something generic:
interface ExceptionAction {
public void apply() throws Exception;
}
class Catcher {
public static void invoke(ExceptionAction ea) {
try{
ea.apply();
} catch(Exception e) {
System.exit(1);
}
}
}
Then invoke by creating lambdas. (You will have to set any 'return' value to a captured local variable):
Catcher.invoke(() -> {
/// your code here
});
I would note that this is about as verbose as try/catch though, and the latter is probably more readable/colloquial.
If I understood you correctly, why don't you ran a generic function that determines what kind of code to return?
try {
//your code here
} catch(YourException e){
Handler.handle(e);
}
Where Handler.handle(e) takes an exception and determines the Integer with which to shutdown the system. At least there you have a centralized point of where the system will shutdown.

How to findout main method has called by JVM or existing process?

Considering the following code
public static void main(String...arg){
//do something
if(<<the method has called by a new process>>){System.exit(0);}
else{System.setProperty("main_result","0");return;}
}
the main method would be called by a separated process by JVM or existing process, now how can I find it out?
Thanks in advance
Let's clarify: there might be another class with a main that was started, or the main is somehow called again.
Normally you want to call System.exit(0) (or return;?) but when called from the program itself you want to end in System.setProperty("main_result","0");.
public static void otherMain(String[] args) {
Main.main(args);
}
public static void main(String[] args) {
...
StackTraceElement[] elems = Thread.currentThread().getStackTrace();
//for (StackTraceElement elem : elems) {
// System.out.printf("%s%n", elem.getClassName());
//}
if (elems.length > 2) { // [0] Thread [1] main
System.setProperty("main_result","0");
}
}
In java, every Java process runs in its own JVM. So, the "same" main
method cannot be called by a different process under normal
circumstances
Even if you run the same program twice, they will be running in their
own JVMs.
You can try one thing.. Keep a static variable in your program, run it and
make it sleep for a long period of time (process 1).. Now, run the same
program again and update the static variable(runs in process 2).. See, whether it will be
updated in the first process (No, it won't be updated as each process will have it's own
set of variables..)
Do you really need it? Just don't use System.exit(0); and refactor main method to finish gracefully.
Calling System.setProperty in both cases - when run as new process and also as a class on classpath, will not make any difference.
Edit: Finding out who is calling the method is not easy and definitely bad practice.
I would refactor the code as follows:
public static void main(String...arg){
System.exit(doStuff(arg));
}
public static int doStuff(String... arg) {
//do something
}
To access this logic within the same JVM you can now call MyClass.doStuff and get the return value directly.
It would be better to consider refactoring and get rid of such problem.
Otherwise the following code can help:
if(Thread.currentThread().getStackTrace()[1].getClassName().equals(
System.getProperty("sun.java.command"))){
System.out.println("!");
}
Will not work if there is no "sun.java.command" property (on not Sun/Oracle JVMs it may absent)

Java App to run a Kettle Job and receive the result

It is possible to run a Kettle Job/Transformation from a Java application, and then get the result (a variable for example), in the same Java App?
Although command line execution from Java likely isn't ideal, below would work. Just replace the cmd line with the appropriate paths and read in the output file of the job.
public static void main(String[] args) {
try {
String cmd = "\"c:\\Program Files\\Pentaho\\pdi-ce-5.0.1.A-stable\\data-integration\\kitchen.bat\" -file=\"c:\\users\\exampleuser\\desktop\\examplejob.kjb\"";
System.out.println(cmd);
Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();
} catch (Exception e) {
e.printStackTrace(System.err);
}
/*READ OUTPUT FILE OF KJB IN TO OBTAIN VALUES*/
}
*http://forums.pentaho.com/showthread.php?81151-Tutorial-Using-command-line-arguments-with-Kettle-and-scheduling
*http://docs.oracle.com/javase/tutorial/java/data/strings.html
*http://wiki.pentaho.com/display/EAI/.01+Introduction+to+Spoon
*http://javarevisited.blogspot.com/2011/02/how-to-execute-native-shell-commands.html
*http://www.mkyong.com/java/how-to-execute-shell-command-from-java/
I'd try this to execute the transformation this way. Kettle's Java API is quite readable.
The way described above does not cover retrieving the results. You'd need to add some custom logic to read the output data of the job. I'm not sure if there is a generic way to do that with ETL.
You can try grabbing the output into a HSQLDB or another in-memory DB, as described here, and extract the output manually.

Control the execution of a java program from my java program

public class LineNum1 extends Thread{
public synchronized void run()
{
try {
Hello.main(null);
System.out.println("Stack Trace of thread"+ this.currentThread().getName());
System.out.println(this.currentThread().getStackTrace()[1].getLineNumber());
System.out.println("End of Stack Trace");
} catch (Exception e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
LineNum1 t = new LineNum1();
t.start();
}
}
I'm developing a code coverage tool.
Using the above program I'm executing Hello.java from here. Is there any method where I can get the control over Hello.java?
Or to make my life simpler can i get the line numbers of the executed lines(Execution path) of Hello.java?
You want to use the Java Debug Interface. It's the Java library that is used for writing Java tools like debuggers. It'll allow you to step through the program, query for line numbers and whatnots as you go.
There's a simple demo application for it called trace that does most of what you want already: http://docs.oracle.com/javase/1.5.0/docs/guide/jpda/trace.html
There's a lot of documentation for it, if you've got the time to read it:
http://docs.oracle.com/javase/1.5.0/docs/guide/jpda/index.html
You can probably execute the second Java class as a Process and read the output yourself.
I have not completed the code coverage completely yet. But I have used bytecode instrumentation to instrument the methods, hence i get the log of all the methods I've visited. This Javassist Turtorial might help you.

Categories