Restart Tomcat with Java - java

I need to restart the tomcat from Java code.
For eg, if a query is not executed for a certain time Period then it will restart the tomcat automatically.
I have tried the following shutdown and startup code, but when we shutdown the tomcat then the java code will not run and tomcat not started.
Note :- I am running this code from a application and restarting the same tomact which the same application is using.
Following the code
try {
PreparedStatement.setQueryTimeout(10);
rs = PreparedStatement.executeQuery();
} catch (SQLException ex) {
System.out.println("IN CATCH BLOCK FOR THE REFRESH INVOICE");
String shutcommand = "killall java";
Process shutchild = Runtime.getRuntime().exec(shutcommand);
System.out.println("JAVA PROCESS KILLED");
String locationCommand = "cd /root/cluster/tomcat6/bin";
Process locationChild = Runtime.getRuntime().exec(locationCommand);
String strtcommand = "./startup.sh";
Process strtchild = Runtime.getRuntime().exec(strtcommand);
}

Killing tomcat after SQLException this is not good idea to handle this exception. Probably the problem is on database site.
But if you are sure, that it is what you need you can kill this java proces in this section, but to run tomcat you should use for example bash and cron. Why? Beacues after killing your executing code will stop, so you don't achieve the line to start tomcat.
How to check tomcat: Is Tomcat running?

TL;DR
File binaryDir = new File(System.getProperty("catalina.home") + File.separator + "bin");
String restartCommand = "\"shutdown.bat & ping 0.0.0.0 -n 4 & C:\\WINDOWS\\system32\\net start Tomcat8\"";
new ProcessBuilder("cmd", "/c", restartCommand).directory(binaryDir).start();
Survive
Creating new process will survive JVM shutdown. If you combine commands in one line
it should work fine according to my tests and this.
shutdown.bat
You need to use shutdown.bat instead stopping windows service because it often fails on Windows with message Cannot stop service Apache Tomcat...
ping 0.0.0.0 -n 4
You need to wait some time after shutdown otherwise you will get Service is already starting. Try again later error message. Also note I use ping instead timeout because it causes problems on some systems.
C:\WINDOWS\system32\net start Tomcat8
I'm starting windows service because invoking startup.bat won't work for me. Also remember to replace Tomcat8 if you using different tomcat or custom service name for example Tomcat7
Redirect I/O
Don't redirect input or output of process instance or command will shutdown with JVM, and Tomcat won't start.

You can execute this native command using java
String command = "c:\program files\tomcat\bin\startup.bat";//for linux use .sh
Process child = Runtime.getRuntime().exec(command);

You should consider using ProcessBuilder instead of Runtime exec. Also, you should split all the arguments when you want to execute a command.
I suggest this :
ProcessBuilder shutcommand = new ProcessBuilder("killall", "java");
Process shutchild = shutcommand.start();
System.out.println("JAVA PROCESS KILLED");
ProcessBuilder strtcommand = new ProcessBuilder("/root/cluster/tomcat6/bin/startup.sh", "java");
Process strtchild = strtcommand.start();

Related

java.lang.InterruptedException while running a batch file

I am trying to run a batch file which has set of services I want to restart. When I call this batch file from my Java application I get Interrupted Exception.
My batch file
call net stop app-service
call net start app-service
call net stop ui-service
call net start ui-service
call net stop custom-app
call net start custom-app
call net stop MSSQLSERVER /Y
call net start MSSQLSERVER
My java code to run the batch file
File file = new File(System.getProperty("user.dir") + File.separator + "restart.bat");
String time="cmd /c "+file.getAbsolutePath();
Process p = Runtime.getRuntime().exec(command);
int exitvalue = p.waitFor();
I'm getting the following error
java.lang.InterruptedException
at java.lang.ProcessImpl.waitFor(ProcessImpl.java:451)
What am I doing wrong?
Looks like the problem is with the batch file. Calling stop and start immediately is what's causing the issue. Make sure the SQL server and services are stopped, then start the server and those services.
Please check this answer:
Stop and Start a service via batch or cmd file
Use the SC (service control) command, it gives you a lot more options
than just start & stop.
DESCRIPTION:
SC is a command line program used for communicating with the
NT Service Controller and services. USAGE:
sc [command] [service name] ...
The option <server> has the form "\\ServerName"
Further help on commands can be obtained by typing: "sc [command]"

Running shell script on tomcat7

