I want to stop a server running on port 8080. In my java application, whenever application is closed, also this server needs to be stopped. But I could not find any solution except stopping the server manually. Is there any way to stop a server with codes ? By the way, I am using Windows 7
How are you starting SymmetricDs? As a windows service, as a WAR or embedded in you application?
Looking at the user guide it seems that if you could embed it in your code you ought to be able to start and stop it directly. More details in the user guide along with the following example code.
import org.jumpmind.symmetric.SymmetricWebServer;
public class StartSymmetricEngine {
/**
* Start an engine that is configured by two properties files. One is
* packaged with the application and contains overridden properties that are
* specific to the application. The other is found in the application's
* working directory. It can be used to setup environment specific
* properties.
*/
public static void main(String[] args) throws Exception {
SymmetricWebServer node = new SymmetricWebServer(
"classpath://my-application.properties");
// this will create the database, sync triggers, start jobs running
node.start(8080);
// this will stop the node
node.stop();
}
}
try {
// Execute a command to terminate your server
String command = "command to stop your server";
Process child = Runtime.getRuntime().exec(command);
} catch (IOException e) {
}
Why don't you check Cargo? It provides a Java API to start/stop Java containers. You can find the list of supported containers in the home page.
Since i did not see the code , how are creating server and accepting connection ,below
i have given you the following ooptions.you should try to implement the firstway ,
rest of the option wont guarantee whether correct process will be killed.
public void stopServer()
{
threadReference.interrupt();
}
while(!Thread.interrupted())
{
// Accept Server Connection
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
Runtime.getRunTime().addShutDownHook(new Thread()
{
public void run()
{
try
{
ref.stop();
} catch (IOException e)
{
// close server socket
// other clean up
e.printStackTrace();
}
}
});
you need to specify this in Runtime.getRuntime() TASKKILL /F /IM or there is a jps which is better to kill relevant process.
try
{
Process p = Runtime.getRuntime().exec("TASKKILL /F /IM communicator*");
BufferedReader in =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String result = null;
while ((result= in.readLine()) != null) {
if ( "SUCCESS".equals(result.substring(0,7))
{
break;
}
}
} catch (IOException e)
{
e.printStackTrace();
}
Related
Im using Akka 2.5.6 in Java 8 and I want to know the right way to finish de ActorSystem, part of the functionality of my code is to process some XML files and validate them, to achieve this I have created 3 actors:
Controller, Processor and Validator.
The Controller is responsible for initiating the process and sending file by file and other information to the Processor, then the Processor create a digital signature of the file and sends the response to the Validator that finally validates the status and sends an OK message to the Controller which is counting the number of files validated and compares them with the total files. Once the total of files with the total of validated files are equal, I call to finish the ActorSystem with the terminate () method.
The method to finish is as follows:
private void endActors()
{
ActorSystem actorSystem = getContext().system();
Future <Terminated> terminated = actorSystem.terminate();
do {
log.info ("Waiting to finish ...");
try {
Thread.sleep (30000L);
} catch (InterruptedException ex) {
log.error ("Error in Thread.");
}
} while (! ended.isCompleted ());
log.info ("Actors finished processing.");
}
The loop never ends because the future is never complete, I dont know if this is the right way, I hope you have understood me and can help me or give me some advice.
Try the following (the key here is the on complete) . I wrote a class along these lines to use in a setup and teardown for junit, to avoid issues from actor system not fully terminating in the teardown of one test before being created in another test. (that caused port already in use issues)
private static ActorSystem system = null;
private static Future<Terminated> terminatedFuture;
public static ActorSystem getFreshActorSystem() {
tearDownActorSystem();
while(system != null) {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
}
}
system = ActorSystem.create();
return system;
}
public static void tearDownActorSystem() {
if (system !=null && !isInMiddleOfTerminating()) {
terminatedFuture = system.terminate();
terminatedFuture.onComplete( new OnComplete(){
#Override
public void onComplete(Throwable failure, Object success) throws Throwable {
system = null;
terminatedFuture = null;
}
} , system.dispatcher());
}
}
private static boolean isInMiddleOfTerminating() {
return terminatedFuture !=null;
}
I have written a Java code that must run only after successful shutting down of weblogic server.
The code shuts down the weblogic server and performs the required operations and then restarts the servers.
My question now is .. Is there a way by which 1 can keep a tab on the weblogic console to see if the shutdown proceess is over or not or if there were some exceptions thrown by the server during startup or shut down(not manually but programmatically)??
In my local machine I had made the thread to sleep until the server was shutdown completely by keeping the average time to shut (manually).
The code goes as under:
static final String DOMAIN_NAMES = "domainNames";
static final String DOMAIN_HOME="domainHome";
public static void main(String[] argss)
{
AbstractApplicationContext context=new FileSystemXmlApplicationContext(new String[]{"src/main/resources/redeployconfig.xml"});
StepOneRedeploy stepOne=(StepOneRedeploy) context.getBean("stepOneRedeploy");
stepOne.setProperties();
Properties prop=stepOne.getProperties();
String domainNames = prop.getProperty(DOMAIN_NAMES);
System.out.println(domainNames);
String domainHome = prop.getProperty(DOMAIN_HOME);
StringTokenizer domainNamesTokens= new StringTokenizer(domainNames,",");
StringTokenizer domainNamesTokens2=domainNamesTokens;
ArrayList<String> serverIPListArray = new ArrayList<String>();
while (domainNamesTokens.hasMoreElements())
{
String domainName=domainNamesTokens.nextToken();
System.out.println(domainName);
serverIPListArray.add(domainName);
}
while(domainNamesTokens2.hasMoreElements())
{
String domainName=domainNamesTokens2.nextToken();
/** Stopping weblogicserver **/
String domainPathToShutServer = domainHome + domainName+"/stopWebLogic.cmd";
String commandToShutServer="cmd /C start "+domainPathToShutServer;
try
{
Process p = Runtime.getRuntime().exec(commandToShutServer,null);
}
catch (Exception e)
{
e.printStackTrace();
}
/**Putting thread to sleep for 1 minute**/
try {
Thread.sleep(20000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/** Deleting temp folder **/
try
{
File delTmpFile=new File("");
boolean isTmpDelete=delTmpFile.delete();
System.out.println(isTmpDelete);
if(!isTmpDelete)
{
throw new TempDeleteFailedException("Could not delete Tmp folder for "+domainName);
}
}
catch(TempDeleteFailedException tdfe)
{
tdfe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
/** Deleting stage folder **/
try
{
File delStgFile=new File("");
boolean isStgDelete=delStgFile.delete();
System.out.println(isStgDelete);
if(isStgDelete)
{
throw new StageDeleteFailedException();
}
}
catch (StageDeleteFailedException stgDelEileException)
{
stgDelEileException.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
/** Starting weblogicserver **/
String domainPath = domainHome + domainName+"/startWebLogic.cmd";
String command="cmd /C start "+domainPath;
try
{
Process p = Runtime.getRuntime().exec(command,null);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
I have tried ProcessBuilder to start weblogic server.
But it says that
java.io.IOException: Cannot run program "startWebLogic.cmd" (in directory "D:\Oracle\Middleware\user_projects\domains\ass1"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:470)
at TestMain.main(TestMain.java:35)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(ProcessImpl.java:177)
at java.lang.ProcessImpl.start(ProcessImpl.java:28)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
... 1 more
So if I were to refactor the Question...
How can 1 catch the exceptions thrown by the executable run using Java code?
Is there a way by which 1 can keep a tab on the weblogic console to see if the shutdown proceess is over or not or if there were some exceptions thrown by the server during startup or shut down(not manually but programmatically)??
Weblogic logs are written to disk. By default they ae in DOMAIN_NAME\servers\SERVER_NAME\logs\SERVER_NAME.log(see: Understanding WebLogic logging files).
Just monitor the server log for exceptions. Take a look at Commons IO - Tailer.
By the way, you can use WLST and JMX to stop, start, restart and monitor the health of Weblogic (see ServerRuntimeMBean and ServerLifeCycleRuntimeMBean), no need to fire standalone processes.
You can either:
Use MBeanServerConnection (see: This Example)
Use an Embbeded WLST interpreter to Manage the server Life Cycle.
"Waiting enough" is a bad idea as it will easily break when the situation changes, and using a process builder is very limiting (not to mention that, these startup scripts typically spawn the main process as a separate process so you don't get to watch them to start with).
I'd look into hooks that the WebLogic server provides. WebLogic has lots of hooks so I don't know which one would be appropriate for you, but for example if it's a servlet you could do your shutdown process from a ServletContextListener.
I am trying to implement a feature to restart PostrgeSQL server from Java code using Runtime.getRuntime().exec() method. The method is working fine if the PostgreSQL server is not SSL enabled but if the PostreSQL server is SSL enabled and if the private key is encrypted with a password, it requires passphase to be passed. I tried with below code for implementing the same,
String postgreSQLRestartCMD =
"/u/postgreSQL/pg_ctl -D /u/postgreSQL/data restart -w";
//-w option waits until the passphase is sent
final Process restartPosgreSQLServer = Runtime.getRuntime().exec(postgreSQLRestartCMD);
PrintStream ps = new PrintStream(restartPosgreSQLServer.getOutputStream());
ps.println("keyPassword"); // sending passphasse here
new Thread(new Runnable() {
#Override
public void run() {
try {
IOUtils.copy(restartPosgreSQLServer.getInputStream(), logWriter);
}
catch (final IOException e) {
logWriter.println("Error occurred while reading InputStream.");
e.printStackTrace(logWriter);
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
try {
IOUtils.copy(restartPosgreSQLServer.getErrorStream(), logWriter);
}
catch (final IOException e) {
logWriter.println("Error occurred while reading ErrorStream.");
e.printStackTrace(logWriter);
}
}
}).start();
int returnStatus = restartPosgreSQLServer.waitFor();
if (returnStatus == 1) {
logWriter.println("Error has occured while running PostgreSQL server.");
} else {
logWriter.println("PostgreSQL has started successfully.");
}
But the server is not getting started. I am trying in Linux. In console its getting struck with below line and I guess passohase not sent properly.
Enter PEM pass phrase:
Where is this going wrong and why is the passphase not sent?
Edit
Upon digging further I just found that Runtime.getRuntime().exec(cmd) is creating new process, my ps.println("password") is passed to parent process. But I am not sure, whether my observation is right.
What you are not taking into account is that before programs ask for the password, they flush the input buffer. Otherwise it would be very easy to have extra characters read in for password, that the user accidentally typed before the password prompt.
You'll have to raise the level of complexity of your code to analyze the process's output and print to its stdin only after actually witnessing the password prompt.
how to run java tcp server in window azure?
can window azure do it?
I find so many article about java application for window azure,they is that open a JSP web project in eclipse, and than use worker role publish it in window azure, but my tcp server is general java project, so how to publish it to window azure?
my tcp server:
public class test {
private static int serverport = 12345;
private static ServerSocket serverSocket;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(serverport);
System.out.println("Server is start.");
while (!serverSocket.isClosed()) {
System.out.println("Wait new clinet connect!");
waitNewPlayer();
}
} catch (IOException e) {
System.out.println("Server Socket ERROR");
}
}
public static void waitNewPlayer() {
try {
Socket socket = serverSocket.accept();
System.out.println(socket.getInetAddress().getHostAddress()+"'s socket is connected now!");
createNewUser(socket);
} catch (IOException e) {
}
}
public static void createNewUser(final Socket socket) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println("nangnang");
} catch (IOException e) {
System.out.println("Socket is closed!");
}
System.out.println("This socket is removed form the player array!");
}
});
t.start();
}
}
You should be able to run an app like this in Azure, but you'll need to take care of a couple of things:
Open an Input Endpoint for your worker role - this opens the port to the outside world. You then need to either map it to the exact same port internally, or let Azure pick a port for you (and then you can ask the role environment which port you've been assigned, and open that port in your code instead of 12345)
For all your println's, you'd need to remote-desktop to see them, or you need to push them to diagnostics logging so you can see those debug statements via an external tool like Cerebrata's Diagnostics Manager.
As far as publishing: It's the same as the jsp examples you've seen: you build an Azure project to go along with your Java project, you set up the role size and instance count, create input endpoints, optionally create a cache, set up configuration settings for storage accounts, create a package to run in emulator or in the cloud, etc.
You might also want to try AzureRunMe which also supports Azure Java Project. http://azurerunme.codeplex.com/
I'm trying to run headless tests from Jenkins. This works fine for HTML tests when I specify the HTML test suite. But now I want to run selenium-2 tests against the same selenium server.
I tried this:
Execute shell:
export DISPLAY=":99" && java -jar /var/lib/selenium/selenium-server.jar
But this seems to be hang until I stopped the server manually. How do I start the selenium server in such a way that my selenium RC tests invoked through grails ?
There is no special method to "start" selenium server to be used by any particular language. When you start selenium server it will start listening on a port for incoming requests. You should be having a line of code inside your tests to point your tests to the selenium server. I don't know grails. In java it would be
Selenium sel = new DefaultSelenium("host","port","browsername","baseurl")
> host - IP of the machine where server is started
> port - port number on which selenium server is listening. This is
usually 4444 if you don't specify anything
> browsername-Browser on which you want the tests to be
> run baseURL- base URL of the web app you need to test.
The equivalent method for this in grails should get you working.
EDIT - JAVA code to start selenium server:
Selenium sel;
int port=9999;
public static SeleniumServer server;
public void startSeleniumServer() throws Exception {
try {
ServerSocket serverSocket = new ServerSocket(port);
serverSocket.close();
//Server not up, start it
try {
RemoteControlConfiguration rcc = new RemoteControlConfiguration();
rcc.setPort(port);
server = new SeleniumServer(false, rcc);
} catch (Exception e) {
System.err.println("Could not create Selenium Server because of: "
+ e.getMessage());
e.printStackTrace();
}
try {
server.start();
System.out.println("Server started");
} catch (Exception e) {
System.err.println("Could not start Selenium Server because of: "
+ e.getMessage());
e.printStackTrace();
}
} catch (BindException e) {
System.out.println("Selenium server already up, will reuse...");
}
}
public void stopSeleniumServer(){
if (server != null)
{
try
{
server.stop();
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("Selenium server stopped..");
}
public void startSeleniumRC() throws Exception{
sel=new DefaultSelenium("localhost",
port,
"*firefox",
"http://www.google.com");
sel.start();
}
public void stopSeleniumRC()
{
sel.shutDownSeleniumServer();
}