I have the following use case. I need to transfer an XText model instance via the network in some serialized format. For this purpose I need to serialize the model on the client side, send it as the body of some kind of POST request and deserialize it on the server side.
At the time I issue the send request I do only have access to the object structure of my model. I do not have the files I created the model from any more (it would be possible, but it would destroy the cleanliness of my architecture and makes testing very complex).
I created the following code for serializing the model based on some threads here on StackOverflow and tutorials available via other Websites to serialize an XText-Model
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap( ).put("xtextbin", new XMIResourceFactoryImpl());
Injector injector = Guice.createInjector(new ScenarioRuntimeModule());
Serializer serializer = injector.getInstance(Serializer.class);
System.out.println(serializer.serialize(scenario));
However it does not work and I get the following error:
com.google.inject.CreationException: Guice creation errors:
1) Error injecting constructor, org.eclipse.emf.common.util.WrappedException: org.eclipse.emf.ecore.resource.impl.ResourceSetImpl$1DiagnosticWrappedException: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Ungültiges Byte 1 von 1-Byte-UTF-8-Sequenz.
The problem most likely lies with the XMIResourceFactoryImpl, which I do not know how to use properly.
Another approach might be to use:
String serializedScenario = ModelUtils.serialize(scenario);
But I do not know how to deserialize the result of this serialize call.
My question however is more basic, since the code above might be a completely wrong approach. Unfortunately I did not find very much about this in the documentation or anywhere else on the Web.
TL;DR:
What is the best way to serialize an XText object model and to deserialize it again?
The first line doesn't belong here at all, just remove it.
How did you create/obtain the object 'scenario'?
If it was parsed with Xtext already you can obtain the serializer like this:
((XtextResource)scenario.eResource()).getResourceServiceProvider
.get(ISerializer.class)
Related
I am trying to create a contract for a GET request and I'd like to use a path parameter, that can be reused in the response as well. Is this at all possible? I can only find examples for POST, query parameters and body's.
So if I want to define a contract that requests an entity i.e. /books/12345-6688, I want to reuse the specified ID in the response.
How do I create a contract for something like this?
Possible since Spring Cloud Contract 1.2.0-RC1 (fixed in this issue).
response {
status 200
body(
path: fromRequest().path(),
pathIndex: fromRequest().path(1) // <-- here
)
}
See the docs.
Nope that's not possible due to https://github.com/tomakehurst/wiremock/issues/383 . Theoretically you could create your own transformer + override the way stubs are generated in Spring Cloud Contract. That way the WireMock stubs would contain a reference to your new transformer (like presented in the WireMock docs - http://wiremock.org/docs/extending-wiremock/). But it sounds like a lot of work for sth that seems not really that necessary. Why do you need to do it like this? On the consumer side you want to test the integration, right? So just hardcode some values in the contract instead of referencing them and just check if you can parse those values.
UPDATE:
If you just need to parametrize the request URL but don't want to reference it in the response you can use regular expressions like here - https://cloud.spring.io/spring-cloud-contract/single/spring-cloud-contract.html#_regular_expressions
UPDATE2:
Like #laffuste has mentioned, starting from RC1 you can reference a concrete path element
I have a REST WS implemented using Jersey/Jackson. The method which has been implemented is PUT and it is working fine until i get an empty or null body.
After googling a bit, I realized that it is a known issue and there are couple of work arounds available. One of the work around that i found (and implemented) is using ContentRequestFilter to intercept calls, do basic checks and decide what to do.
But in that case, I have to check if the call is for that specific method. I don't like this since what if the method changes in future ?
What i want is to receive as InputStream instead of parsed JacksonObject (Its a custom POJO object created using Jackson Annotations) and parse the inputstream to do that. However, I am unable to find a reference to do that i.e., parsing a jackson object, out of input stream (based on input media type) and return the respective object.
Can someone direct me to some helpful resources or help me here ?
This is an easy way of getting the contents from a request handled by Resource. Just replace Map.class with your annotated POJO:
#POST
public void handle(String requestBody) throws IOException {
ObjectMapper om = new ObjectMapper();
Map result = om.readValue(requestBody, Map.class);
}
With this approach you are free to handle a null value in any way you find suitable.
Currently our application uses GWT-RPC for most client-server communication. Where this breaks down is when we need to auto generate images. We generate images based on dozens of parameters so what we do is build large complex urls and via a get request retrieve the dynamically built image.
If we could find a way to serialize Java objects in gwt client code and deserialize it on the server side we could make our urls much easier to work with. Instead of
http://host/page?param1=a¶m2=b¶m3=c....
we could have
http://host/page?object=?JSON/XML/Something Magicical
and on the server just have
new MagicDeserializer.(request.getParameter("object"),AwesomeClass.class);
I do not care what the intermediate format is json/xml/whatever I just really want to be able stop keeping track of manually marshalling/unmarshalling parameters in my gwt client code as well as servlets.
Use AutoBean Framework. What you need is simple and is all here http://code.google.com/p/google-web-toolkit/wiki/AutoBean
I've seen the most success and least amount of code using this library:
https://code.google.com/p/gwtprojsonserializer/
Along with the standard toString() you should have for all Object classes, I also have what's called a toJsonString() inside of each class I want "JSONable". Note, each class must extend JsonSerializable, which comes with the library:
public String toJsonString()
{
Serializer serializer = (Serializer) GWT.create(Serializer.class);
return serializer.serializeToJson(this).toString();
}
To turn the JSON string back into an object, I put a static method inside of the same class, that recreates the class itself:
public static ClassName recreateClassViaJson(String json)
{
Serializer serializer = (Serializer) GWT.create(Serializer.class);
return (ClassName) serializer.deSerialize(json, "full.package.name.ClassName");
}
Very simple!
I know that GWT has a good RPC support. But for various purposes I need to build this on my own:
1.) How can I convert a Bean Object (on the Client Side) like;
class MyPerson {
String name;
String getName();
void setName(String name);
//..
}
with GWT into a JSON String? (Ideally only using libraries that come officially from GWT/Google).
2.) Secondly, how can I send this generated JSON String from the Client side to any Server also using any GWT Client Logik. (Ideally only using libraries that come officially from GWT/Google).
I have searched a lot, but the examples never show how to send data but only to receive JSON data.
Thank you very much!!!
Jens
There's a nifty class called AutoBeanFactory that GWT will create for you, no third-party libs required. See http://google-web-toolkit.googlecode.com/svn-history/r9219/javadoc/2.1/com/google/gwt/editor/client/AutoBeanFactory.html
Once you have your AutoBeanFactory, you can use it like this:
producing JSON from an object of type SimpleInterface
AutoBean<SimpleInterface> bean = beanFactory.create(SimpleInterface.class, simpleInterfaceInstance);
String requestData = AutoBeanCodex.encode(bean).getPayload();
useRequestBuilderToSendRequestWhereverYouWant(requestData);
parsing JSON from an object of type SimpleInterface
SimpleInterface simpleInterfaceInstance = AutoBeanCodex.decode(beanFactory, SimpleInterface.class, responseText).as();
You can use RequestBuilder to send these requests without GWT-RPC or the RF stuff.
I recommend you use RestyGWT it makes JSON rest services work just like GWT RPC services.
Take a look at GWT's AutoBean framework, which can be used to create and receive JSON payloads. The RequestBuilder type can be used to send HTTP requests to the server.
You have also another solution which is 3rd party solution, maybe a second place solution but it can be also the first place.
The 3rd party called GSON and it's a project open source on google code.
You can find it here.
I used it and it's very good and very simple.
I used Eclipse to generate a java client code stub given a third party wsdl. The client works great, I'm able to access the webservice an do what I need to do.
Now, I'd like to write some unit tests that can run without needing to be connected to the webservice. Is it possible to use some mechanism within axis2 stack to deserialize a xml file into one of the java objects in the java client stub code?
For example, one of the classes in the client stub code is "Contact". Say I have an xml file that mimics the xml that would usually is found in soap request. How can I deserialize that into a java Contact object?
I've used XMLBeans before, but hoping there's an easier way since it seems that the java client is already doing this deserialization under the hood somewhere? Maybe axis2 has a method to do take a chunk of xml and return a java object?
UPDATE:
I tried this:
String packageName = Contact.class.getPackage().getName();
JAXBContext jc = JAXBContext.newInstance( packageName );
I get this:
java.lang.AssertionError: javax.xml.bind.JAXBException: "com.sforce.soap._2006._04.metadata" doesnt contain ObjectFactory.class or jaxb.index
Then, I tried this:
Contact c = new Contact();
JAXBContext jc = JAXBContext.newInstance( c.getClass() );
But then I get exception that one of the classes that the Contact Class uses does not have a no-arq default constructor
I was hoping this would be a quick and easy thing to do, but until I have time to fully grok axis2 and how it uses jaxb, I'm just gonna parse the xml manually.
This is called "unmarshalling" in Axis. Have a look at org.apache.axis2.jaxws.message.databinding.JAXBUtils.getJAXBUnmarshaller(JAXBContext context). Once you have an unmarshaller, you can deserialize the XML back into objects.