Java SendMail sends mail after server is stopped - java

I have a UI wrapper for a jar. When the event 'submitButton' is triggered from the UI, the following method is called to execute it. The jar executes in a separate process, but the mail is sent only after the calling process (i.e. UI server) is stopped. Any idea why ? (The jar works fine when executed from cmd line).
public static String doSendMail(){
// Run a java app in a separate system process
Process process;
try {
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "SendMail.jar", ">>", "test.log");
process = pb.start();
InputStream in = process.getInputStream();
InputStream err = process.getErrorStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Success";
}

A couple of problems: >> is shell redirection. You are running the subprocess directly, so it probably got ignored. Also, you never handled the output written from the process, so it likely got buffered and blocked the process until the UI ended.

Related

I am trying to execute an exe in Java which is developed in Dotnet

The code in java was made to run a .exe file created in .NET platform and the code was shown to be running successfully. The process even showed to be alive when called with isAlive() function but doesn't run. The .exe did not run, i.e. was not shown anywhere in task manager. Also I checked it with waitFor() methood.
Further i need to run this on a Java Servlet please suggest me if what i can do to make this run, Thanks in advance
The code is as below:-
public static void main(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder("D:\\J2EEeclipse-workspace\\TARecruiter\\WebContent\\WEB-INF\\Debug\\Sharpenter.RP.UI.Console.exe");
Process p=pb.start();
System.err.println( p.waitFor());
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The below-provided code-snippet would work and initiate the process. Which can be viewable in the task manager. To make it work currently create a .java code with the provided snippet in the folder where the .exe file exists and run the code. Now you can make this code as a thread and call anywhere in your program as a thread to make it work. This certainly is not the final solution, but until the time I get to the actual reason keep working.
try {
Process
p=Runtime.getRuntime().exec("Sharpenter.ResumeParser.UI.Console.exe");
try{ p.waitFor();
}catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

Scheduled Task wont open my Jar

I am currently trying to create a scheduled task, that runs my Jar file every minute. the command line code to create the task looks like this:
schtasks /Create /tn Testname /sc Minute /tr C:\Users\MyUser\Desktop\Program.jar
no matter how long I wait, nothing happens. The Scheduled Task GUI shows that the result of my task is (0x1)
Howwever if I run C:\Users\MyUser\Desktop\Program.jar in the CMD everything works fine
What am I doing wrong?
I was able to create the scheduled task via Java, I dont know if this will help somebody in the future, but just in case I am gonna post my code anyway:
private void createScheduledTask(String taskName) {
List<String> commandList = new ArrayList<String>();
commandList.add("schtasks.exe");
commandList.add("/Create");
commandList.add("/tn");
commandList.add(taskName);
commandList.add("/sc");
commandList.add("Minute");
commandList.add("/tr");
commandList.add("java -jar C:\\Users\\MyUser\\Desktop\\Program.jar REPLACE_WITH_ARGUMENT");
try {
int returnValue = executeCMDStatement(commandList);
if(returnValue == 0){
//everything should have worked out
} else {
//there was an error
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static int executeCMDStatement(List<String> commandList) throws InterruptedException, IOException {
ProcessBuilder builder = new ProcessBuilder(commandList);
Process process = builder.start();
process.waitFor(3, TimeUnit.SECONDS);
return process.exitValue();
}

How can I perform an operation when a Spring application ends? [duplicate]

This question already has answers here:
Spring webapp - shutting down threads on Application stop
(1 answer)
Register shutDownHook in web application
(4 answers)
Closed 5 years ago.
I am not so into Spring framework and I have the following problem.
I am implementing a simple console application (it is a batch that obtain some data from a database and perform some call to an external web service).
When the application starts it creates a lock file in the same folder where the executed .jar file is.
My problem is: when the application ends this lock file have to be deleted.
This must be done either when the application terminates successfully or when it terminates for an error.
I read that in Java I can use a ShutdownHook but I am thinking that maybe Spring provide me some more neat way to do it.
So basically I have a situation like this:
public class MainApp {
public static void main(String[] args) {
try {
checkIfRunning();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
new MainApp().execute();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void execute() throws InterruptedException {
System.out.println("Trigger BATCH START");
//TimeUnit.SECONDS.sleep(150);
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.load("applicationContext.xml");
context.refresh();
System.out.println("OBTAINED CONTEXT");
System.out.println("Trigger BATCH END");
}
/**
* Check if the Trigger batch is alread running:
* #throws FileNotFoundException
*/
private static void checkIfRunning() throws FileNotFoundException {
System.out.println("checkIfRunning() START");
File f = new File(System.getProperty("user.dir") + "/lock.txt");
if(f.exists() && !f.isDirectory()) {
System.out.println("Lock file exists !!!");
}
else {
File file = new File(System.getProperty("user.dir") + "/lock.txt");
FileOutputStream fos = new FileOutputStream(file);
}
}
}
How can I correctly intercept the event related to the application termination to perform the delete of my lock file?
The application can terminate because:
It completed its execution.
The user press CTRL+C and quit it.
An exception occur and it terminate.
What is a smart way to do it using Spring?
Since the file creation happens outside of Spring, I would delete it outside of Spring for consistency.
You can add a shutdown hook:
try {
checkIfRunning();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} finally {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Deleting the lock file...");
// TODO: call a function to delete the lock file if it exists
System.out.println("Lock file delete");
}
});
}
According the documentation: addShutdownHook(Thread hook):
The Java virtual machine shuts down in response to two kinds of events:
The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

Java Open external program then close java program

Alright, I have a shutdown hook that makes sure I close my connection nicely whenever I close. What I need to do now is open another program (terminal emulator) then close mine while leaving the terminal emulator open. I am able to open the emulator but the java program doesn't close until the emulator closes. How can I run something and close my program out?
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
#Override
public void run() {
if (connection != null) {
try {
connection.close();
System.out.println("Connection Closed");
try {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "C:\\MVbase\\mvterm.lnk");
Process p = pb.start();
System.exit(0);
} catch (IOException e) {
System.out.println(e);
}
} catch (MVException e) {
System.out.println(e.getMessage());
}
}
}
}, "Shutdown-thread"));
The easiest way to do it is to make a shell script or batch file that runs the program then shuts it down and starts the terminal emulator.
#!/bin/sh
cd C:/location/of/program
javac program.java
java program
kill program
cd C:/location/of/terminalemulator
run terminalemulator
Save this as a batch file and it should do it all from the command line.

execute exe file through ecec() and then send the console (.exe) in background

i want to run a specified file (.exes) in background...
File file = new File ("C:\\Documents and Settings\\INTEL\\My Documents\\NetBeansProjects\\demo\\calc.exe");
Desktop.getDesktop().open(file);
what if i use Runtime stuff
Executes the specified string command in a separate process.
Process process = Runtime.getRuntime().exec("C:\\Documents and Settings\\INTEL\\My Documents\\NetBeansProjects\\demo\\calc.exe");
You could execute your process in another thread
Thread thread = new Thread(){
public void run(){
try {
Runtime.getRuntime().exec("...");
} catch (Exception e) { ... }
}
}
thread.start();

Categories

Resources