How to get processId from windowHandle in Java? - java

Is is feasible to get the process Id from windowHandle or even vice versa in Java?
We have the option to get the thread from the windowHandle in Java
User32.INSTANCE.GetWindowThreadProcessId(desktopWindow.getHWND(),null);
but how would be relate this thread to the processId

From GetWindowThreadProcessId
[out, optional] lpdwProcessId
Type: LPDWORD
A pointer to a variable that receives the process identifier. If this parameter is not NULL, GetWindowThreadProcessId copies the identifier of the process to the variable; otherwise, it does not.
In other words, pass an IntByReference, and afterwards retrieve its value. For instance (error checking omitted):
IntByReference lpdwProcessId = new IntByReference();
User32.INSTANCE.GetWindowThreadProcessId(desktopWindow.getHWND(), lpdwProcessId);
Optional<ProcessHandle> processHandle = ProcessHandle.of(lpdwProcessId.getValue());

Related

What is ProcessBuilder of Java's counterpart in C++?

There is a python program which is not installed in system's default path. How do I call a program in C++ similar to ProcessBuilder's functionality in Java.
What is the equivalent of the below in C++
ProcessBuilder pb = new ProcessBuilder("python3","software","param");
pb.inheritIO();
Process ps = pb.start();
if(ps.exitValue()==0) {
System.out.println("Process executed successfully");
}
https://en.cppreference.com/w/cpp/utility/program/system
int wstatus = std::system("python3 software param");
The return value is an implementation-defined value. On Posix systems it contains a lot of information that can be extracted using the following macros:
WIFEXITED(wstatus)
returns true if the child terminated normally, that is, by calling exit(3) or
_exit(2), or by returning from main().
WEXITSTATUS(wstatus)
returns the exit status of the child. This consists of the least significant 8
bits of the status argument that the child specified in a call to exit(3) or
_exit(2) or as the argument for a return statement in main(). This macro should
be employed only if WIFEXITED returned true.
WIFSIGNALED(wstatus)
returns true if the child process was terminated by a signal.
WTERMSIG(wstatus)
returns the number of the signal that caused the child process to terminate.
This macro should be employed only if WIFSIGNALED returned true.
WCOREDUMP(wstatus)
returns true if the child produced a core dump. This macro should be employed
only if WIFSIGNALED returned true.
This macro is not specified in POSIX.1-2001 and is not available on some UNIX
implementations (e.g., AIX, SunOS). Therefore, enclose its use inside #ifdef
WCOREDUMP ... #endif.
WIFSTOPPED(wstatus)
returns true if the child process was stopped by delivery of a signal; this is
possible only if the call was done using WUNTRACED or when the child is being
traced (see ptrace(2)).
WSTOPSIG(wstatus)
returns the number of the signal which caused the child to stop. This macro
should be employed only if WIFSTOPPED returned true.
WIFCONTINUED(wstatus)
(since Linux 2.6.10) returns true if the child process was resumed by delivery of
SIGCONT.

Using WM_COPYDATA for sending a String message between Java apps using JNI

