How do I create a new ForwardingCache? - java

I can't for the life of me figure out how to create a new ForwardingCache. I can see how I should create a Cache but not a ForwardingCache. What (obvious class) am I missing?
EDIT: I forgot to add that I need this forwarding so my listeners can be notified on a cache put. If there is a better way to perform post-put actions then please leave a comment/answer.

What you are missing is basic difference of Map and Cache in guava terminilogies. So, in guava Cache, you either provide a way to calculate a value if that is not there or do the stuff on preload.
See here http://code.google.com/p/guava-libraries/wiki/CachesExplained#Applicability
So, I dont think that your put case will arise or can't see how is that arising?
As for creating ForwadCache. if you can still see/explain further how you can use ForwadingCache, you can basically provide a concrete implementation of ForwardingCache.SimpleForwardingCache http://docs.guava-libraries.googlecode.com/git-history/v10.0.1/javadoc/index.html?com/google/common/cache/ForwardingCache.SimpleForwardingCache.html and the override delegate method, of course use Eventbus there.
But coming back to the original question again, you can very well see that there are removalListeners but no addListener on cache.
Just thinking loud you can use EventBus in case of CacheLoader or get operation itself (your compute logic when the value is not found).

As with all the other Guava Forwarding classes, you extend either ForwardingCache or ForwardingCache.SimpleForwardingCache, overriding the methods you want to intercept. The choice of which of those two you want to use depends on whether you want to provide your backing Cache implementation at construction time or through the delegate() method.

Related

Spring multiple HandlerMethodArgumentResolver per path

I have the following question. Is it possible to add multiple custom HandlerMethodArgumentResolver for different paths?
For example I want to a HandlerMethodArgumentResolver that does A for /myapi/someMapping1/ and a different one that does B for /myapi/someMapping2/.
I know that a similar behavior is possible for HandlerInterceptor but I would like to know if this is available for HandlerMethodArgumentResolver too.
Actually, after some research I could not find an out of the box implementation for this approach. In fact, after some consideration my use case example that I though was needing something like this, could be made simpler (thus negating the need for something like that).
Given though, that something like this is imperative, one can actually create a concrete implementation of HandlerMethodArgumentResolver in which the request can be injected.
With this in hand, the origin of the request can be inspected with the appropriate methods and both the supportsParameter and resolveArgument can be implemented accordingly.
Given though that a single API may expose information and actions regarding a specific resource I don't see the reason why something like this may be needed.

Know when value of any variable defined inside the class is changed

I have defined a class which acts like a model/pojo. The class has many keys/variable. I have implemented custom solution for storing the POJO on disk for future uses. Now what I want to do is that whenever any value in the class/POJO is changed, I should call a method which sync the fresh changes with file on disk.
I know I can define setter for each variable. But it's quite tedious to do for 100s of direct and sub fields, and even if I define setter for each field, I have to call sync function from all the setters.
What I need is single proxy setter or interceptor for all change pushes to variables in class.
I am using this in an android application, so whenever the user enters new details in his/her account I have to store those details at that specific instance of time for preventing the data loss. I am using GSON for serialising and de-serialising.
Sorry for using vague terminologies, never been to college :|.
The easiest solution is indeed to use a setter. You only have to create one for each field you want to monitor, and most IDEs generate them for you or you can use something like Koloboke, so it being tedious isn't really an argument.
A proxy class or reflection would also be possible, but that is pretty hacky. Another way would be an asynchronous watcher/worker that checks for changes in you POJO instances, but even that seems unnecessarily complicated.
Apart from that you might need to rethink your POJOs structure if it has that many fields.
The problem with persisting(in your case writting to a disk) entity on each property update is that most of the updates are modifying more then one property. So in case you have a code like this:
entity.setA(avalue);
entity.setb(bvalue);
entity.setc(cvalue);
You would write it to the disk 3 times, which is probably not a best way, as it takes more resources, and 2 out of 3 writes are unnecessary.
There are several ways to deal with it. Imagine you have some service for saving this data to a disk, lets name it entityRepository. So one option is manually call this entityRepository each time you want to save/update your entity. It seems to be very uncomfortable, comparing to calling this automatically on setter call, however, this approach clearly shows you when and why your entity is persisted/updated, in your approach it's unclear, and can lead to some problems future problems and mistakes, for example, in future you will decide that you now need to update one of the properties without immideately persisting, then it appears that you will need 2 setter, one with update, and one without...
Another way is to add version property, and when its setter is called inside this setter call entityRepository.save(this).
The other way is to look at AOP, however anyway I don't recommend persist entity on any change, without having control over it.
You are talking about data binding. There is no built-in way for that so you have indeed to sync it yourself. Look into How to Write a Property Change Listener. There are also lots of other approaches to this, but as said no built-in way.

