Can java access global events created using CreateEvent - java

I am trying to access a global event created by native code in my java client. I am using JNA for this purpose to call OpenEvent method of kernel32.dll. But the method always returns NULL and GetLastError returns 2, which is File not found.
So I was wondering if JVM can see these global events and if so is there any other approach I can use?
--
Vinzy

How do you call your openEvent?
I suppose it's something like this
int result = kernel32.OpenEvent( 10000, false, "Global\\nameOfEvent" ); //request for deletion
with the only difference you may be using objects as arguments, which, I suppose, is a matter of preference.
Maybe if you provide the code for the call we might be able to help you. Another thing to be asked is if you call CreateEvent in your native code somewhere. If you dig into the Windows API, you will notice that:
"The function succeeds only if some
process has already created the event
by using the CreateEvent function."
source : http://msdn.microsoft.com/en-us/library/ms684305(v=vs.85).aspx
Which in your situation mean you will be in a lot trouble if you were not the one creating the event. There is a way of obtaining a handle to an event you did not create but it's a bit more complicated and let's start by you providing a bit more information.
Cheers.
To sum it up:
If you don't call CreateEvent anywhere in your code you will have trouble when calling OpenEvent. To escape this problem you would basically have to find which process/thread holds the lock to the event and make it give it to your thread (the jvm's).
If you do call CreateEvent in your code then you should not have any problems obtaining a reference to your event and the culprit is somewhere else.
In any case, a bit more code would be nice.

Related

JCEF - access browser window object

I need to access the browser window object to assign some objects and functions to it. I have read that it may be possible on onContextCreated call but I even don't know on which object it is called and how to access this object. I read https://magpcss.org/ceforum/viewtopic.php?f=10&t=12367 but those 'fancy' links don't help...
Also, I fetched both JCEF and Pandomium, which wraps jcef natives... but didn't found any hint in any of them (searched by calls of onContextCreated).
I have only found CefMessageRouter, but it seems to provide only basic function calls and callbacks (I also need to pass an object which contains function also), which not exactly makes me happy.
To say more, I know that assigning values may be possible with CefV8Value... but didn't found implementation (and even declaration) of it in java files.
Maybe it is possible to hack this like pass name of the existing function and then allow js to find this one in the scope, but the problem is I would not like to not give my web app too much knowledge about being embedded...
I appreciate any help.

how to create a custom stacktrace in java with additional info (like parameters)?

I was assigned a task to create a custom stacktrace like output to a log file for some specified functions, but instead of just using the class and method names I would also have to output the parameters and their values.
This is supposed to be a separate jar that could run on any java project, after.
I don't even know if such thing is possible, let alone where to start.
Any help would be appreciated.
EDIT: there is other library that does that by using native VM api: https://github.com/cretz/stackparam it also modifies Throwable class to always print that modified stacktrace.
The only possible way I can think of is using agents and instrumentalization, but agent needs to be added to startup command line.
Then I would register transformer to transform every class (remember that some basic java classes might be already loaded) using ASM library and add code to beginning of every method invocation to manually track each method class and pass it to my library that would track them:
// note that parameters names might not exist in runtime if code was compiled without a flag to include them.
public void doSomething(String name, int something) {
MyLib.enterMethod(ThisClass.class, new MethodSignature(void.class, String.class, int.class), new Argument("name", name), new Argument("something", something));
try {
// original code
} finally { // so we don't need to care about return in the middle of original code or exceptions
MyLib.exitMethod();
}
}
enterMethod would add invocation frame to some queue and exitMethod would remove last added frame. Note that you should have separate queue for each thread, use some Map<Thread, MyFrame> or ThreadLocal it might be good idea to use some weak references for threads.
And then you could use frames from that queue to create own stacktrace.
But doing something like that might decrease performance a lot - not even just because cost of this code, but adding that to every setter/getter might cause that methods to never be inlined and affect performance even more.
So it is possible but I really don't recommend doing something like that.
Also some other transformers added by other libraries might affect results, it might be good idea to also compare your stacktrace with original stacktrace to find any missing methods that you didn't transform - like native ones, and add them to your stacktrace but without that additional data.
If you really need to support native methods too - then you can create more advanced transformer that would add enterMethod/exitMethod before and after call to native method.
Also if this is only for debugging you could use debugging API so it would only work as a debugger.

Do I need to perfectly pair bindService / unbindService calls?

