using Gson library in GWT client code - java

I'm currently writing a web application in java using GWT 2.0 in eclipse.
I wanted to know if there is a way to use Gson library in a GWT application's client code.
and if there is a way - please tell me how...
Thanks!

Gson uses Java features that are not supported in GWT such as reflection. Thus it is not possible to use Gson in GWT client side code.

Not exactly what you wrote but I guess that what you meant was how to serialize/deserialize JSON in GWT code?
In GWT 2.1.1 you can use GWT AutoBean framework
See there at the bottom of the article it has this magic code ...
String serializeToJson(Person person)
{
// Retrieve the AutoBean controller
AutoBean<Person> bean = AutoBeanUtils.getAutoBean(person);
return AutoBeanCodex.encode(bean).getPayload();
}
Person deserializeFromJson(String json)
{
AutoBean<Person> bean = AutoBeanCodex.decode(myFactory, Person.class, json);
return bean.as();
}
the serializeToJson() woks fine for me even with instances that are inherit Person but I did not try the deserializeFromJson...

(feel free to enhance my post if you like)
currently (2015-02-07) it is not possible although I like Gson very much and would like to have only one solution for shared code :-/ , but there are some other libraries available (I only know AutoBeans and Gson myself and had a quick look at Piriti):
(some support both or only one of XML and JSON (de)serialization)
client- and server-side
AutoBeans (*): http://code.google.com/p/google-web-toolkit/wiki/AutoBean
I had problems with generics there (2015-02-07) similar to this: RequestFactory: Proxy implementing interface with generics
client-side-only
Piriti
RestyGWT: http://restygwt.fusesource.org/documentation/restygwt-user-guide.html#JSON_Encoder_Decoders
RocketGWT: http://code.google.com/p/rocket-gwt/wiki/JsonSerialization
Acris: http://code.google.com/p/acris/wiki/GWTJsonizer
JavaScript overlay types (*)
server-side only
Gson (from Google)
(*) from GWT project itself
Comparisons:
e.g. https://github.com/hpehl/piriti/wiki/Comparison

In our GWT project we use piriti:
http://code.google.com/p/piriti/
Works like a charm :-)

I have write a library that allows using GWT with Gson, you can download here and enjoy it.

Related

Writing an XML SOAP message in Java

I have the following method that accepts xml and I do some data feeding with the content.
I am supposed to return a SOAP message as well, something along these lines:
<ow-e:Envelope revision='2.0' xmlns:ow-e='http://www.url.com/test-envelope'>
<ow-e:Header>
<ow-e:Properties>
<ow-e:SentAt>2004-12-14T13:54:36</ow-e:SentAt>
<ow-e:Topic>SOME_STRING</ow-e:Topic>
</ow-e:Properties>
</ow-e:Header>
</ow-e:Envelope>
So right now what I am doing is the following:
String some_string = "qwe";
String response = "";
response = "<ow-e:Envelope revision='2.0' xmlns:ow-e='http://www.url.com/test-envelope'><ow-e:Header><ow-e:Properties><ow-e:SentAt>2004-12-14T13:54:36</ow-e:SentAt><ow-e:Topic>" + some_string + "</ow-e:Topic></ow-e:Properties></ow-e:Header></ow-e:Envelope>";
return response;
Which is absolutely terrible. Any idea how I can actually make it more bearable? Using a framework is not an option at the moment.
This is the first time I am dealing with SOAP messages/responses and it feels like hell coming from REST. I probably need to create some kind of hierarchy to populate the values correctly, but I am not sure how it can be done just by using Java without any frameworks.
You mentioned using frameworks is not an option, but something more lightweight may be available in your platform:
JAXB. JAXB allows you to map Java classes to XML representations using annotations. It's far better than doing marshaling and unmarshaling by hand or by concatenating or parsing strings. With properly structured and annotated POJOs, JAXB can handle things for you. You might even be able to cheat and use xjc with your WSDL file to create annotated classes with the -wsdl option (experimental though).
SAAJ. Bluntly put, SAAJ is just like a specific builder and parser for SOAP messages. It will handle the structure and namespaces for you. Speaking of which...
... the example you are showing isn't really valid SOAP message. SOAP is a protocol. You need to properly format it and use the right namespaces otherwise you are just returning some XML messages that look like SOAP, but aren't.

How do I load an EDMX schema file in Java with OLingo 4?

I have a large edmx schema file that would be very inconvenient to manually re-create, one EntityType at a time, in Java using OLingo. While I'm not opposed to writing a loader of some kind, I wanted to make sure that OLingo 4 doesn't already provide this functionality.
I found an article that shows how OLingo 2 can load this kind of information:
#Override
public Edm readMetadata(final InputStream inputStream, final boolean validate)
throws EntityProviderException {
EdmProvider provider = new EdmxProvider().parse(inputStream, validate);
return new EdmImplProv(provider);
}
But I need to use version 4. I haven't found the same interfaces in the documentation for version 4, so I'm at a bit of a loss. Any pointers much appreciated.
After more investigation, I found that I needed the odata-server-core-ext package and I could import org.apache.olingo.server.core.MetadataParser. Among other things, this class has a function called buildEdmProvider(Reader) which does the work of building a SchemaBasedEdmProvider for you.
If you're not bound to OLingo, you could also try odata-client: https://github.com/davidmoten/odata-client
I've not had a good chance to use it myself as unfortunately the web service I'm trying to connect to is OData 2, and odata-client only supports 4. However, it looked to have some neat features (including type safety and automatic/transparent paging).

