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

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.

Related

Manage data transfer in REST Architecture (Interface)

I'm working on my first client-server project and using REST.
So my question is where and how do I handle the data.
Options:
Define a datamodel and share it to the server and client. So I could you use JSON and object transfering, but each change of the datamodel requires also possible changes in the server and client implementation.
Simply transfer the data as basic data types (strings, boolean etc.). So only a datamodel is required in the client.
What do you recommend?
As you want to develop REST APIs and REST evolves around resource representations so first option (define data model) is way to go.
Note that all data model changes will not break the APIs and thus client implementations. Only when you re-structure your resource representation OR you take out one of attribute from model - that's when you will need to version your APIs.

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.

Transfering OWL data from client to server using GWT

I am working on a web application which is being developed using GWT. I am also using OWL ontologies and Jena framework to structure semantic contents in the application.
A simple function in the application would be getting some data from the user and send it to the servers side to be stored as a data graph using the ontology. I suppose one way would be to store the data as java class objects equivalent to the ontology classes and send them using the GWT async communication. To convert OWL classes to java, I used Jastor.
My question is that after the server receives the java class, is it possible to easily convert is to an OWL individual and add it to the data graph, using the functions of Jena and/or Jastor? For instance in the server side interface implementation we call something like this:
Public void StoreUser (User userObj) {
//User: a Jastor created java class. userObj is instantiated using the user data on the client side.
OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
//Open the ontology here using inputstream and ontModel.read!
Individual indiv = (Individual) userObj.resource();
//Add the individual to the model here! }
Unfortunately I wasn't able to find any Jena function that can add an existing individual to the model.
Would you suggest another way to pass the ontology data to server side and store it, rather than using Jastor created classes (for instance using an XML file)?
Thanks for your help
There are two parts to the answer. First, an Individual is a sub-class of a Jena Resource, which is definitely something that you can add to a model. However, individual resources, or properties or literals are not stored in a Model. A Model stores only triples, represented as Statement objects in the Java API. So to add some resource to a model, you have to include it in a triple.
In Jena, an individual is defined as a subject of a triple whose predicate is rdf:type and whose object is not one of the built-in language classes. So if you have:
ex:my_car rdf:type ex:Ferrari .
ex:Ferrari rdf:type owl:Class .
(note: this example is entirely fictitious!), then ex:my_car would be an individual, but ex:Ferrari would not (because OWL Class is a built-in type). So, to add your individual to your model, you just need to assert that it is of some type. Since I don't know GWT and don't use Jastor, I can't say whether the type association that is normally part of a Jena Individual is retained after serialization. I suspect not, in which case you'll need to have some other means of determining the type of the individual you want to add, or use a different predicate than rdf:type to add the resource to the the Model.
All that said, personally I probably wouldn't solve your problem this way at all. Typically, when I'm working with client-side representations of server-side RDF, I send just the minimal information (e.g. URI and label) to the client as JSON. If I need any more data on a given resource, I either send it along with the initial JSON serialization, or it's just an Ajax call away. But, as I say, I don't use GWT so that advice may not be of any use to you.

Can an API in SOAP/WSDL be kept backwards compatible easily?

When using an IPC library, it is important that it provides the possibility that both client and server can communicate even when their version of the API differs. As I'm considering using SOAP for our client/server application, I wonder whether a SOAP/WSDL solution can deal with API changes well.
For example:
Adding parameters to existing functions
Adding variables to existing structs that are used in existing functions
Removing functions
Removing parameters from existing functions
Removing variables from existing structs that are used in existing functions
Changing the type of a parameter used in an existing function
Changing the order of parameters in an existing function
Changing the order of composite parts in an existing struct
Renaming existing functions
Renaming parameters
Note: by "struct" I mean a composite type
As far as I know there is not such stuff as per the SOAP/WSDL standard. But tools exists to cope with such issues. For instance, in Glassfish you can specify XSL stylesheet to transform the request/response of a web service. Other solution such as Oracle SOA suite offer much more elaborated tools to manage versioning of web service and integration of component together. Message can be routed automatically to different version of a web service and/or transformed. You will need to check what your target infrastructure offers.
EDIT:
XML and XSD is more flexible regarding evolution of the schema than types and serialization in object-oriented languages. Some stuff can be made backward compatible by simply declaring them as optional, e.g.
Adding parameters to existing functions - if a parameter is optional, you get a null value if the client doesn't send it
Adding variables to existing structure that are used in existing functions - if the value is optional, you get null if the client doesn't provide it
Removing functions - no magic here
Removing parameters from existing functions - parameters sent by the client will be superfluous according to the new definition and will be omitted
Removing variables from existing structure that are used in existing functions - I don't know in this case
Changing the type of a parameter used in an existing function - that depends on the change. For a simple type the serialization/deserialization may still work, e.g. String to int.
Note that I'm not 100% sure of the list. But a few tests can show you what works and what doesn't. The point is that XML is sent over the wire, so it gives some flexibility.
It doesn't. You'll have to manage that manually somehow. Typically by creating a new interface as you introduce major/breaking changes.
More generally speaking, this is an architectural problem, rather than a technical one. Once an interface is published, you really need to think about how to handle changes.

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