It appears from all the code examples that we only want to invoke #unbindService (on the same context), if we have invoked #bindService, which is accomplished via a boolean check.
But there are no similar checks in the #bindService call -- i.e. we do not check if we have already bound first to avoid "double binding".
So my questions --
"will bad things happen" if I bind a service multiple times but only unbind once, or it's only bad if i bind once and unbind multiple times? Such asymmetry seems weird to me but wanted to see if anyone knows the answer. I am playing with it now myself trying to figure it out but would prefer an "official" answer from more experienced devs.
What is considered a "bind" and "unbound" operation -- is it the fact that i have simply invoked the #bind (or #unbind) API, and those calls must be paired, OR is the bound/unbound state indicated by the #onServiceConnected/Disconnected callback that must be paired? Google's own examples seem to indicate the former is true, could anyone confirm? If former is true, then a final more subtle question: if #bindService returns false, i.e. android won't even attempt to connect as it couldn't resolve the service, in that case is it safe to invoke #unbindService?
Thank you.
I doubt that Android allows to bind to same service several times, but it makes no sense.
You bind to service and get a Messenger object. Next time you check, if messenger is null. If it isn't there is no need to bind again. Once your activity ends and the messenger is not null, you unbind.
The details are here.

Cancelling method calls when the same method is called multiple time

I think there's probably a name for what I'm describing here, but I don't know it. So my first question would be to know the name of this technique.
Here's an example: suppose you're implementing live search on a web page. Everytime the user types in the search box, you fire a new search query, and the results are updated as often as possible.
This is a stupid thing to do because you'll send much more queries than you actually need. Sending a request once per 2-3 letters or at most once per 100 ms is probably sufficient.
A technique is thus to schedule the queries to be executed soon after a key is typed, and if there are still queries that were planned but not executed, cancel them since they're obsolete now.
Now more specifically, are there specific patterns or librairies for solving this problem in Java ?
I had to solve the problem in a Swing app, and I used an ExecutorService, which returned ScheduledFutures that I could cancel. The problem is that I had to manually create a Runnable for each method call I wanted to "buffer", and keep track of each Future to cancel it.
I'm sure I'm not the first person to implement something like this, so there must be a reusable solution somewhere ? Possibly something in Spring with annotations and proxies ?
Given the other answers, and after some searching, it seems there's indeed no library that does what I wanted.
I created one and put it on GitHub. Future readers of this question may find it interesting.
https://github.com/ThomasGirard/JDebounce
I don't think it's very good yet but at least it works and can be used declaratively:
#Debounce(delayMilliseconds = 100)
public void debouncedMethod(int callID, DebounceTest callback) { }
This is not solvable in Java without using some extra infrastructure like you did with executor and futures. It is not possible to solve this in syntactically concise manner in Java.
You will always need some sort of method result wrapper, because the mechanism returns immediately but the actual result is retrieved later. In your case this was accomplished via Future.
You will always need to be able to specify code to be executed in a manner that will allow delayed execution. In most languages this is accomplished using function pointers or function values or closures. In Java, lacking these language features, this is usually accomplished by passing an object that implements some sort of interface such as Runnable, Callable, that allows delayed execution of a block of code. There are other options but none of them are simple, such as using a dynamic proxy.
tl;dr
Can't do this in concise manner in Java.
What you need is called debouncing. You should check the jQuery Throttle/Debounce plugin (which is btw totally independent of jQuery except for using the same namespace). What you need is covered by the debounce part:
Using jQuery throttle / debounce, you can pass a delay and function to
$.debounce to get a new function, that when called repetitively,
executes the original function just once per “bunch” of calls,
effectively coalescing multiple sequential calls into a single
execution at either the beginning or end.
Underscore.js has the same method:
_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function
which will postpone its execution until after wait milliseconds have
elapsed since the last time it was invoked. Useful for implementing
behavior that should only happen after the input has stopped arriving.
For example: rendering a preview of a Markdown comment, recalculating
a layout after the window has stopped being resized, and so on.
// example: debounce layout calculation on window resize
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
[Edit]
I mistakenly read "Javascript" instead of Java. Actual Java solution was written by OP afterwards.

In Java, how can I construct a "proxy wrapper" around an object which invokes a method upon changing a property?

I'm looking for something similar to the Proxy pattern or the Dynamic Proxy Classes, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like the Proxy class in Action Script 3 would be fine.
Here's what I want to achieve in general:
I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.
The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.
During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.
Edit: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.
If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by manipulations on the byte code level though.
Actually, the easiest way to do it is probably by using AspectJ and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe.
How does differential execution work?
Is a question I answered that deals with this.
However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed.
Obligitory links:
Wiki Differential execution
Wiki Callback
Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call.
I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change.
Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at.
Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion).
Hope that helps...
I don't want to intercept method calls before they are invoked on the real object, but
rather I'd like to intercept properties that are being changed
So in fact, the objects you want to monitor are no convenient beans but a resurgence of C structs. The only way that comes to my mind to do that is with the Field Access call in JVMTI.
I wanted to do the same thing myself. My solution was to use dynamic proxy wrappers using Javassist. I would generate a class that implements the same interface as the class of my target object, wrap my proxy class around original class, and delegate all method calls on proxy to the original, except setters which would also fire the PropertyChangeEvent.
Anyway I posted the full explanation and the code on my blog here:
http://clockwork-fig.blogspot.com/2010/11/javabean-property-change-listener-with.html

Categories

Resources