Recycling non EMF-aware web services [message #1587709] |
Tue, 27 January 2015 09:14  |
Eclipse User |
|
|
|
Hello,
I was wondering how I could best proceed for the following case.
On the server side, I have some Jersey web services, totally non-EMF aware (cannot change).
On the client side, I have an RCP-application, which datamodel is EMF-based.
My question is : is there a means of using these web services to populate EMF resources, preferably without writing ad hoc messagebodywriters and readers ... ? In my opinion, this should be feasible, as the EMF model is generated on ground of the xml schemas of the entities used on the server side.
Is there anything in the EMF API I could use to do this ?
Thomas Elskens
|
|
|
Re: Recycling non EMF-aware web services [message #1591575 is a reply to message #1587709] |
Thu, 29 January 2015 11:13  |
Eclipse User |
|
|
|
Okay it turns out that with EMF's reflective capabilities, creating a custom JSON parsing mechanism is really only a matter of a few lines of code (and some solid naming conventions).
The code is not optimized and not very pretty, but the basic idea is conveyed (with Jackson library) :
//...
public List<EObject> readJSonAsList(String jsonString, String rootType) throws IOException
{
List<EObject> result = new ArrayList<>() ;
JsonNode root = mapper.readTree(jsonString) ;
if (root.getNodeType() != JsonNodeType.ARRAY) throw new IOException("Wrong data format : ARRAY expected !") ;
Iterator<JsonNode> elements = root.iterator() ;
while (elements.hasNext())
{
JsonNode arrayNode = elements.next() ;
EObject arrayElement = recursiveReading(rootType,arrayNode) ;
result.add(arrayElement) ;
}
return result ;
}
private EObject recursiveReading(String fieldName, JsonNode root) throws IOException
{
EClass clazz = getEClass(fieldName) ;
EObject result = clazz.getEPackage().getEFactoryInstance().create(clazz) ;
Iterator<Entry<String,JsonNode>> fields = root.fields() ;
while (fields.hasNext())
{
Entry<String,JsonNode> field = fields.next() ;
String nextFieldName = field.getKey() ;
JsonNode nextNode = field.getValue() ;
if (nextNode.getNodeType() == JsonNodeType.OBJECT)
{
result.eSet(clazz.getEStructuralFeature(nextFieldName), recursiveReading(nextFieldName,nextNode));
}
else
{
setField(result, nextFieldName, nextNode) ;
}
}
return result ;
}
//...
Sorry for bothering !
|
|
|
Powered by
FUDForum. Page generated in 0.04791 seconds