How to kill firefox child process/tab from Java/C++ - java

I have my application in Java which invokes a browser [IE or Firefox etc ] ..
Requirement is when my Java Application exits i have to kill all the web pages [Child processes ] i have opened from my Application in IE/Firefox etc..
I use the following code .
Note : cmd contains "System Browser exe path and URL"
static ArrayList<Process> pro = new ArrayList<Process>();
String cmd=" ";
Process p = Runtime.getRuntime().exec(cmd);
pro.add(p);
I maintain a static arraylist to add all the process objects .
To kill the process i invoked i use the below code
Iterator<Process> iter = pro.iterator();
while(iter.hasNext()){
Process p = iter.next();
System.out.println("Now Killing "+p.toString());
p.destroy();
}
This code[p.destroy();] is working fine for Internet Explorer , But its not working for Firefox/Chrome...
Since Firefox runs as a Main process and the process what i invoke goes as its child :(...
I have to use generic fix for Windows and Linux..
I can even go for C++ file fix which does this with some search criteria ..so that i can execute that executable from my code using
Runtime.getRuntime().exec("executable cmd");

In windows, you can run :
wmic process get description, executablepath, processid | findstr firefox
which will give you the PID of the firefox process. Then you can use tskill PID to kill
the process.

Good question.
There are several solution.
The first is the following. Run browser not directly but using script (shell for unix, bat file for windows) that will report you the process ID of the browser that it runs. Then use kill -9 PID on linux and taskkill on windows.
This solution will require you writing scripts for different platform (at list for 2).
But I have other suggestion. If the URL that you are opening in browser is yours (I mean you can add some javascript there) you can do the following. The URL that you are opening will create AJAX call to server. When you close your application you should say to server to send command to the browser to close it. At this moment javascript that is running into the browser will close its window. This is the most cross-platform solution.
BTW I think that the server that is used by mentioned AJAX component may be your own application. And the signal that you send to the AJAX component is just connection error. Really, if your application is the server and you are closing it, the AJAX call will fail. This 100% means that the browser should be closed too.

try using pkill (killing by process name) command.
Runtime.getRuntime().exec("pkill firefox");
or in c++
system("pkill firefox");
But it's not platform independent. It will run on Unix-like operating system, and not in windows.

Related

Jmeter and MemCached Sets and Gets

So apologies if what I ask is trivial but I am experimenting with Memcached and Jmeter. I have a Memcached server setup (as far as I can tell) and am able to make telnet requests to it via telnet IP PORT and additionally set and get using commands set and get appropriately.
Now point me to a different application if perhaps this is the wrong choice; but my understanding was that Jmeter should allow me to pound the server with equivalent Set and Get requests.
Unfortunately the experimental platform is a remote linux PC running Rockylinux which is similar to CentOS / RedHat to my understanding (I didn't set this part up); and as a result I do not have a GUI to launch while on the Linux PC. I have however opened Jmeter up on my local PC on windows and understand I should be able to send the test file over and run it.
I followed these instructions to try to setup a TCP sampler and set the "text to send" field as below; after doing the additional step in the link regarding the precompiler.
set tutorialspoint 0 900 9${CR}${LF}
memcached${CR}${LF}
quit${CR}${LF}
Running the above as a headless jmeter session doesn't generate any errors called [./jmeter -n -t "Sample.jmx" -l testresults.jtl"] but when I connect via telnet I'm also not seeing the value for the key "tutorialspoint" get updated. When manually doing the get and set I am seeing updates. Any ideas what I could be doing wrong? Checking the log indicates ResponseCode 200 OK as expected. Is there a good method to debug something in a Headless setup?
Thanks for your time.
I believe the easiest way is using Memcached Java Client library
Download spymemcached-2.12.3.jar and drop it to "lib" folder of your JMeter installation (or any other location in JMeter Classpath)
Restart JMeter to pick the .jar up
Add JSR223 Sampler to your test plan and use the following code snippets:
def client = new net.spy.memcached.MemcachedClient(new InetSocketAddress('your-memcached-host', your-memcached-port)) - for connecting to the server
client.set('tutorialspoint', 900, 'memcached').done to write memcached to the tutorialspoint key for 15 minutes
client.get('tutorialspoint') - to read the value of tutorialspoint key
client.shutdown() - to disconnect
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It
Demo:

Parent process unexpectedly killed by child cmd.exe process running java jar - WINDOWS 7 PROBLEM - C++

Info about the project: I am creating a C++ console application that manages a Minecraft server by listening to port activity. When server port is pinged, it starts the server and then periodically checks if there are established connections on that port. If none, the server is shut down and app goes into listening mode once again.
The problem arises when the server is stopped. Somehow my main console app is getting killed by the child server process and I can't seem to find out how and why or any solutions to this.
My console app creates a new cmd.exe child process that runs a "java -jar server.jar" command when starting the server. When stopping the server a simple "stop" message is written to the standard input of the child process. This all works fine and the java server stops.
However as soon as the child process exits, the console app unexpectedly crashes and the Windows "Program has stopped working." dialog appears. The curious thing is that I have tested the application on my programming laptop that runs Windows 10 and it runs without any issues there both in release and debug mode. My server machine is running Windows 7 however, so it seems to somehow be a Windows 7 problem.
Now there's no code I can really show you since it's the java and cmd.exe child process performing the exit and I of course didn't code the server.jar file. But I will attach an image link of the console when it crashes just for fun.
The child process does not have a separate window, it inherits handles from the parent console app and writes to the parent's STDOUT so messages from the child show in the main app's console.
I have tried starting the child process with CREATE_NEW_PROCESS_GROUP flag, still crashes.
I have tried ignoring SIGINT and SIGTERM signals, still crashes.
I have also verified that the application doesn't start execution of the commands following the server shutdown call (writing stop message to stdin of server process) so they can't be the problem.
If anyone has any tips or ideas about what could be the issue I'm all ears. Thanks!
Console application crashes, Windows "Program has stopped working." dialog is not shown on picture.
EDIT:
Okay, so I created a minimal reproducible example. Here is all the needed code (for C++ main function):
//security attributes for pipes
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
//handles for child standard input/output
HANDLE child_stdin_rd = NULL;
HANDLE child_stdin_wr = NULL;
if (!CreatePipe(&child_stdin_rd, &child_stdin_wr, &saAttr, 0))
return -1;
if (!SetHandleInformation(child_stdin_wr, HANDLE_FLAG_INHERIT, 0))
return -1;
STARTUPINFOW startupInfo;
ZeroMemory(&startupInfo, sizeof(STARTUPINFOW));
startupInfo.cb = sizeof(STARTUPINFOW);
startupInfo.hStdInput = child_stdin_rd;
startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
PROCESS_INFORMATION processInfo;
ZeroMemory(&processInfo, sizeof(PROCESS_INFORMATION));
//cmd.exe path
wstring exepath = L"c:\\windows\\system32\\cmd.exe";
//cmd command to start server
wstring command = L"cmd.exe /c java -Xms1G -Xmx4G -jar server.jar nogui";
LPWSTR com = new wchar_t[command.size() + 1];
copy(command.begin(), command.end(), com);
com[command.size()] = 0;
if (!CreateProcessW(exepath.c_str(), com, 0, 0, TRUE, CREATE_NEW_PROCESS_GROUP, 0, 0, &startupInfo, &processInfo))
return -1;
//sleep for 1 min, letting server start up
this_thread::sleep_for(chrono::minutes(1));
//command to stop server
string stopCmd = "stop\n\0";
DWORD stopCmdByteSize = stopCmd.size() * sizeof(char);
if (!WriteFile(child_stdin_wr, stopCmd.c_str(), stopCmdByteSize, 0, 0))
return -1;
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
CloseHandle(child_stdin_wr);
To reproduce this, your machine would need to be running Windows 7 and in the same folder as the application must be a Minecraft server.jar file (version 1.15.2 at time of writing this) which you can get from their website. Also, the server might need some setting up first, running it for the first time by double-clicking .jar file creates all needed server files, you must open "eula.txt" and accept the EULA by changing eula=false to eula=true. Then the server should be good to go.
Like stated before, I didn't code the server.jar file and thus do not know the complete behavior of the java server program.
Bug found! Problem solved!
Ahh, after some vigorous thinking and reading the docs again to verify the code is correct I found the culprit.
In the call to the WriteFile() function I forgot to give it a pointer to a DWORD so that it can update the number of bytes the function has written.
So the following code:
if (!WriteFile(child_stdin_wr, stopCmd.c_str(), stopCmdByteSize, 0, 0))
return -1;
Needed to be changed to:
DWORD bytesWritten = 0;
if (!WriteFile(child_stdin_wr, stopCmd.c_str(), stopCmdByteSize, &bytesWritten, 0))
return -1;
So I guess it was a kind of undefined behavior that Windows 10 could handle but Windows 7 couldn't, resulting in the program crashing.. Kind of feel embarrassed for writing this lengthy post because of a small error in a function call, but there you have it folks! Thanks to those who gave tips! :)
You may have better luck using RCON, which is a protocol built into the Java edition server used to remotely manage a server with a simple TCP packet format, rather than trying to write commands to the standard input of the server directly.
See wiki.vg's page on RCON for an explanation on the packet format.

How to Stop Hybris server from command prompt or Admin console

I want to add a new extension and for that I need to stop hybris server first, but I am unable to figure out how exactly I should STOP the server: through command line or by admin Console?
I cannot type any command as my server is running.
I also started the server by using hybrisserver.bat
just push ctrl + c in the command line window and the server is shut down properly
As a small side note, if you'd like to stop a hybris server through the admin console, you could always go to Console > Scripting Languages > Edit Statement and execute System.exit(0);
hybris has got all the necessary runtime shutdown hooks to do a graceful (as if you did CTRL + C).
In theory it's also possible to restart the hybris system internally by executing:
import de.hybris.platform.core.Registry;
Registry.destroyAndForceStartup();
By default, there's a restriction to forbid doing so using groovy scripts, though.
Sometimes it happen that the hybrisserver is runned on another console and even after hybrisserrver.sh stop some processes are still running. And you will receive message like:
INFO: Illegal access: this web application instance has been stopped already
My solution is (for linux based systems):
lsof | grep hybris
To get the processes runned from "hybris" directory(change on you need) and then kill the listed processes with:
kill -15 <PROCESS_ID>
PS. (This solution require the root privileges)
Use this command /bin/platform/hybrisserver.sh stop
That will stop the server.

Windows service installed with Procrun works in //TS mode, but doesn't start as a Windows service saying it "started and then stopped"

I installed a standard executable jar file as a Windows service by running the following command:
> prunsrv.exe //IS//"My Service" --Install="C:\path-to-prunsrv.exe" --Jvm=auto \
--Startup=auto --StartMode=jvm --Classpath="C:\path-to-MyService.jar" \
--StartClass=com.mydomain.MyService
I can now run my program fine in console mode by running the following command (I'm using Java 1.6):
> prunsrv.exe //TS//"My Service"
When I try to start the service through the standard Windows services interface, I get the following error message:
The MyService service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.
There is no output in my application's log file when I attempt to start the service this way. There is also no output in the Window's event log (Windows 7 64-bit). What can I do to try and figure out why this service will not run?
Don't use any white-space in the service name!
After many hours of testing and pulling apart Tomcat and duplicating it's bootstrap process, the fix for my problem ended up being that Apache Commons Daemon (Procrun) does not work properly when there is white-space in the name of the Windows service.
It seemingly correctly installs and registers a service with Windows when there are spaces in the service name. The Windows registry entries even look correct. The service even runs in debug (aka TS or console) mode just fine. When run, however, as an actual service launched by Windows it fails if the service was installed with a white-space in the service name.
I sure wish Procrun had some type of log output when it fails! Good logging can make debugging issues like this a snap.
I did need to have multiple words in my service name, so I named my service with one word and changed the name with the "DisplayName" parameter:
> prunsrv.exe //IS//MyService --Install="C:\path-to-prunsrv.exe" --Jvm=auto \
--Startup=auto --StartMode=jvm --Classpath="C:\path-to-MyService.jar" \
--StartClass=com.mydomain.MyService --DisplayName="My Service"
I wanted to give some additional information about what '11101101b' said above. (This is my first post, so please be gentle!)
I was able to get the service to install correctly with spaces in the service name by changing the //IS//MyService part of his command to instead be the following, which I suspect is what he also did. (I apologize if I'm assuming incorrectly.) Notice that the opening double quote is at the beginning of the string rather than at the beginning of the service name.
"//IS//My Service"
As was the case for him, the service installed correctly and looked correct, but it wouldn't start. I was able to get around that by changing the service's ImagePath value data setting in the registry to have the same change for the //RS//My Service part of the command. Therefore, the registry value instead had the following in its data setting:
"//RS//My Service"
Everything seems to be working without any problems.
This server starts and stops because of reason the task is completed by the service so it would stop automatically. if you have a logic of running long inside it would not stop.
I got same problem ... under my local machine everthing working fine on server the same issue => problem was that Working Path was not set.
May its heps someone ... be the force with you

Java - Access file with user authentication

I have a server where I work with a database and files using a java app.
When I start my app I give a report regarding file access to the server using:
public static boolean folderExists(String folderPath) {
File folderToCheck = new File(folderPath);
return folderToCheck.exists();
}
Every time I start my app (after a fresh restart of my computer)
I get a false response, even though the server is on.
The reason is because I must give an authentication as another user.
What I do is access the server through Windows
where I am being asked for username/password,
and after that I get a true response regarding file access to the server.
Is there a way to give the authentication username/password through Java,
and not through Windows?
Thank you
On Windows 'native' Java IO (e.g. java.io.File) always inherits the security context of the user running the JVM process. For example, you could run the Java app as a Windows service with the correct credentials.
The JCIFS project implements CIFS (the Windows SMB file server protocol) and allows you to directly specify the username/password.
See the API for examples.
I am pretty sure, that there is no way to grant fileaccess by java, without a Windows-Call.
You can call cacls file.log /e /t /p Everyone:f but this will be language-dependent.
I had a similar problem: How to change the file ACL in windows, if I only know the SID?
With Java7 there may be a way to do this.

Categories

Resources