use of com.nedap.archie.creation.ExampleJsonInstanceGenerator in project archetype-languageserver by nedap.
the class GenerateExampleCommand method apply.
public void apply() {
String documentUri = ((JsonPrimitive) params.getArguments().get(0)).getAsString();
String format = ((JsonPrimitive) params.getArguments().get(1)).getAsString();
String serializedExample = null;
Flattener flattener = new Flattener(storage, BuiltinReferenceModels.getMetaModels(), FlattenerConfiguration.forOperationalTemplate());
DocumentInformation documentInformation = storage.getDocumentInformation(documentUri);
Archetype archetype = storage.getArchetype(documentInformation.getArchetypeId());
OperationalTemplate opt = (OperationalTemplate) flattener.flatten(archetype);
ExampleJsonInstanceGenerator exampleJsonInstanceGenerator = new ExampleJsonInstanceGenerator(BuiltinReferenceModels.getMetaModels(), archetype.getOriginalLanguage().getCodeString());
Map<String, Object> exampleMap = exampleJsonInstanceGenerator.generate(opt);
String extension;
ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
String jsonRmObject = null;
OpenEHRBase example;
try {
jsonRmObject = objectMapper.writeValueAsString(exampleMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
switch(format) {
case "json":
extension = "_example.json";
serializedExample = jsonRmObject;
break;
case "flat_json":
extension = "_flat_example.json";
FlatJsonGenerator flatJsonGenerator = new FlatJsonGenerator(ArchieRMInfoLookup.getInstance(), FlatJsonFormatConfiguration.nedapInternalFormat());
try {
example = objectMapper.readValue(jsonRmObject, OpenEHRBase.class);
Map<String, Object> flatExample = flatJsonGenerator.buildPathsAndValues(example);
serializedExample = JacksonUtil.getObjectMapper().writeValueAsString(flatExample);
} catch (JsonProcessingException | DuplicateKeyException e) {
throw new RuntimeException(e);
}
break;
case "xml":
{
extension = "_example.xml";
try {
example = objectMapper.readValue(jsonRmObject, OpenEHRBase.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
StringWriter sw = new StringWriter();
try {
Marshaller marshaller = JAXBUtil.getArchieJAXBContext().createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(example, sw);
} catch (JAXBException e) {
throw new RuntimeException(e);
}
serializedExample = sw.toString();
break;
}
//
default:
throw new UnsupportedOperationException("unsupported format: " + format);
}
String uriToWrite = documentUri.substring(0, documentUri.lastIndexOf("/")) + "/example/" + opt.getArchetypeId() + extension;
textDocumentService.writeFile(uriToWrite, "opt in " + format, serializedExample);
}
Aggregations