Patterns for propagating changes to nested objects - java

I am implementing a game/application where the player's account/state is synced to the server. I am contemplating a general framework communicating modifications of nested objects of an entity (the entity being the users's account). Let us assume for discussions of computation/reflection that both the client and server are written in Java (in reality client is in Actionscript which can modify properties dynamically)
Take for instance Firebase. Modifications to any object of the root object (a Firebase object) are propagated with a request that probably looks something like:
Service: PersistenceService
Action: modifiedObjects
Body:
Objects [{"/full/Path/To/Object/1","newValue"},{"/full/Path/to/Object/2","newValue"}]
My request for your input is the following:
1) Please correct and/or augment the following thoughts on implementing this general framework for propagating modifications to a tree of objects.
On the sending side, it would appear that every object either:
1) Needs to store it's full path from the root entity
2) Changes to properties of all nested objects need to be done reflectively
OR
A sync needs to forced, comparing the entity's saved object tree from the last request to the current object tree for modifications.
On the server side, one can analyze the paths of the objects to cache objects that are accessed multiple times in one request so as not to access the tree by reference/search collections multiple times.

The answer I have come up with is actually very obvious the obviously the best way to do it. The answer is to mirror a database of tables. Assign each object an id, and store every object in an ArrayList (or assign each object a unique ID based on type and store the object in its type's ArrayList which is itself stored in a HashMap).
I call my interfaces ServiceObject and ServiceContainer.
Now the only thing I have to see that works is how json and protostuff serialize dual references to objects. Are they serialized as seperate objects? If so, than I any nested ServiceObject's need to deserialized as references to the objects in the ArrayList.

Generally observer pattern is answer to kind of requirement you have (from wiki)
The observer pattern (aka. Dependents, publish/subscribe) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
You need implementation on the client server hence example given on the wiki is not applicable you might want to check this :
http://deepintojee.wordpress.com/2011/03/18/observer-pattern-applied-at-remote-level/

Related

How to save variable value across different REST api call using Java core

I have a requirement to hold user list inmemory. The state of user list should maintain across different REST api calls. Like there is an api to save user, so whenever i call save, user saved in variable and will be available in anothee REST api get call.
How can i achieve this? I am thinking of some singleton class to hold data as singleton scope is at JVM level
REST architecture which means Representational State transfer which means you do not store the state of the object (or resource) in REST terms.
Every API hit is (and should be) considered a new resource manipulation call. For e.g. You may be Creating a resource (POST) , deleting a resource (DELETE) , updating a resource (PUT) and so on...
You may still want to access a resource's state i.e. in your case userlist which you may somehow update and get from database or file or temporary storage. Database would be preferred.
Your question inclines more towards maintaining sessions which is in contrary to REST API principles
I'd suggest you to go through basic principles of REST API architecture ( Precisely 6 of them)
https://restfulapi.net/

Proxy pattern concrete class hiding implementation details

I have been reading about java proxy pattern and invocation handler and everywhere it is seen that the concrete class construction is available to the client.
For example,
//TwitterService service = (TwitterService) SecurityProxy.newInstance(new TwitterStub());
TwitterService service = new TwitterStub();
System.out.println(service.getTimelinePosts("abc"));
User can create an instance of TwitterStub directly and access the methods. I was wondering if there was a way of not exposing the or avoiding the construction of the concrete class via the client ?
Is there a better way ?
As the GoF puts it, the intent of the proxy pattern is "to provide a surrogate or placeholder for another object to control access to it".
So, in your specific case what happens is that you're creating a particular proxy instance directly. And that's fine as long as you (as a client) know that you want a particular type of proxy object.
If what you want is a level of indirection, you can use an Abstract Factory Pattern that return different types of proxy objects. But so far, the reason of proxy objects is to act on behalf of other objects.
As a side note, proxies are useful when you have objects that are expensive to create, but you don't want to necessarily cripple main application function due to such expense. For example, suppose you have a document with 1000 images. You can use proxies for them, and only load them when stricly needed (i.e. when they are in visible view), and you can still load the full document really fast without the overhead of reading 1000 images at once.

Spring REST representation class

I'm reading the two introductory articles about bulding and consuming Spring Rest web services.
What's weird - they're creating a Greeting representation class in the client app (second link ref) for storing the GET response (the greetingmethod on server side returns a Greeting object). But the Greeting classes on the server and client side are different classes - well, they are two distinct classes with identical names, identical field names and types (client's doesn't have a constructor).
Does it mean I have to similarly rewrite the class from stratch when building the client app? In order to do that, I'd need specs on what are the fields' types of JSON-packed objects passed by server's app. A server serializes the object of class ABCClass to JSON and sends it to client. Even if some field called 'abc' has value 10, it doesn't make it an integer. Next time it might contain a string.
My question is - how much information from server app's devs do I need in order to create a client application? How is it usually done?
It all depends on your deserializer and on your needs. With Jackson for example you might use mixins (wiki ref) and custom deserializers (wiki ref) that build your object with your required field names and your structure.
Its just simplest way to have same field names and structure, but not the only one.
Of course, however, you should know the server reply structure to deserialize it anyway

State Design Pattern Implementation

I am trying to apply the State Design Pattern to an instant messenger program that I am building. The program is built on top of an existing instant messenger API. I am essentially creating a wrapper class to simplify the process of sending a message. (The wrapper class is going to be used by several automated scripts to fire off messages when some event occurs.)
Here is what I have so far:
A Messenger class that will serve as the client interface and hold a reference to the current state.
An AbstractMessengerState class from which all of the concrete states will inherit.
Several concrete State classes representing the various states (e.g. SessionStarted, LoggedIn, LoggedOut, etc.)
The problem I am having is where to store the state data. That is, which class(es) should store the fields that I need to carry out the business logic of the messenger program. For example, I have a Map data structure that maps userIDs (strings) to the objects used by the underlying API. I have a Session object that is used to access various messenging components and to log in and out of the messenger server. These objects need to be shared between all the subclasses.
If I store this data in the base class than I will be duplicating data every time I instantiate a new State. Is there a way to ensure that the data in the base class is accessible by the subclasses without duplicating the fields?
UPDATED
Ok, after reading a related post I am going to try to store everything in the Context (Messenger) class and see how that goes.

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