I want to send a simple string message between Java applications using WM_COPYDATA (Windows' Data Copy IPC mechanism). I am using JNI to write the WinAPI code in C.
At this stage, I just simply print the message out at the receiving application. Currently, it just prints out null. I suspect it is because of lParam not being initialised. But I don't know how to use lParam to extract the data from COPYDATASTRUCT.
Any suggested solutions would be much appreciated. As you'll see, I'm new to WinAPI.
I currently have the following code:
Sending code:
HWND hwnd = 0;
LPCTSTR lpszString = "A message";
COPYDATASTRUCT cds;
cds.dwData = 1;
cds.cbData = sizeof(TCHAR) * (_tcslen(lpszString) + 1);
cds.lpData = (TCHAR*)lpszString;
SendMessage(hwnd, WM_COPYDATA, (WPARAM)hwnd, (LPARAM)(LPVOID)&cds);
return 0; // success
Receiving Code:
LPARAM lParam;
COPYDATASTRUCT* pcds = (COPYDATASTRUCT*)lParam;
if (WM_COPYDATA)
{
LPCTSTR lpszString = (LPCTSTR)(pcds->lpData);
printf("%s\n", lpszString);
}
else return -1;
return 0; // success
You are sending to a window handle with the value 0. You have to supply a valid window handle and 0 is not.
Some other comments:
You ostensibly use TCHAR but your code can only compile for ANSI. Unless you target Windows 98 don't use TCHAR. Use Unicode.
You should not assume that the data is null terminated when receiving. Make sure you copy no more than cbSize bytes. This guards against buffer overruns in case the sender is not who you expect.
It is customary to check dwData as a means to verify that the sender is who you expect.
Likewise you would normally pass the sender window as wParam rather than the recipient.
if (WM_COPYDATA) is pointless. The condition evaluates true at compile time.
Looking at your code it is not at all obvious that you have created any windows. You need a window to receive the message. Perhaps that is at the root of your problem. Since you did not provide an MCVE it is hard to be more precise.

NullPointerException while using jruby

I embed jruby script engine into my java program by using javax.script.ScriptEngineManager
I made some jruby code that end with do ~ end block,
after running all code, NullPointerException occured.
but code ends with any other statement, no exception occurs.
version : 1.7.19
Caused by: java.lang.NullPointerException
at org.jruby.embed.variable.Argv.updateARGV(Argv.java:169)
at org.jruby.embed.variable.Argv.retrieve(Argv.java:158)
at org.jruby.embed.variable.VariableInterceptor.retrieve(VariableInterceptor.java:154)
at org.jruby.embed.internal.BiVariableMap.retrieve(BiVariableMap.java:378)
at org.jruby.embed.internal.EmbedEvalUnitImpl.run(EmbedEvalUnitImpl.java:124)
in ARGV.java updateARGV
if (vars.containsKey((Object)name)) {
var = vars.getVariable((RubyObject)receiver.getRuntime().getTopSelf(), name);
var.setRubyObject(argv);
vars.getVariable returned null because of isReceiverIdentical return false
in BiVariableMap.java
if (var.isReceiverIdentical(receiver)) {
return var;
}
In isReceiverIdentical, this method just compare receiver with BiVariable's receiver usgin '=='.
Is this jruby bug? Or do I have to do something for this?
If you need more information about this problem, plz comment it!
I got ScriptEngine(engine) from ScriptEngineManager and set some java instance and method like this
engine.put("this", console);
engine.eval("$command = $this.java_method :command, [java.lang.String]");
here is my test ruby code. result and tab is java object
that has some method return String and list.
result = $command.call "something to pass"
puts result.getMessage
tabular = result.getData
tabular.each do |tab|
rows = tab.getRows
rows.each do |row|
puts row
end
puts tab.getColumnNames
end
I had created ruby type object in my java code by creating new Ruby object...
This causes checking fail in updateARGV because a receiver that register variable in BiVariableMap and another receiver that update variable are different.
So, I got a Ruby object from new ScriptingContainer(from it we can always get a same Ruby object if local context is singleton) and used it to create new ruby type object in my java code.
Reference: https://github.com/jruby/jruby/wiki/RedBridge#Singleton

how to access the variable in the object passed from client?

First of all I am new to Java programming and object oriented style programming. I started learning it on January this year.
Basically i have a class name vehicleInformation with some local variable.
Then I i prompt the information in the client side and then store it in a object vehicleInformation. Then pass the object to the server side. My instruction is to insert the data in the object to the database. My question is how do i access to the data in the object when it is pass from the client side.
the code below show how i create the object and send it to the server.
vehicleInformation v = new vehicleInformation(plateNumber,vehicleType, engineNumber, chassisNumber, make, model);
toServer.writeObject(v);
the code below is how i read the object but I have no idea how to access to the variable in the obect as we normally use objectName.variable to access it.
Object object = inputFromClient.readObject();
To be safe you should check the type of the object before the typecast.
if (object instanceof VehicleInformation) {
vehicleInformation = (VehicleInformation) object;
}
else {
// Do something with the unexpected object type. e.g. throw an exception.
...
}
You can typecast
VehicleInformation vehicleObject = (VehicleInformation)inputFromClient.readObject();
Cast your object to vehicleInformation.
vehicleInformation objectname = (vehicleInformation)inputFromClient.readObject();
and get variable objectname.variable
And follow class naming convention for better visibility.

JSONUtils.isNull returns false. But there is no element inside JSON String

I dont know if I use the wrong method?
But when I execute this line of code:
JSONUtils.isNull(Score.JSON_SCORE_QUESTION)?null:json.getLong(Score.JSON_SCORE_QUESTION)
on that json string(where Score.JSON_SCORE_QUESTION is the key "qs"):
{"username":"Stefan","points":1295,"level":26,"scomment":"Wuhuuuu","uuid":"08c3a06c-ad9a-4ec0-aec9-4223517389d3","sid":11747,"rank":121,"sstempel":1388768015000,"model":"SCORE"}
isNull always returns false.
Did I need another method?
JSONUtils.isNull "tests if the obj is a javaScript null (i.e. is JSONNull)", but a string (e.g. "qs") is not null in any applicable context. This function is for dealing with values and has nothing to do with properties. (Being static, it has no way of using the data in the json object anyway!)
Instead, JSONObject.has(key) (or containsKey) should be used to determine existance of a property:
Long score = json.has(Score.JSON_SCORE_QUESTION)
? json.getLong(Score.JSON_SCORE_QUESTION)
: null; /* or use a long primitive and provide a default */
Alternatively, the following might work (YMMV):
Long score = (Long)json.get(Score.JSON_SCORE_QUESTION);

Categories