Is it possible to use GWT EntityProxy WITH RPC calls? - gwt

I was reading about this EntityProxy feature in GWT 2.1+ and was wondering if you can use this proxy mechanism to avoid having to create DTOs and combine with regular RPC calls?
I have a command pattern which uses RPC mechanism, but as everybody knows, most of the time you have to round trip complex objects. But you usually end up coding a DTO which is usually a copy of your server side persistent object.
So can EntityProxy help you in this matter?
Thanks

EntityProxy is part of the RequestFactory system and cannot be used with GWT-RPC. The purpose of EntityProxy (and ValueProxy) is to avoid the need to code an entire DTO and all of the glue code that entails. The Request objects used by RequestFactory roughly approximate a command pattern, since multiple Request objects can be queued within a single RequestContext and evaluated with a single round-trip to the server.

Related

Gwt-rpc usage DAO only. Get rid of DTO

I am about to start new java project and I consider GWT as my framework for it.
I've checked a lot of articles on the internet (main documentation also) and I am quite confused.
So I ask You:
Can I use jpa Entities to work with DAO, and to be sended over network to client?
I really don't understand the concept of DTO (writing almost the same but more poor class of Model)
If I will about to send Entities over network to client, how to use Serializable Transient annotation to NOT serialize and send methods, parameters of class? Is it even possible?
How all of this will work with Generic Typed Superclass extended by right class implementation?
f.e:
public class GenericModel extends GenericModel<T> {
//some generic code
}
public class RightModel extends GenericModel<RightModel> {
// some right class code
}
the same goes with DAO...
Please help.
I count on Yours experience.
Not that I was an expert at that time but when I started to combine Hibernate (not JPA as such) and GWT, it was a pain.
The reason that you can't just send over Hibernate managed objects (and I guess same counts for JPA, regardless of the underlying technology), is that they contain bytecode-manipulation stuff like javassist. GWT doesn't like this at all, and you can't send those objects over the GWT RPC wire.
Ofcourse also it doesn't make sense: you can't expect your Javascript (client-side) to invoke SQL to lazy-load collections when you invoke a getter on your DAO (because that's what happens server-side with these DAO objects, that's what the javassist magic is doing behind your back).
I'm not sure that even if all collections were eagerly loaded, your objects would be free of javassist stuff, and could be serialized over GWT-RPC. That leaves you with one alternative, which is to have POJO objects tailor-made to contain only those parts (properties/collections) that you need on the client at that moment - the DTO.
Since then a lot has happened in GWT, and I know of something completely different from RPC, which is RequestFactory (see http://www.gwtproject.org/doc/latest/DevGuideRequestFactory.html). I haven't used that myself, but it claims to make it easy to build data-oriented (CRUD) apps with an ORM-like interface on the client. So this may be the way to go if you don't want to build custom classes for wiring RPC.

Functional programming equivalents for the following [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make the leap from functional programs for "hello world" equivalents to more real-world applications.
As I come from a Java world and have been exposed to all it's design patterns, my modeling process is still very Java oriented (e.g. I think in terms of *Managers, *Factory, *ClientFactory, *Handler etc.)
Changing my thought process in one shot, will be hard so I was hoping to get some pointers on how the following scenarios (described in a OO way) would be modeled in a functional language.
Examples in a functional language like Clojure/Haskell (or perhaps a hybrid like Scala) would be helpful.
Stateless Request handlers
E.g. is a Servlet. It is essentially a request handler with methods like doGet, doPost. How would one model such a class in a functional language?
Orchestrator classes
Such classes don't do anything by themselves, but just orchestrate the whole process or workflow. They offer multiple entry point APIs.
E.g. A OrderOrchestrator orchestrates a multiple step workflow starting with payment instrument validation, shopping cart management, payment, shipment initiation etc.
They might maintain some internal state of their own that is used by the different steps like payment, shipment etc.
ClientFactory pattern
Let's say you have written a client that for a LogService that is used by your client to log traffic data about their services. The client logs the data in S3 under buckets and accounts managed by you and you provide additional services like reporting and analytics on this data.
You don't want your customer to worry about providing the configuration information like AWS account info etc and hence you provide a ClientFactory that instantiates the appropriate client object based on whether this is for testing or production purposes without requiring the customer to provide any configuration. E.g. LogServiceClientFactory.getProdInstance() or LogServiceClientFactory.getTestInstance().
How is such a client modeled in a functional language?
Builder Pattern and other Fluent API designs
Client libraries often provide Builders to create objects with complex configuration. Sometimes APIs are also fluent to make it easy to create. An example of Fluent API is Mockito APIs : Mockito.when(A.get()).thenReturn(a) IIRC this is internally implemented by returning progressively restrictive Builders to allow the developer to write this code.
Is this a parallel to this in the functional programming world?
Datastore instances
Let's say that your codebase uses data stored in a ActiveUserRegistry from multiple places. You want only 1 instance of this registry to exist and have the entire code base access this registry. So you provide a ActiveUserRegistry.getInstance() that guarantees that all the code base accesses the instance (Assume that the instance is thread-safe etc.)
How is this managed in a functional setting? Do we have to make sure the same instance is passed around in the entire codebase?
Below is something to get started:
Stateless Request handlers
Clojure: Protocols
Haskell: Type classes
Orchestrator classes
State monad
ClientFactory pattern
LogServiceClientFactory is a Module and getProdInstance and getTestInstance being the functions in the module.
Builder Pattern and other Fluent API designs
Function composition
Datastore instances
Clojure: Function that uses an atom (to store and use the single instance)
Haskell: TVar,MVar
I'm not vary familiar with the many of these Java-style structures, but I'll take a stab at answering:
Stateless Request handlers
These exist in the functional world as well. Functions can fill this role easily, even with something as simple as a function from requests to responses. The Play Framework uses something more powerful, specifically a function from the Request to an Iteratee (type (RequestHeader) ⇒ Iteratee[Array[Byte], SimpleResult]). The Iteratee is an entity that can progressively consume input (Array[Byte]) as it is received and eventually produce the response (SimpleResult) to give back to the client. The request handler function is stateless and can be reused. The Iteratee is also stateless - the result of feeding it each chunk is actually to get a new Iteratee back, which is then fed the next chunk. (I'm oversimplifying really, it uses Futures, is entirely non-blocking, and has effective error handling - worth looking at to get a feel of the power and simplicity that functional-style code can bring to this problem).
Orchestrator classes
I'm not familiar with this pattern, so forgive me if this makes no sense. Having one giant mutable object that gets passed around is an anti-pattern. In functional code, there would be separate datatypes to represent the data that needs to passed between each stage of the process. These datatypes would be immutable.
As for things that organize other things, look at Akka and how one actor can monitor other actors underneath it, handling errors or restarting them as needed.
Builder Pattern and other Fluent API designs
Functional program has these and takes them to their logical conclusion. Functional code allows for very powerful DSLs. As for an example, check out a parser combinator library, either the one in the Scala standard library or one of the libraries for Haskell.
ClientFactory pattern and Datastore instances
I don't think this is any different in functional code. Either you have a singleton, or you do proper dependency injection. The Factory pattern is used in functional code as well, though first-class functions make many design patterns too trivial to be worth naming (from the GoF: Factory, Factory method, Command, and at least some instances of Strategy and Template can usually just be functions).
Have a look at Functional Programming Patterns in Scala and Clojure: http://pragprog.com/book/mbfpp/functional-programming-patterns-in-scala-and-clojure .
It should exactly have what you need.

What are the differences of using value proxies for my entities instead of entity proxies?

So far i understand that i will have no more need to define an #version field in my entitites and no more need to use an entity locator. And for value proxies i will have to usenormal editors. Any other diffrences, advantages, disadvantages? What about in the context of using request factory in conjunction with spring
The main difference is that with EntityProxy, the client can send a diff of changes rather than the entire object graph. This is made possible because EntityProxys have an identity, so the server can fetch the identity from the datastore and then apply the diff/patch sent from the client, and only then the entity will be passed to your service methods.
With ValueProxy you basically have an equivalent of GWT-RPC: the object is reconstructed from scratch on the server, and not associated with your datastore (in the case of JPA for instance, it's not attached to the session). Depending on your datastore API, this can make things more complex to handle in your service methods.
Other than that, you'll also lose the EntityProxyChange events.

Java Rest Client consuming JSON - how to create JAXB objects?

I need to write a rest client (in Java - using RestEasy) that can consume JSON responses. Regarding the need for the rest client (or wrapping service) to translate the JSON responses to a Java type, I see the following options:
1. map the response to a string and then use JsonParser tools to extract data and build types manually.
2. Use JAXB annotated POJOs - in conjunction with jackson - to automatically bind the json response to an object.
Regarding 2, is it desirable / correct to define an XSD to generate the JAXB annotated POJOs? I can advantages to doing this using, e.g. reuse by an XML client.
Thanks.
I'm a fan of #2.
The reasoning is that your JAXB annotated model objects essentially are the contract for the business/domain logic that you're trying to represent on a transport level, and POJOs obviously give you excellent control over getter/setter validation, and you can control your element names and namespaces with fine granularity.
With that said, I like having an additional "inner" model of POJOs (if necessary, depending on problem complexity/project scope) to isolate the transport layer from the domain objects. Also, you get a nice warm feeling that you're not directly tied to your transport layer if things need to change internally in your business/domain object representation. A co-worker mentioned Dozer, a tool for mapping beans to beans, but I have no direct experience with it to comment further.
I'm not a fan of generating code from XSDs. Often the code is ugly or downright unreadable; and managing change, however subtle or insignificant can introduce unexpected results. Maybe I'm wrong about that but I require good unit-tests on a proven model.
This is based on my personal experience writing a customer-facing SDK with a hairy XML-over-HTTP (we don't call it REST) API. JAXB/Jackson annotated POJOs made it relatively painless. Hope that helps.

Sending persisted JDO instances over GWT-RPC

I've just started learning Google Web Toolkit and finished writing the Stock Watcher tutorial app.
Is my thinking correct that if one wants to persist a business object (like a Stock) using JDO and send it back and forth to/from the client over RPC then one has to create two separate classes for that object: One with the JDO annotations for persisting it on the server and another which is serialisable and used over RPC?
I notice the Stock Watcher has separate classes and I can theorise why:
Otherwise the gwt compiler would try
to generate javascript for everything
the persisted class referenced like
JDO and com.google.blah.users.User, etc
Also there may be logic on the server-side
class which doesn't apply to the client
and vice-versa.
I just want to make sure I'm understanding this correctly. I don't want to have to create two versions of all my business object classes which I want to use over RPC if I don't have to.
The short answer is: you don't need to create duplicate classes.
I recommend that you take a look from the following google groups discussion on the gwt-contributors list:
http://groups.google.com/group/google-web-toolkit-contributors/browse_thread/thread/3c768d8d33bfb1dc/5a38aa812c0ac52b
Here is an interesting excerpt:
If this is all you're interested in, I
described a way to make GAE and
GWT-RPC work together "out of the
box". Just declare your entities as:
#PersistenceCapable(identityType =
IdentityType.APPLICATION, detachable
= "false") public class MyPojo implements Serializable { }
and everything will work, but you'll
have to manually deal with
re-attachment when sending objects
from the client back to the server.
You can use this option, and you will not need a mirror (DTO) class.
You can also try gilead (former hibernate4gwt), which takes care of some details within the problems of serializing enhanced objects.
Your assessment is correct. JDO replaces instances of Collections with their own implementations, in order to sniff when the object graph changes, I suppose. These implementations are not known by the GWT compiler, so it will not be able to serialize them. This happens often for classes that are composed of otherwise GWT compliant types, but with JDO annotations, especially if some of the object properties are Collections.
For a detailed explanation and a workaround, check out this pretty influential essay on the topic: http://timepedia.blogspot.com/2009/04/google-appengine-and-gwt-now-marriage.html
I finally found a solution. Don't change your object at all, but for the listing do it this way:
List<YourCustomObject> secureList=(List<YourCustomObject>)pm.newQuery(query).execute();
return new ArrayList<YourCustomObject>(secureList);
The actual problem is not in Serializing the Object... the problem is to Serialize the Collection class which is implemented by Google and is not allowed to Serialize out.
You do not have to create two versions of the domain model.
Here are two tips:
Use a String encoded key, not the Appengine Key class.
pojo = pm.detachCopy(pojo)
...will remove all the JDO enhancements.
You don't have to create separate instances at all, in fact you're better off not doing it. Your JDO objects should be plain POJOs anyway, and should never contain business logic. That's for your business layer, not your persistent objects themselves.
All you need to do is include the source for the annotations you are using and GWT should compile your class just fine. Also, you want to avoid using libraries that GWT can't compile (like things that use reflection, etc.), but in all the projects I've done this has never been a problem.
I think that a better format to send objects through GWT is through JSON. In this case from the server a JSON string would be sent which would then have to be parsed in the client. The advantage is that the final Javascript which is rendered in the browser has a smaller size. thus causing the page to load faster.
Secondly to send objects through GWT, the objects should be serializable. This may not be the case for all objects
Thirdly GWT has inbuilt functions to handle JSON... so no issues on the client end