Get updated copy of environment variable in java - java

I want to get latest/updated copy on environment variable using java.
Java is not returning latest copy if someone changed particular environment variable after running a programme.
please use below sample code to test the scenario.
import javax.swing.JOptionPane;
public class Test extends Thread {
public static void main(String[] args) {
Test test = new Test();
test.start();
}
#Override
public void run() {
super.run();
while (true) {
JOptionPane.showMessageDialog(null, System.getenv("A"));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Update:
Tried ProcessBuilder also
ProcessBuilder processBuilder = new ProcessBuilder("echo %A%");
System.out.println(processBuilder.environment().get("A"));

The environment variables are set when the JVM starts and will not change.
That is generally true for all Windows programs. E.g. start a Command Prompt, change an environment variable through the Windows Control Panel, and the Command Prompt will not see the changed value.
Only Command Prompts opened after the change will see the change.

Related

Java console app jar - Handle Exception and continue in windows command prmpt

I have a Console Java Application in maven, infinite loop
I have handle exception in java
public class MyClassName {
public static void main(String[] args) {
while (true) {
start();
}
}
private static void start() {
try {
//this method check new files in S3 and copy to network location also it has throws Throwable
//i have not added code here because it is too long
doProcess()
} catch (Throwable t) {
t.printStackTrace();
}
}
}
doProcess() method check new files in S3 and copy to Network Machine
also it has throws Throwable
after creating jar, in windows command promp
java -jar -Xmx8192M jarname.jar
when it throws exception, pause completely until ctrl+C, but if I ctrl+C it will resume again,
what is wrong here?
is there any wrong on java code or is there any wrong on command?

Execute java in shell and wait until i get the return code

I am now executing java a java program like this:
package com.test;
public class Test {
public static void main(String[] args){
execute();
}
public static String execute(){
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "a";
}
}
I want to execute the Test.execute() method in linux shell script, wait until the method return and get return code . but the return of main() method is void , so what Can I do the get a return code or return msg from it ?
Any suggestions?
I find a solution:
package com.test;
public class Test {
public static void main(String[] args){
execute();
}
public static String execute(){
try {
System.out.println("sleeping");;
Thread.sleep(5000);
Runtime.getRuntime().exit(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "a";
}
}
And then my shell:
#!/bin/bash
java -cp test.jar com.test.Test
echo "The return code of the java application is $?"
I can get the value n which is in Runtime.getRuntime().exit(n);
First change the signature of main method in your code example:
public static void main() to public static void main(String[] args)
Then instead of just calling the execute method from main, try to print the result using System.out.println :
System.out.println(execute());
and then in linux shell you can use following to get the return values:
> set out = `java com.test.Test`
> echo $out
The shell script would have to call java com.test.Test. And this will call the main method which inturn is currently calling execute.
From a shell script you would have to start a JVM and a JVM always starts with a Main method.
As for the return code, you can access it using the $? shell variable.
So basically your shell script would be something like this:
#!/bin/bash
java -cp . com.test.Test
echo "The return code of the java application is $?"
Also you need to specify the classpath where all you relevant classes reside. In the above example I am putting in the current dir as the classpath.
The JVM will terminate with a exit code of 0 on completion of all non-daemon threads. If you want to return a specific exit code in case of an error you can use System.exit(<codehere>). Please note that calling System.exit() will cause the JVM to shutdown even if there are other non-daemon threads that are running.
Edit:
Added "-cp ." to the command based on the comments.
Added some exit code details

Java Console Restart

How can I restart my Java Console Application.
I want to create a method that when it's being called it restart or relaunch the console application. Can you guys give me some ideas how can I do it?
Have you tried calling main(args) passing in String[] args
If you really want a restart() method you could do something like
private void restart(String[] strArr)
{
main(strArr);
}
Crude mini example
import java.io.*;
public class Test{
public static void main(String[] args)
{
try{
System.out.println("Type 'R' to restart");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
if(input.equals("R"))
restart(args);
else
System.out.println("You did not restart");
}
catch(Exception e)
{e.printStackTrace();}
}
private static void restart(String[] strArr)
{
System.out.println("You restarted");
main(strArr);
}
}
I can't think of a way to do it using just Java, you will need some help from scripting. You could restart by finishing the JVM execution with System.exit() and using a special value for the caller to know if it needs to be restarted rather than finished. So in your Java code you would have something like this:
public class Test {
public static final int RESTART_CODE = 100;
public static void main(String ... args) throws IOException {
// DO something...
restart();
}
static void restart() {
System.exit(RESTART_CODE);
}
}
And then a script invoking the JVM (in this case a Linux bash script, you could do something similar with a *.bat file if you're using Windows). Tee script:
#!/bin/bash
java Test "$#"
[ $? == 100 ] && ./test.sh "$#"
An then you can call your program with
java.sh _argument1_ _argument2_ ...
Theoretically, you should be able to called Runtime.exec() and pass in the command to run your Java Console App.
For precaution, prior to calling Runtime.exec(), you should save all the data or reach the state where your application is ready to exit.
As Runtime.exec() will execute another instance of console app, and the new instance could have loaded all the data.
After successfully called Runtime.exec(), the existing app can peacefully die off.
Let me know if this can be done, as my concern is whether the new instance will be killed off when the existing app exited.

Run a .java file using ProcessBuilder

I'm a novice programmer working in Eclipse on Windows XP, and I need to get multiple processes running (this is going to be a simulation of a multi-computer system). My initial hackup used multiple threads to multiple classes, but now I'm trying to replace the threads with processes.
From my reading, I've gleaned that ProcessBuilder is the way to go. I have tried many many versions of the input you see below, but cannot for the life of me figure out how to properly use it. I am trying to run the .java files I previously created as classes (which I have modified). I eventually just made a dummy test.java to make sure my process is working properly - its only function is to print that it ran.
My code for the two files are below. Am I using ProcessBuilder correctly? Is this the correct way to read the output of my subprocess? Any help would be much appreciated.
David
Edit: The solution is to declare ProcessBuilder("java.exe","-cp","bin","Broker.test");
primary process
package Control;
import java.io.*;
import java.lang.*;
public class runSPARmatch {
/**
* #param args
*/
public static void main(String args[]) {
try {
ProcessBuilder broker = new ProcessBuilder("javac.exe","test.java","src\\Broker\\");
Process runBroker = broker.start();
Reader reader = new InputStreamReader(runBroker.getInputStream());
int ch;
while((ch = reader.read())!= -1)
System.out.println((char)ch);
reader.close();
runBroker.waitFor();
System.out.println("Program complete");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
subprocess
package Broker;
public class test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("This works");
}
}
You are calling the java compiler on the .java file, this will not run the class. What you probably want to do is running java.exe on your .class file. (ie something like "java.exe -cp ./bin Broker.test", assuming your class files are in ./bin)

How to run code after a call to Sytem.exit(0) in a finally block

I have three classes say alpha, beta, gamma and each of the three classes has a main method.
Both alpha and beta classes have, inside their main method, a try...catch...finally block like:
public class alpha{
public static void main(String[] args){
try{
Do something;
}catch(Exception ex){
ex.printStackTrace();
}
finally{
System.exit(0);
}
}
}
public class beta{
public static void main(String[] args){
try{
Do something;
}catch(Exception ex){
ex.printStackTrace();
}
finally{
System.exit(0);
}
}
}
Now in gamma class i call main methods of alpha and beta classes to run continuously like below
public gamma{
public static void main(String[] args) {
try {
alpha.main(arg);
beta.main(arg1);
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is that the code beta.main(arg1) is never reached due to the System.exit(0) inside the alpha class's finally block.
Since alpha and beta are standalone applications when they executed separately they should terminate the service at the end of program.
So now this there any way to reach the beta.main(arg1) line without much changing the actual functionality of alpha and beta classes.
Kindly let me know if you need further details.
Thanks in advance...
In such case, shutdown hook can be used:
public class Gamma{
public static void main(String[] args) {
try {
Thread hook = new Thread() { public void run() { Beta.main(args); } };
hook.setDaemon(true);
Runtime.getRuntime().addShutdownHook(hook);
Alpha.main(args);
} catch (Exception e) {
e.printStackTrace();
}
}
}
(Ideally, nothing that is part of a module's public API should ever do anything that calls exit, and the main method of a class should just be a small shim that invokes something else that does the real work before producing the proper exit code.)
That said, if you want to prevent System.exit, you can register a SecurityManager that converts calls to System.exit into SecurityExceptions or Errors.
System.exit:
throws
SecurityException - if a security manager exists and its checkExit method doesn't allow exit with the specified status.
Something like
System.setSecurityManager(new SecurityManager() {
#Override
public void checkExit(int exitCode) throws SecurityException {
throw new SecurityException("stop that");
}
});
Then the method which is calling main methods can just catch and suppress that SecurityException. You could make it more robust by creating your own ExitCalledError and throwing that instead and only suppressing that.
I find this very useful for preventing unit-test runners from spuriously reporting success when the test runner is exited by code under test with a zero exit code.
Really, the only solution is to get rid of the System.exit() call. This is why System.exit() is evil. A good way to replace them is by throwing an exception -- you can add an exception handler to the system (look into adding them to ThreadGroups to add one for every exception path) and then decide what you want to do.
System.exit(0) terminates the currently running Java Virtual Machine. It closes all application on the VM, not just the application which calls System.exit(0). You need to think alternative for your functionality. Here is a link about it. System.exit usage

Categories

Resources