Do I need to perfectly pair bindService / unbindService calls? - java

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.

Related

Spring StateMachine How do I know if a transistion is rejected due to failed guard or action?

I have the same question as in the topic below, but I'm not so sure if my approach is wrong.
How do I know if a guard rejected a transistion
My app is a linear step-by-step strategy board game with several different game settings. I've decided to use Spring StateMachine to solve as in my opinion (and so far) it solves a lot little code-related organisational problems But now I'm stacked
The problem I have run into is that I can't say if my event passed all the guards and transition occurs. I just get true-flag when an event is added to the queue
The approach I'm following is passing data via event-context, validation of one with guards and apply changes using actions
transitions
.withExternal().source(SPEECHES).target(VOTING).event(VOTING_EVENT)
.guard(Guard.and(
guards.get(NoVotesFromSuspectedGuard.QUALIFIER),
guards.get(NoSelfVotingGuard.QUALIFIER),
guards.get(NoDeadParticipantsVotingGuard.QUALIFIER),
guards.get(NoVotingForDeadParticipantsGuard.QUALIFIER),
votingOutOfParticipantListGuardFactory.get(NUMBER_OF_PLAYERS),
guards.get(VotingBasedOnPreviousOneGuard.QUALIFIER)
))
.action(actions.get(CalculateVotingAction.QUALIFIER))
As I understand now, there is no possibility to notify event-supplier about failed guard evaluation. If so, just let me know and I will switch to another SM implementation. But if there is any possibility of solving my problem, please help me.
The behaviour I expect is any meta info of failed guard (to build formatted error message)
You can use some context flag, for example context.put("NoVotesFromSuspectedGuard", false) when "NoVotesFromSuspectedGuard" isn't success and then you can check this variable in your invoke code context.getExternalVariables().get("NoVotesFromSuspectedGuard", Boolean.class).
Also, in Spring State Machine you can declare ActionListener bean, which contains some different methods for StateMachine events monitoring.
For more information, you can see Habr(Russian)

Zuul filter return value

What is the possible usage of ZuulFilter.run() return value?
All the examples (for instance Spring example) return null.
The official documentation says:
Some arbitrary artifact may be returned. Current implementation ignores it.
So why to have it at all?
I've used this lib in multiple projects and I never thought to look into and stumbled upon this question so I had to look. Just tracing the code in IntelliJ, it does look like the results are pointless.
I'm on zuul-core:1.3.1:
Looking at FilterProcessor, when the routing methods are called to route based on the type, they all call runFilters(sType) which ultimately get the the return Object in question of the implementing IZuulFilter classes. The trail seems to stop here.
I then stopped to looked at their test classes and nothing seems to do anything with the return Object either nor the ZuulFilterResult that wraps it.
I then thought, ok, well maybe there is a way to pass data from one IZuulFilter to another (e.g. from pre to route) but that doesn't seem possible either since FilterProcessor.processZuulFilter(ZuulFilter) doesn't do anything with the results and just passes it back to runFilters(sType) which we know ignores it.
My next line of questioning was, "well, perhaps you can provide your own FilterProcessor implementation and swap it out and actually use the Object somewhere". But alas, it looks like that isn't the case either unless you want/need to implement a lot more even into the ZuulServlet?
Lastly, I thought, "well, maybe it's just a convention thing". But java.lang.Runnable.run() is void and javax.servlet.Filter.doFilter is also void.
So for now, my best guess is that like all of us at some point in our careers, we sometimes fall into a YAGNI situation; perhaps this is just one example.

Tracking Parse notification consumption

Recently we switched our push notification system over to Parse.com, but I'm having ridiculous trouble integrating our client on several ends.
These are the two requirements, yet it seems impossible to implement them together:
There are several different types of notifications (different sounds based on type, or icons, etc.) that need to be used depending on the state of the client and the notification received. Therefor I need the option of a custom NotificationBuilder.
I need to track the consumption of the notification.
Their documentation states that if you want to handle everything yourself, all you have to do is add one line when the internal Parse OPEN event is broadcasted:
ParseAnalytics.trackAppOpened(getIntent());
Ha! If only that worked.
By preventing the internal Parse helper from receiving the RECEIVE event (by overriding the onPushReceive() method of the ParsePushBroadcastReceiver), it appears to remove any link between the data pushed to the device and the Parse service running on it (which makes sense why that would be, since it never reached the starting point in the first place). And no, calling the super version is not an option, as it would cause Parse to display its version of a notification since there will be an alert/title key that I have no control over.
I figured, what the hell, might as well try to put the tracking method call in the Activity that is called by the popup (whose Intent does contain all the data originally passed to it). Still, no effect, reaffirming my belief that intercepting the event is preventing the local Parse system from knowing there's a notification to consume, therefor preventing its consumption from being tracked.
So, the question is, does anyone know how to get Parse to use a custom NotificationBuilder so that the events it requires can actually be triggered correctly, allowing me to actually track notification consumption?
Or any kind of solution that enables me to use a custom notification, while still triggering the appropriate events to be tracked?
Possibly some way to save the push_hash and manually send the API call to whatever endpoint handles consumption?
Quite literally pulled some hair out over this one today and would appreciate any help I can get...
Thanks, everyone!

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.

Can java access global events created using CreateEvent

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.

Categories

Resources