Preserve Generics when generating JSON schema

I'm using jackson-module-jsonSchema and jsonschema2pojo API.
Brief explanation: I'm trying to json-schemify my server's Spring controller contract objects (objects that the controllers return and objects that they accept as parameters) and package them up to use with a packaged retrofit client in order to break the binary dependency between the client and server. The overall solution uses an annotation processor to read the Spring annotations on the controller and generate a retrofit client.
I've got it mostly working, but realized today I've got a problem where generic objects are part of the contract, e.g.
public class SomeContractObject<T> {
...
}
Of course, when I generate the schema for said object, the generic types aren't directly supported. So when I send it through the jsonschema2pojo api I end up with a class like so:
public class SomeContractObject {
}
So my question is simple but may have a non-trivial answer: Is there any way to pass that information through via the json schema to jsonschema2pojo?

How to use Couchbase Java Client in a Dropwizard Project?

I've been looking at the couchbase-java-client project and wondering whether it's possible to use it inside of a dropwizard project.
It seems like it'd be a natural fit, because couchbase is basically a JSON database, but the java client doesn't seem to be compatible with Jackson. As far as I can tell, the couchbase client library includes its own internal implementation of a JSON library that's incompatible with all the other java JSON libs out there, which is really weird.
I found a JacksonTransformers class that looked promising at first. But upon closer inspection, the library is using a shaded version of Jackson (with a rewritten package of com.couchbase.client.deps.com.fasterxml.jackson.core).
Anyhow, since dropwizard uses Jackson and Jersey for marshalling JSON documents through the REST API, what's the least-friction way of using the couchbase-java-client library? Is it even possible in this case?
It is definitely possible to use Couchbase with Dropwizard. The client SDK provides JSON manipulation objects for the developer's convenience but it also allows for delegating JSON processing to a library like Jackson or GSON.
Take a look at the RawJsonDocument class here.
Basically, you can use a Stringified JSON (coming out of any framework) to create one of those objects and the client SDK will understand it as a JSON document for any operation i.e.:
String content = "{\"hello\": \"couchbase\", \"active\": true}";
bucket.upsert(RawJsonDocument.create("rawJsonDoc", content));
It should be possible to make this work.
Client requests to dw server for Resource Person.
DW server requests to couchebase, gets a Pojo back representing Person or JSON representing person.
If it's JSON, create a POJO with Jackson annotations in DW and return that to client
If it's a special couchebase pojo, map that to a Jackson pojo and return to to client
A solution based on #CamiloCrespo answer:
public static Document<String> toDocument(String id, Object value,
ObjectMapper mapper) throws JsonProcessingException {
return RawJsonDocument.create(id, mapper.writeValueAsString(value));
}
Keep in mind, that you can't use a simply maper, like ObjectMapper mapper = new ObjectMapper(), with Dropwizard.
You can get it from Environment#getObjectMapper() in the Application#run() method, or use Jackson.newObjectMapper() for tests.
An example of using:
ObjectMapper mapper = Jackson.newObjectMapper();
User user = User.createByLoginAndName("login", "name");
bucket.insert(toDocument("123", user, mapper));

how to "toString()" GWT EntityProxy derivatives for logging and debugging?

GWT 2.1.1 has very good framework - RequestFactory with all the EntityProxy and stuff.
I am looking for a way to serialize runtime instances that implement EntityProxy for debugging and logging etc. I do not care for format as long as it human readable.
To be more specific I would like to have something like the provided by Apache Commons Lang
ReflectionToStringBuilder
May be there is some way to use the JSON serialization mechanics that GWT has inside? if yes how to make it a bit more readable?
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
String stringRep = ReflectionToStringBuilder.toString(this);
There are at least 2 solutions:
First: Based on the idea by Thomas Broyer
public static String toString(EntityProxy entityProxy)
{
DefaultProxyStore store = new DefaultProxyStore();
Swap.requestFactory.getSerializer(store).serialize(entityProxy);
return store.encode();
}
Which produce something like this:
{"V":"211","P":{"1#2#biz.daich.swap.shared.dto.UserAccountProxy":{"O":"PERSIST","R":"2","Y":1,"T":"biz.daich.swap.shared.dto.UserAccountProxy","P":{"id":null,"items":null,"channelId":null,"lastActive":1296194777916,"name":null,"emailAddress":"test#example.com","lastReported":1296194777916,"lastLoginOn":1296194777916}}}}
Second: Based on the AutoBean framework
public static String toJson(EntityProxy entityProxy)
{
return AutoBeanCodex.encode(AutoBeanUtils.getAutoBean(entityProxy)).getPayload();
}
Which produce string like
{"emailAddress":"test#example.com","lastActive":1296194777916,"lastLoginOn":1296194777916,"lastReported":1296194777916}
The second is just what I need - it more readable in log.
I haven't tried it but have a look at RequestFactory#getSerializer, there's some sample code in the javadoc for the ProxySerializer.
If using the method
toJson(EntityProxy entityProxy)
change this to
toJson(BaseProxy proxy)
and then you can log Value and Entity Proxy objects.

Categories