JavaFx: Listener and/or binding handling

I was just wondering how JavaFx handles the listeners for an ObservableValue.
I have a few uncleared things about the Listeners in general:
How do javaFx handles multiple listeners on the same value? As I know I can add multiple listeners to the same obsValue, then what is the trigger order? Like in fifo?
What happens if I add the same listener(the same instance) twice to the same object, does is gets added twice? if yes then it triggers twice? Or i'm not sure how it works.
I know there are cases when I can replace listener with binding and vice versa, but which is more effective? Better to bind, or better to add a listener?
I am using the listeners and the bindings for a while so i know how to use them(at least I think I know :) ), then I'm not interested in how to use them, since I have to do some more complex listens or bindings I want to clarify some points like I wrote, to be sure I'm using them effectively, and I don't do any unnecessary memory leaks.
I would accept any explanations in this domain, or any good documentation, where I can find answers at leas for these points.
How do javaFx handles multiple listeners on the same value? As I know
I can add multiple listeners to the same obsValue, then what is the
trigger order? Like in fifo?
What happens if I add the same listener(the same instance) twice to
the same object, does is gets added twice? if yes then it triggers
twice? Or i'm not sure how it works.
Let us look at the documentation for one part of the answer:
ObservableValue<T>.addListener(ChangeListener<? super T> listener);
Adds a ChangeListener which will be notified whenever the value of
the ObservableValue changes.
If the same listener is added more than once, then it will be
notified more than once. That is, no check is made to ensure
uniqueness.
Note that the same actual ChangeListener instance may be safely
registered for different ObservableValues.
The bold section of the statement above tells us all we need to know, adding the same ChangeListener n times will cause it to be fired n times.
The ObservableValue interface does not specify any operations for checking if a ChangeListener already exists. You may be lucky and find an implementation does give you this mechanism, but really it is not of much use. To guarantee you are not adding a duplicate ChangeListener you can do the following:
ChangeListener<...> myListener = ...;
someProperty.removeListener(myListener);
someProperty.addListener(myListener);
In terms of the order executed the ObservableValue interface itself does not specify the order.
Looking at the standard Property classes included in the JavaFX library, e.g. SimpleDoubleProperty, they are fired off in the order added. It is difficult to explain quickly how this is achieved to the slightly complex mechanisms used by classes such as SimpleDoubleProperty. Look at the ExpressionHelper class for more detail on how this is done.
If you were to implement the ObservableValue interface yourself (although this is not advised by the Javadoc) you could specify your own order of execution.
I know there are cases when I can replace listener with binding and
vice versa, but which is more effective? Better to bind, or better to
add a listener?
Bindings are generally used when you want to bind Property<T> objects together, so for example if you bind propertyB to propertyA (i.e. propertyA.bind(propertyB)) then when propertyB is changed, propertyA will also change. Bindings can be bi-directional as well.
So, if you want a change to effect another Property using a bind makes sense. But note, that properties only reference a single other property through binding. To bind multiple properties you can daisy chain them like a link list (through their bindings) or by using a class that facilitates multiple bindings (e.g. DoubleBinding)
If the above is not the case, add a Listener.
Also see this resource: Using JavaFX Properties and Binding

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.

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