I have been breaking my head for two days trying to fix the file permissions for my tomcat7 server. I have a library class (.jar file included in myapp/WEB-INF) which needs to run a shell script. The library is written by me and works fine within NetBeans ie. no hassle in creating,reading and deleting files. That is because NetBeans runs the program as blumonkey(my username on my Ubuntu System). But when I import this into tomcat and run it, tomcat "executes" the command, produces no definite output, tries to check for a file(which will be generated when the script succeeds) and throws a FileNotFoundException.
More Details as follows:
Tomcat7 installed using apt-get, has its data in 2 locations - /var/lib/tomcat7 with conf and webapps folders and /usr/share/tomcat7 with the bin and lib folders
The user uploads a .zip file which is stores to /home/blumonkey/data. Rest of the program runs on the documents stored here. All new folders/files uploaded by tomcat have, obviously, tomcat7 as the owner.
I have tried things like changing the ownership to blumonkey, adding tomcat7 to blumonkey user group but none of the methods worked (Somewhere around here I probably messed up changing permissions carelessly :/ ). Apparently tomcat7 is unable to process on the files it owns.(How can this be?).
The script works when I run it in the terminal. But it doesn't work when I do a sudo -u tomcat7 script.sh, ie run it as tomcat7. It just exits with no message. I doubt that this it what is happening as I have tried to debug by redirecting the errors and outputs in ProcessBuilder but they came empty.
Any help regarding how to fix the issue and get the script running would be greatly appreciated. Please comment if you need any more info.
The code for script execution
private static void RunShellCommandFromJava(String command,String fn, String arg1,String arg2) throws Exception
{
try
{
System.out.println(System.getProperty("user.name"));
ProcessBuilder pbuilder = new ProcessBuilder("/bin/bash",command,fn,arg1,arg2);
System.out.println(pbuilder.command());
pbuilder.redirectErrorStream(true);
Process p = pbuilder.start();
p.waitFor();
}
catch(Exception ie)
{
throw ie;
}
}
The command which needs to be executed
"/bin/bash /abs/path/to/script.sh /abs/path/to/doc/in/data-folder maxpages=30 maxsearches=3"
PS : I have followed this question but it didn't help. I also tried other options like Runtime.exec(), bash,/bin/bash/ and /bin/bash/ -c, some of them don't work at all, others give no results.
Try to use Runtime and check standard error to find out what was the problem (probably permissions or paths):
// run command
String[] fixCmd = new String[] { "/bin/bash", "/abs/path/to/script.sh", "/abs/path/to/doc/in/data-folder", "maxpages=30", "maxsearches=3" };
Process start = Runtime.getRuntime().exec(fixCmd);
// monitor standard error to find out what's wrong
BufferedReader r = new BufferedReader(new InputStreamReader(start.getErrorStream()));
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}

ActiveMQ query: How to start

I am starting ActiveMQ process through Java code like this:
ProcessBuilder pb = new ProcessBuilder(activeMQHome + "run_activemq.sh",
logDirectory,
activeMQHome,
brokerPath);
pb.start();
logDirectory: log location
activeMQHome: /Common/thirdParty/apache-activemq-5.3.0/bin/
brokerPath: brokerPath location
Now I have to start this process thorugh command line. Or to be more specific, I have to start it through /etc/inittab so that it can start automatically.
What entry should I give? I can start it by ./run_activemq.sh but how will I give logDirectory and brokerPath?
Actually there is need to start AMQ process through Java code. ActiveMQ already comes with start/stop script in its $ACTIVEMQ_HOME/bin directory and that you can very well put in /etc/inittab to start at system startup. Log Directory and other settings are configured in $ACTIVEMQ_HOME/conf/activemq.xml file.

how to restart tomcat from a running webapp?

I need to restart tomcat service from a webapp running on this tomcat. So I'm trying to execute script that stops tomcat service, and then starts it:
echo "before stop" >> textfile.txt
NET STOP "Tomcat7"
:loop
timeout 3
SC query Tomcat7 | FIND "STATE" | FIND "RUNNING" > NUL
IF ERRORLEVEL 1 (
goto start
) ELSE (
goto loop
)
:start
NET START "Tomcat7"
Java code:
String command = "C:\\Tomcat 7.0\\bin\\restart.bat";
Process p = Runtime.getRuntime().exec(command);
Tomcat is stopped, but not started.
If I run this batch from command line, it works properly.
thank you for your time
This worked:
String fileName = "C:\\Tomcat 7.0\\bin\\restart.bat";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
Runtime.getRuntime().exec(commands);
taken from http://www.rgagnon.com/javadetails/java-0014.html
What you are asking is not exactly safe and possible but do take a look at Tomcat manager API that allows you to programmatically manipulate Tomcat deployment and instance:
http://tomcat.apache.org/tomcat-7.0-doc/api/index.html
http://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/catalina/manager/host/HostManagerServlet.html
Agree with Edmon.
Tomcat is a provider of containers. Each container should act independently of each other, even if they call the services another provides. This should all be done via RMI or alike.
Like Edmon also suggests, you could call using the API, but again... sounds bad. Instead, question why it needs to restart. Then, if there's no work around, use the Tomcat Manager.

Invoking a Remote .bat file over http

I have a .bat file on a remote machine. I want to invoke it through http call. I dont want to make any changes on the remote machine. Is there a way to do it using java and http?
String command = "cmd /C start C:/Users/abc/Desktop/test.bat";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
The above works good to invoke a .bat file on local machine. I would not mind considering other ways too, but invoking it through http would be the first choice.
EDIT:
I am using paramiko to do this now. However,I am unable to run the remote commands on the command prompt.
ssh = paramiko.SSHClient()
print "Enter the IP address"
ip = raw_input("ip>")
print "Enter the username"
user = raw_input("username>")
print "Enter the password"
pwd = raw_input("password>")
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=user, password=pwd, allow_agent = False)
print "connection successfull"
i, o, e = ssh.exec_command("echo test") # example command
s = e.read()
if s: # an error occurred
raise RuntimeError, s
result = o.read()
print result
Somehow it says AllowDesktopAccess failed
You need a service on the remote machine, for example an http server that is configured to run this script on demand (eg via cgi) or an ssh server you can connect to to issue the command.
Since you're using windows (I assume) then PsExec may be the service you need.
http://technet.microsoft.com/en-us/sysinternals/bb897553

Categories