Start json parser

This commit is contained in:
jamesagnew 2014-03-20 08:02:36 -04:00
parent 31e8584f12
commit 1fddb04fb3
15 changed files with 418 additions and 646 deletions

View File

@ -52,7 +52,7 @@ public class FhirContext {
}
@SuppressWarnings("unchecked")
public BaseRuntimeElementDefinition<?> getResourceDefinition(String theResourceName) {
public RuntimeResourceDefinition getResourceDefinition(String theResourceName) {
RuntimeResourceDefinition retVal = myNameToElementDefinition.get(theResourceName);
if (retVal == null) {

View File

@ -22,5 +22,4 @@ public interface IQueryParameterType {
*/
public String getValueAsQueryToken();
}

View File

@ -1,16 +1,35 @@
package ca.uhn.fhir.parser;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.primitive.IdDt;
public class BaseParser {
public abstract class BaseParser implements IParser {
@Override
@SuppressWarnings("unchecked")
public <T extends IResource> T parseResource(Class<T> theResourceType, String theMessageString) {
StringReader reader = new StringReader(theMessageString);
return (T) parseResource(theResourceType, reader);
}
@Override
public IResource parseResource(String theMessageString) throws ConfigurationException, DataFormatException {
return parseResource(null, theMessageString);
}
@Override
public IResource parseResource(Reader theReader) throws ConfigurationException, DataFormatException {
return parseResource(null, theReader);
}
public void containResourcesForEncoding(IResource theResource) {
List<ResourceReferenceDt> allElements = theResource.getAllPopulatedChildElementsOfType(ResourceReferenceDt.class);

View File

@ -1,391 +0,0 @@
package ca.uhn.fhir.parser;
public class CopyOfJsonParser {
// private FhirContext myContext;
//
// public CopyOfJsonParser(FhirContext theContext) {
// myContext = theContext;
// }
//
// @Override
// public String encodeBundleToString(Bundle theBundle) throws DataFormatException {
// StringWriter stringWriter = new StringWriter();
// encodeBundleToWriter(theBundle, stringWriter);
//
// return stringWriter.toString();
// }
//
// @Override
// public void encodeBundleToWriter(Bundle theBundle, Writer theWriter) {
// try {
// XMLStreamWriter eventWriter;
// eventWriter = myXmlOutputFactory.createXMLStreamWriter(theWriter);
// eventWriter = decorateStreamWriter(eventWriter);
//
// eventWriter.writeStartElement("feed");
// eventWriter.writeDefaultNamespace(ATOM_NS);
//
// writeTagWithTextNode(eventWriter, "title", theBundle.getTitle());
// writeTagWithTextNode(eventWriter, "id", theBundle.getId());
//
// writeAtomLink(eventWriter, "self", theBundle.getLinkSelf());
// writeAtomLink(eventWriter, "first", theBundle.getLinkFirst());
// writeAtomLink(eventWriter, "previous", theBundle.getLinkPrevious());
// writeAtomLink(eventWriter, "next", theBundle.getLinkNext());
// writeAtomLink(eventWriter, "last", theBundle.getLinkLast());
// writeAtomLink(eventWriter, "fhir-base", theBundle.getLinkBase());
//
// if (theBundle.getTotalResults().getValue() != null) {
// eventWriter.writeStartElement("os", OPENSEARCH_NS, "totalResults");
// eventWriter.writeNamespace("os", OPENSEARCH_NS);
// eventWriter.writeCharacters(theBundle.getTotalResults().getValue().toString());
// eventWriter.writeEndElement();
// }
//
// writeOptionalTagWithTextNode(eventWriter, "updated", theBundle.getUpdated());
// writeOptionalTagWithTextNode(eventWriter, "published", theBundle.getPublished());
//
// if (StringUtils.isNotBlank(theBundle.getAuthorName().getValue())) {
// eventWriter.writeStartElement("author");
// writeTagWithTextNode(eventWriter, "name", theBundle.getAuthorName());
// writeOptionalTagWithTextNode(eventWriter, "uri", theBundle.getAuthorUri());
// eventWriter.writeEndElement();
// }
//
// for (BundleEntry nextEntry : theBundle.getEntries()) {
// eventWriter.writeStartElement("entry");
//
// eventWriter.writeStartElement("content");
// eventWriter.writeAttribute("type", "text/xml");
//
// IResource resource = nextEntry.getResource();
// encodeResourceToXmlStreamWriter(resource, eventWriter);
//
// eventWriter.writeEndElement(); // content
// eventWriter.writeEndElement(); // entry
// }
//
// eventWriter.writeEndElement();
// eventWriter.close();
// } catch (XMLStreamException e) {
// throw new ConfigurationException("Failed to initialize STaX event factory", e);
// }
// }
//
// private void encodeChildElementToStreamWriter(JsonWriter theEventWriter, IElement nextValue, String childName, BaseRuntimeElementDefinition<?> childDef, String theExtensionUrl) {
// if (nextValue.isEmpty()) {
// return;
// }
//
// switch (childDef.getChildType()) {
// case PRIMITIVE_DATATYPE: {
// IPrimitiveDatatype<?> pd = (IPrimitiveDatatype<?>) nextValue;
// if (pd.getValue() != null) {
// theEventWriter.name(childName);
// if (pd instanceof IntegerDt) {
// theEventWriter.value(((IntegerDt)pd).getValue());
// } else if (pd instanceof DecimalDt) {
// theEventWriter.value(((DecimalDt)pd).getValue());
// } else if (pd instanceof BooleanDt) {
// theEventWriter.value(((BooleanDt)pd).getValue());
// } else {
// String value = pd.getValueAsString();
// theEventWriter.value(value);
// }
// theEventWriter.writeAttribute("value", value);
// encodeExtensionsIfPresent(theEventWriter, nextValue);
// theEventWriter.writeEndElement();
// }
// break;
// }
// case RESOURCE_BLOCK:
// case COMPOSITE_DATATYPE: {
// theEventWriter.writeStartElement(childName);
// if (isNotBlank(theExtensionUrl)) {
// theEventWriter.writeAttribute("url", theExtensionUrl);
// }
// BaseRuntimeElementCompositeDefinition<?> childCompositeDef = (BaseRuntimeElementCompositeDefinition<?>) childDef;
// encodeCompositeElementToStreamWriter(nextValue, theEventWriter, childCompositeDef);
// encodeExtensionsIfPresent(theEventWriter, nextValue);
// theEventWriter.writeEndElement();
// break;
// }
// case RESOURCE_REF: {
// ResourceReferenceDt ref = (ResourceReferenceDt) nextValue;
// if (!ref.isEmpty()) {
// theEventWriter.writeStartElement(childName);
// encodeResourceReferenceToStreamWriter(theEventWriter, ref);
// theEventWriter.writeEndElement();
// }
// break;
// }
// case RESOURCE: {
// throw new IllegalStateException(); // should not happen
// }
// case PRIMITIVE_XHTML: {
// XhtmlDt dt = (XhtmlDt) nextValue;
// if (dt.hasContent()) {
// encodeXhtml(dt, theEventWriter);
// }
// break;
// }
// case UNDECL_EXT: {
// throw new IllegalStateException("should not happen");
// }
// }
//
// }
//
// private void encodeCompositeElementChildrenToStreamWriter(IElement theElement, XMLStreamWriter theEventWriter, List<? extends BaseRuntimeChildDefinition> children) throws XMLStreamException,
// DataFormatException {
// for (BaseRuntimeChildDefinition nextChild : children) {
// List<? extends IElement> values = nextChild.getAccessor().getValues(theElement);
// if (values == null || values.isEmpty()) {
// continue;
// }
//
// for (IElement nextValue : values) {
// if (nextValue == null) {
// continue;
// }
// Class<? extends IElement> type = nextValue.getClass();
// String childName = nextChild.getChildNameByDatatype(type);
// String extensionUrl = nextChild.getExtensionUrl();
// BaseRuntimeElementDefinition<?> childDef = nextChild.getChildElementDefinitionByDatatype(type);
// if (childDef == null) {
// throw new IllegalStateException(nextChild + " has no child of type " + type);
// }
//
// if (extensionUrl != null && childName.equals("extension") == false) {
// RuntimeChildDeclaredExtensionDefinition extDef = (RuntimeChildDeclaredExtensionDefinition) nextChild;
// if (extDef.isModifier()) {
// theEventWriter.writeStartElement("modifierExtension");
// }else {
// theEventWriter.writeStartElement("extension");
// }
//
// theEventWriter.writeAttribute("url", extensionUrl);
// encodeChildElementToStreamWriter(theEventWriter, nextValue, childName, childDef, null);
// theEventWriter.writeEndElement();
// } else {
// encodeChildElementToStreamWriter(theEventWriter, nextValue, childName, childDef, extensionUrl);
// }
// }
// }
// }
//
// private void encodeCompositeElementToStreamWriter(IElement theElement, JsonWriter theEventWriter, BaseRuntimeElementCompositeDefinition<?> resDef) throws XMLStreamException,
// DataFormatException {
// encodeExtensionsIfPresent(theEventWriter, theElement);
// encodeCompositeElementChildrenToStreamWriter(theElement, theEventWriter, resDef.getExtensions());
// encodeCompositeElementChildrenToStreamWriter(theElement, theEventWriter, resDef.getChildren());
// }
//
// private void encodeExtensionsIfPresent(JsonWriter theWriter, IElement theResource) {
// if (theResource instanceof ISupportsUndeclaredExtensions) {
// ISupportsUndeclaredExtensions res = (ISupportsUndeclaredExtensions) theResource;
// encodeUndeclaredExtensions(theWriter, res.getUndeclaredExtensions(), "extension");
// encodeUndeclaredExtensions(theWriter, res.getUndeclaredModifierExtensions(), "modifierExtension");
// }
// }
//
// private void encodeUndeclaredExtensions(JsonWriter theWriter, List<UndeclaredExtension> extensions, String theTagName) throws XMLStreamException {
// if (extensions.isEmpty()) {
// return;
// }
//
// theWriter.name(theTagName);
// theWriter.beginArray();
//
// for (UndeclaredExtension next : extensions) {
// theWriter.name("url");
// theWriter.value(next.getUrl());
//
// if (next.getValue() != null) {
// IElement nextValue = next.getValue();
// RuntimeChildUndeclaredExtensionDefinition extDef = myContext.getRuntimeChildUndeclaredExtensionDefinition();
// String childName = extDef.getChildNameByDatatype(nextValue.getClass());
// BaseRuntimeElementDefinition<?> childDef = extDef.getChildElementDefinitionByDatatype(nextValue.getClass());
// encodeChildElementToStreamWriter(theWriter, nextValue, childName, childDef, null);
// }
//
// // child extensions
// encodeExtensionsIfPresent(theWriter, next);
//
// }
//
// theWriter.endArray();
// }
//
// private void encodeResourceReferenceToStreamWriter(XMLStreamWriter theEventWriter, ResourceReferenceDt theRef) throws XMLStreamException {
// if (!(theRef.getDisplay().isEmpty())) {
// theEventWriter.writeStartElement("display");
// theEventWriter.writeAttribute("value", theRef.getDisplay().getValue());
// theEventWriter.writeEndElement();
// }
// if (!(theRef.getReference().isEmpty())) {
// theEventWriter.writeStartElement("reference");
// theEventWriter.writeAttribute("value", theRef.getReference().getValue());
// theEventWriter.writeEndElement();
// }
// }
//
//
// @Override
// public String encodeResourceToString(IResource theResource) throws DataFormatException {
// Writer stringWriter = new StringWriter();
// encodeResourceToWriter(theResource, stringWriter);
// return stringWriter.toString();
// }
//
// @Override
// public void encodeResourceToWriter(IResource theResource, Writer theWriter) {
// JsonWriter eventWriter = new JsonWriter(theWriter);
//// try {
// encodeResourceToXmlStreamWriter(theResource, eventWriter);
// eventWriter.flush();
//// } catch (XMLStreamException e) {
//// throw new ConfigurationException("Failed to initialize STaX event factory", e);
//// }
// }
//
//
// private void encodeResourceToXmlStreamWriter(IResource theResource, JsonWriter theEventWriter) throws XMLStreamException, DataFormatException {
// RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource);
//
// theEventWriter.beginObject();
//
// theEventWriter.name("resourceType");
// theEventWriter.value(resDef.getName());
//
// encodeCompositeElementToStreamWriter(theResource, theEventWriter, resDef);
//
// theEventWriter.writeEndElement();
// }
//
// private void encodeXhtml(XhtmlDt theDt, XMLStreamWriter theEventWriter) throws XMLStreamException {
// if (theDt == null || theDt.getValue() == null) {
// return;
// }
//
// boolean firstEvent = true;
// for (XMLEvent event : theDt.getValue()) {
// switch (event.getEventType()) {
// case XMLStreamConstants.ATTRIBUTE:
// Attribute attr = (Attribute) event;
// if (isBlank(attr.getName().getPrefix())) {
// if (isBlank(attr.getName().getNamespaceURI())) {
// theEventWriter.writeAttribute(attr.getName().getLocalPart(), attr.getValue());
// } else {
// theEventWriter.writeAttribute(attr.getName().getNamespaceURI(), attr.getName().getLocalPart(), attr.getValue());
// }
// } else {
// theEventWriter.writeAttribute(attr.getName().getPrefix(), attr.getName().getNamespaceURI(), attr.getName().getLocalPart(), attr.getValue());
// }
//
// break;
// case XMLStreamConstants.CDATA:
// theEventWriter.writeCData(((Characters) event).getData());
// break;
// case XMLStreamConstants.CHARACTERS:
// case XMLStreamConstants.SPACE:
// theEventWriter.writeCharacters(((Characters) event).getData());
// break;
// case XMLStreamConstants.COMMENT:
// theEventWriter.writeComment(((Comment) event).getText());
// break;
// case XMLStreamConstants.END_ELEMENT:
// theEventWriter.writeEndElement();
// break;
// case XMLStreamConstants.ENTITY_REFERENCE:
// EntityReference er = (EntityReference) event;
// theEventWriter.writeEntityRef(er.getName());
// break;
// case XMLStreamConstants.NAMESPACE:
// Namespace ns = (Namespace) event;
// theEventWriter.writeNamespace(ns.getPrefix(), ns.getNamespaceURI());
// break;
// case XMLStreamConstants.START_ELEMENT:
// StartElement se = event.asStartElement();
// if (firstEvent) {
// theEventWriter.writeStartElement(se.getName().getLocalPart());
// if (StringUtils.isBlank(se.getName().getPrefix())) {
// theEventWriter.writeDefaultNamespace(se.getName().getNamespaceURI());
// } else {
// theEventWriter.writeNamespace(se.getName().getPrefix(), se.getName().getNamespaceURI());
// }
// } else {
// if (isBlank(se.getName().getPrefix())) {
// if (isBlank(se.getName().getNamespaceURI())) {
// theEventWriter.writeStartElement(se.getName().getLocalPart());
// } else {
// if (StringUtils.isBlank(se.getName().getPrefix())) {
// theEventWriter.writeStartElement(se.getName().getLocalPart());
// theEventWriter.writeDefaultNamespace(se.getName().getNamespaceURI());
// } else {
// theEventWriter.writeStartElement(se.getName().getNamespaceURI(), se.getName().getLocalPart());
// }
// }
// } else {
// theEventWriter.writeStartElement(se.getName().getPrefix(), se.getName().getLocalPart(), se.getName().getNamespaceURI());
// }
// }
// break;
// case XMLStreamConstants.DTD:
// case XMLStreamConstants.END_DOCUMENT:
// case XMLStreamConstants.ENTITY_DECLARATION:
// case XMLStreamConstants.NOTATION_DECLARATION:
// case XMLStreamConstants.PROCESSING_INSTRUCTION:
// case XMLStreamConstants.START_DOCUMENT:
// break;
// }
//
// firstEvent = false;
// }
// }
//
// @Override
// public Bundle parseBundle(Reader theReader) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public Bundle parseBundle(String theMessageString) throws ConfigurationException, DataFormatException {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public IResource parseResource(String theMessageString) throws ConfigurationException, DataFormatException {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public IResource parseResource(Reader theReader) throws ConfigurationException, DataFormatException {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public IResource parseResource(XMLEventReader theStreamReader) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public <T extends IResource> T parseResource(Class<T> theResourceType, String theMessageString) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public IResource parseResource(Class<? extends IResource> theResourceType, Reader theReader) {
// // TODO Auto-generated method stub
// return null;
// }
}

View File

@ -12,8 +12,14 @@ import java.util.List;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonValue;
import javax.json.JsonValue.ValueType;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonGeneratorFactory;
import javax.json.stream.JsonParser.Event;
import org.apache.commons.lang3.StringUtils;
@ -190,27 +196,67 @@ public class JsonParser extends BaseParser implements IParser {
@Override
public IResource parseResource(Class<? extends IResource> theResourceType, Reader theReader) {
// TODO Auto-generated method stub
JsonReader reader = Json.createReader(theReader);
JsonObject object = reader.readObject();
JsonValue resourceTypeObj = object.remove("resourceType");
assertObjectOfType(resourceTypeObj, JsonValue.ValueType.STRING, "resourceType");
String resourceType = ((JsonString)resourceTypeObj).getString();
if (theResourceType != null) {
RuntimeResourceDefinition def = myContext.getResourceDefinition(theResourceType);
}else {
RuntimeResourceDefinition def = myContext.getResourceDefinition(resourceType);
}
PushbackJsonParser parser = new PushbackJsonParser(Json.createParser(theReader));
while (parser.hasNext()) {
Event next = parser.next();
switch (next) {
case END_ARRAY:
break;
case END_OBJECT:
break;
case KEY_NAME:
break;
case START_ARRAY:
break;
case START_OBJECT:
break;
case VALUE_FALSE:
case VALUE_TRUE:
break;
case VALUE_NULL:
break;
case VALUE_NUMBER:
break;
case VALUE_STRING:
break;
default:
break;
}
}
return null;
}
private void assertObjectOfType(JsonValue theResourceTypeObj, ValueType theValueType, String thePosition) {
if (theResourceTypeObj.getValueType() != theValueType) {
throw new DataFormatException("Invalid content of element " + thePosition + ", expected " + theValueType);
}
}
@Override
public <T extends IResource> T parseResource(Class<T> theResourceType, String theMessageString) {
// TODO Auto-generated method stub
return null;
}
@Override
public IResource parseResource(Reader theReader) throws ConfigurationException, DataFormatException {
// TODO Auto-generated method stub
return null;
}
@Override
public IResource parseResource(String theMessageString) throws ConfigurationException, DataFormatException {
// TODO Auto-generated method stub
return null;
}
@Override
public IParser setPrettyPrint(boolean thePrettyPrint) {
@ -534,7 +580,7 @@ public class JsonParser extends BaseParser implements IParser {
if (value == null && ext.getAllUndeclaredExtensions().isEmpty()) {
theEventWriter.writeNull();
} else if (value == null) {
theEventWriter.writeStartArray();
theEventWriter.writeStartArray("extension");
for (UndeclaredExtension next : ext.getUndeclaredExtensions()) {
writeUndeclaredExt(theEventWriter, next);
}

View File

@ -0,0 +1,61 @@
package ca.uhn.fhir.parser;
import java.math.BigDecimal;
import javax.json.stream.JsonLocation;
import javax.json.stream.JsonParser;
public class PushbackJsonParser implements JsonParser {
private JsonParser myWrap;
public PushbackJsonParser(JsonParser theWrap) {
myWrap=theWrap;
}
@Override
public boolean hasNext() {
return myWrap.hasNext();
}
@Override
public Event next() {
return myWrap.next();
}
@Override
public String getString() {
return myWrap.getString();
}
@Override
public boolean isIntegralNumber() {
return myWrap.isIntegralNumber();
}
@Override
public int getInt() {
return myWrap.getInt();
}
@Override
public long getLong() {
return myWrap.getLong();
}
@Override
public BigDecimal getBigDecimal() {
return myWrap.getBigDecimal();
}
@Override
public JsonLocation getLocation() {
return myWrap.getLocation();
}
@Override
public void close() {
myWrap.close();
}
}

View File

@ -50,19 +50,19 @@ import ca.uhn.fhir.model.primitive.XhtmlDt;
import ca.uhn.fhir.util.PrettyPrintWriterWrapper;
public class XmlParser extends BaseParser implements IParser {
@SuppressWarnings("unused")
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(XmlParser.class);
static final String ATOM_NS = "http://www.w3.org/2005/Atom";
static final String FHIR_NS = "http://hl7.org/fhir";
static final String OPENSEARCH_NS = "http://a9.com/-/spec/opensearch/1.1/";
@SuppressWarnings("unused")
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(XmlParser.class);
static final String XHTML_NS = "http://www.w3.org/1999/xhtml";
// private static final Set<String> RESOURCE_NAMESPACES;
private FhirContext myContext;
private boolean myPrettyPrint;
private XMLInputFactory myXmlInputFactory;
private XMLOutputFactory myXmlOutputFactory;
private boolean myPrettyPrint;
public XmlParser(FhirContext theContext) {
myContext = theContext;
@ -70,6 +70,139 @@ public class XmlParser extends BaseParser implements IParser {
myXmlOutputFactory = XMLOutputFactory.newInstance();
}
@Override
public String encodeBundleToString(Bundle theBundle) throws DataFormatException {
StringWriter stringWriter = new StringWriter();
encodeBundleToWriter(theBundle, stringWriter);
return stringWriter.toString();
}
@Override
public void encodeBundleToWriter(Bundle theBundle, Writer theWriter) {
try {
XMLStreamWriter eventWriter;
eventWriter = myXmlOutputFactory.createXMLStreamWriter(theWriter);
eventWriter = decorateStreamWriter(eventWriter);
eventWriter.writeStartElement("feed");
eventWriter.writeDefaultNamespace(ATOM_NS);
writeTagWithTextNode(eventWriter, "title", theBundle.getTitle());
writeTagWithTextNode(eventWriter, "id", theBundle.getBundleId());
writeAtomLink(eventWriter, "self", theBundle.getLinkSelf());
writeAtomLink(eventWriter, "first", theBundle.getLinkFirst());
writeAtomLink(eventWriter, "previous", theBundle.getLinkPrevious());
writeAtomLink(eventWriter, "next", theBundle.getLinkNext());
writeAtomLink(eventWriter, "last", theBundle.getLinkLast());
writeAtomLink(eventWriter, "fhir-base", theBundle.getLinkBase());
if (theBundle.getTotalResults().getValue() != null) {
eventWriter.writeStartElement("os", "totalResults",OPENSEARCH_NS);
eventWriter.writeNamespace("os", OPENSEARCH_NS);
eventWriter.writeCharacters(theBundle.getTotalResults().getValue().toString());
eventWriter.writeEndElement();
}
writeOptionalTagWithTextNode(eventWriter, "updated", theBundle.getUpdated());
writeOptionalTagWithTextNode(eventWriter, "published", theBundle.getPublished());
if (StringUtils.isNotBlank(theBundle.getAuthorName().getValue())) {
eventWriter.writeStartElement("author");
writeTagWithTextNode(eventWriter, "name", theBundle.getAuthorName());
writeOptionalTagWithTextNode(eventWriter, "uri", theBundle.getAuthorUri());
eventWriter.writeEndElement();
}
for (BundleEntry nextEntry : theBundle.getEntries()) {
eventWriter.writeStartElement("entry");
eventWriter.writeStartElement("content");
eventWriter.writeAttribute("type", "text/xml");
IResource resource = nextEntry.getResource();
encodeResourceToXmlStreamWriter(resource, eventWriter);
eventWriter.writeEndElement(); // content
eventWriter.writeEndElement(); // entry
}
eventWriter.writeEndElement();
eventWriter.close();
} catch (XMLStreamException e) {
throw new ConfigurationException("Failed to initialize STaX event factory", e);
}
}
@Override
public String encodeResourceToString(IResource theResource) throws DataFormatException {
Writer stringWriter = new StringWriter();
encodeResourceToWriter(theResource, stringWriter);
return stringWriter.toString();
}
@Override
public void encodeResourceToWriter(IResource theResource, Writer stringWriter) {
XMLStreamWriter eventWriter;
try {
eventWriter = myXmlOutputFactory.createXMLStreamWriter(stringWriter);
eventWriter = decorateStreamWriter(eventWriter);
encodeResourceToXmlStreamWriter(theResource, eventWriter);
eventWriter.flush();
} catch (XMLStreamException e) {
throw new ConfigurationException("Failed to initialize STaX event factory", e);
}
}
@Override
public Bundle parseBundle(Reader theReader) {
XMLEventReader streamReader;
try {
streamReader = myXmlInputFactory.createXMLEventReader(theReader);
} catch (XMLStreamException e) {
throw new DataFormatException(e);
} catch (FactoryConfigurationError e) {
throw new ConfigurationException("Failed to initialize STaX event factory", e);
}
return parseBundle(streamReader);
}
/*
* (non-Javadoc)
*
* @see ca.uhn.fhir.parser.IParser#parseBundle(java.lang.String)
*/
@Override
public Bundle parseBundle(String theXml) throws ConfigurationException, DataFormatException {
StringReader reader = new StringReader(theXml);
return parseBundle(reader);
}
@Override
public IResource parseResource(Class<? extends IResource> theResourceType, Reader theReader) {
XMLEventReader streamReader;
try {
streamReader = myXmlInputFactory.createXMLEventReader(theReader);
} catch (XMLStreamException e) {
throw new DataFormatException(e);
} catch (FactoryConfigurationError e) {
throw new ConfigurationException("Failed to initialize STaX event factory", e);
}
return parseResource(theResourceType, streamReader);
}
@Override
public IParser setPrettyPrint(boolean thePrettyPrint) {
myPrettyPrint = thePrettyPrint;
return this;
}
private XMLStreamWriter decorateStreamWriter(XMLStreamWriter eventWriter) {
if (myPrettyPrint) {
PrettyPrintWriterWrapper retVal = new PrettyPrintWriterWrapper(eventWriter);
@ -152,71 +285,6 @@ public class XmlParser extends BaseParser implements IParser {
}
}
@Override
public String encodeBundleToString(Bundle theBundle) throws DataFormatException {
StringWriter stringWriter = new StringWriter();
encodeBundleToWriter(theBundle, stringWriter);
return stringWriter.toString();
}
@Override
public void encodeBundleToWriter(Bundle theBundle, Writer theWriter) {
try {
XMLStreamWriter eventWriter;
eventWriter = myXmlOutputFactory.createXMLStreamWriter(theWriter);
eventWriter = decorateStreamWriter(eventWriter);
eventWriter.writeStartElement("feed");
eventWriter.writeDefaultNamespace(ATOM_NS);
writeTagWithTextNode(eventWriter, "title", theBundle.getTitle());
writeTagWithTextNode(eventWriter, "id", theBundle.getBundleId());
writeAtomLink(eventWriter, "self", theBundle.getLinkSelf());
writeAtomLink(eventWriter, "first", theBundle.getLinkFirst());
writeAtomLink(eventWriter, "previous", theBundle.getLinkPrevious());
writeAtomLink(eventWriter, "next", theBundle.getLinkNext());
writeAtomLink(eventWriter, "last", theBundle.getLinkLast());
writeAtomLink(eventWriter, "fhir-base", theBundle.getLinkBase());
if (theBundle.getTotalResults().getValue() != null) {
eventWriter.writeStartElement("os", "totalResults",OPENSEARCH_NS);
eventWriter.writeNamespace("os", OPENSEARCH_NS);
eventWriter.writeCharacters(theBundle.getTotalResults().getValue().toString());
eventWriter.writeEndElement();
}
writeOptionalTagWithTextNode(eventWriter, "updated", theBundle.getUpdated());
writeOptionalTagWithTextNode(eventWriter, "published", theBundle.getPublished());
if (StringUtils.isNotBlank(theBundle.getAuthorName().getValue())) {
eventWriter.writeStartElement("author");
writeTagWithTextNode(eventWriter, "name", theBundle.getAuthorName());
writeOptionalTagWithTextNode(eventWriter, "uri", theBundle.getAuthorUri());
eventWriter.writeEndElement();
}
for (BundleEntry nextEntry : theBundle.getEntries()) {
eventWriter.writeStartElement("entry");
eventWriter.writeStartElement("content");
eventWriter.writeAttribute("type", "text/xml");
IResource resource = nextEntry.getResource();
encodeResourceToXmlStreamWriter(resource, eventWriter);
eventWriter.writeEndElement(); // content
eventWriter.writeEndElement(); // entry
}
eventWriter.writeEndElement();
eventWriter.close();
} catch (XMLStreamException e) {
throw new ConfigurationException("Failed to initialize STaX event factory", e);
}
}
private void encodeChildElementToStreamWriter(XMLStreamWriter theEventWriter, IElement nextValue, String childName, BaseRuntimeElementDefinition<?> childDef, String theExtensionUrl) throws XMLStreamException, DataFormatException {
if (nextValue.isEmpty()) {
return;
@ -323,6 +391,36 @@ public class XmlParser extends BaseParser implements IParser {
}
}
private void encodeResourceReferenceToStreamWriter(XMLStreamWriter theEventWriter, ResourceReferenceDt theRef) throws XMLStreamException {
if (!(theRef.getDisplay().isEmpty())) {
theEventWriter.writeStartElement("display");
theEventWriter.writeAttribute("value", theRef.getDisplay().getValue());
theEventWriter.writeEndElement();
}
if (!(theRef.getReference().isEmpty())) {
theEventWriter.writeStartElement("reference");
theEventWriter.writeAttribute("value", theRef.getReference().getValue());
theEventWriter.writeEndElement();
}
}
private void encodeResourceToXmlStreamWriter(IResource theResource, XMLStreamWriter eventWriter) throws XMLStreamException, DataFormatException {
super.containResourcesForEncoding(theResource);
RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource);
if (resDef == null) {
throw new ConfigurationException("Unknown resource type: " + theResource.getClass());
}
eventWriter.writeStartElement(resDef.getName());
eventWriter.writeDefaultNamespace(FHIR_NS);
encodeCompositeElementToStreamWriter(theResource, eventWriter, resDef);
eventWriter.writeEndElement();
}
private void encodeUndeclaredExtensions(XMLStreamWriter theWriter, List<UndeclaredExtension> extensions, String tagName) throws XMLStreamException {
for (UndeclaredExtension next : extensions) {
theWriter.writeStartElement(tagName);
@ -346,56 +444,6 @@ public class XmlParser extends BaseParser implements IParser {
}
}
private void encodeResourceReferenceToStreamWriter(XMLStreamWriter theEventWriter, ResourceReferenceDt theRef) throws XMLStreamException {
if (!(theRef.getDisplay().isEmpty())) {
theEventWriter.writeStartElement("display");
theEventWriter.writeAttribute("value", theRef.getDisplay().getValue());
theEventWriter.writeEndElement();
}
if (!(theRef.getReference().isEmpty())) {
theEventWriter.writeStartElement("reference");
theEventWriter.writeAttribute("value", theRef.getReference().getValue());
theEventWriter.writeEndElement();
}
}
@Override
public String encodeResourceToString(IResource theResource) throws DataFormatException {
Writer stringWriter = new StringWriter();
encodeResourceToWriter(theResource, stringWriter);
return stringWriter.toString();
}
@Override
public void encodeResourceToWriter(IResource theResource, Writer stringWriter) {
XMLStreamWriter eventWriter;
try {
eventWriter = myXmlOutputFactory.createXMLStreamWriter(stringWriter);
eventWriter = decorateStreamWriter(eventWriter);
encodeResourceToXmlStreamWriter(theResource, eventWriter);
eventWriter.flush();
} catch (XMLStreamException e) {
throw new ConfigurationException("Failed to initialize STaX event factory", e);
}
}
private void encodeResourceToXmlStreamWriter(IResource theResource, XMLStreamWriter eventWriter) throws XMLStreamException, DataFormatException {
super.containResourcesForEncoding(theResource);
RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource);
if (resDef == null) {
throw new ConfigurationException("Unknown resource type: " + theResource.getClass());
}
eventWriter.writeStartElement(resDef.getName());
eventWriter.writeDefaultNamespace(FHIR_NS);
encodeCompositeElementToStreamWriter(theResource, eventWriter, resDef);
eventWriter.writeEndElement();
}
private void encodeXhtml(XhtmlDt theDt, XMLStreamWriter theEventWriter) throws XMLStreamException {
if (theDt == null || theDt.getValue() == null) {
return;
@ -477,36 +525,11 @@ public class XmlParser extends BaseParser implements IParser {
}
}
/*
* (non-Javadoc)
*
* @see ca.uhn.fhir.parser.IParser#parseBundle(java.lang.String)
*/
@Override
public Bundle parseBundle(String theXml) throws ConfigurationException, DataFormatException {
StringReader reader = new StringReader(theXml);
return parseBundle(reader);
}
private Bundle parseBundle(XMLEventReader theStreamReader) {
ParserState<Bundle> parserState = ParserState.getPreAtomInstance(myContext);
return doXmlLoop(theStreamReader, parserState);
}
/*
* (non-Javadoc)
*
* @see ca.uhn.fhir.parser.IParser#parseResource(java.lang.String)
*/
@Override
public IResource parseResource(String theMessageString) throws ConfigurationException, DataFormatException {
return parseResource(null, theMessageString);
}
private IResource parseResource(XMLEventReader theStreamReader) {
return parseResource(null, theStreamReader);
}
private IResource parseResource(Class<? extends IResource> theResourceType, XMLEventReader theStreamReader) {
ParserState<IResource> parserState = ParserState.getPreResourceInstance(theResourceType, myContext);
return doXmlLoop(theStreamReader, parserState);
@ -537,6 +560,7 @@ public class XmlParser extends BaseParser implements IParser {
}
}
private void writeTagWithTextNode(XMLStreamWriter theEventWriter, String theElementName, StringDt theStringDt) throws XMLStreamException {
theEventWriter.writeStartElement(theElementName);
if (StringUtils.isNotBlank(theStringDt.getValue())) {
@ -544,50 +568,4 @@ public class XmlParser extends BaseParser implements IParser {
}
theEventWriter.writeEndElement();
}
@Override
public Bundle parseBundle(Reader theReader) {
XMLEventReader streamReader;
try {
streamReader = myXmlInputFactory.createXMLEventReader(theReader);
} catch (XMLStreamException e) {
throw new DataFormatException(e);
} catch (FactoryConfigurationError e) {
throw new ConfigurationException("Failed to initialize STaX event factory", e);
}
return parseBundle(streamReader);
}
@Override
public IResource parseResource(Reader theReader) throws ConfigurationException, DataFormatException {
return parseResource(null, theReader);
}
@Override
public IResource parseResource(Class<? extends IResource> theResourceType, Reader theReader) {
XMLEventReader streamReader;
try {
streamReader = myXmlInputFactory.createXMLEventReader(theReader);
} catch (XMLStreamException e) {
throw new DataFormatException(e);
} catch (FactoryConfigurationError e) {
throw new ConfigurationException("Failed to initialize STaX event factory", e);
}
return parseResource(theResourceType, streamReader);
}
@SuppressWarnings("unchecked")
@Override
public <T extends IResource> T parseResource(Class<T> theResourceType, String theMessageString) {
StringReader reader = new StringReader(theMessageString);
return (T) parseResource(theResourceType, reader);
}
@Override
public IParser setPrettyPrint(boolean thePrettyPrint) {
myPrettyPrint = thePrettyPrint;
return this;
}
}

View File

@ -2,6 +2,7 @@ package ca.uhn.fhir.rest.param;
import java.util.List;
import ca.uhn.fhir.model.dstu.valueset.SearchParamTypeEnum;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
@ -15,4 +16,6 @@ public interface IParameter {
public abstract boolean isRequired();
public abstract SearchParamTypeEnum getParamType();
}

View File

@ -6,6 +6,7 @@ import java.util.Collections;
import java.util.List;
import ca.uhn.fhir.model.api.PathSpecification;
import ca.uhn.fhir.model.dstu.valueset.SearchParamTypeEnum;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
@ -63,4 +64,9 @@ public class IncludeParameter implements IParameter {
return false;
}
@Override
public SearchParamTypeEnum getParamType() {
return null;
}
}

View File

@ -42,4 +42,5 @@ final class QueryParameterTypeBinder implements IParamBinder {
}
return dt;
}
}

View File

@ -6,6 +6,9 @@ import java.util.List;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.model.api.IQueryParameterOr;
import ca.uhn.fhir.model.api.IQueryParameterType;
import ca.uhn.fhir.model.dstu.composite.IdentifierDt;
import ca.uhn.fhir.model.dstu.valueset.SearchParamTypeEnum;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
@ -18,6 +21,7 @@ public class SearchParameter implements IParameter {
private IParamBinder parser;
private boolean required;
private Class<?> type;
private SearchParamTypeEnum myParamType;
public SearchParameter() {
}
@ -47,6 +51,7 @@ public class SearchParameter implements IParameter {
return type;
}
@Override
public boolean isRequired() {
return required;
}
@ -78,6 +83,18 @@ public class SearchParameter implements IParameter {
throw new ConfigurationException("Unsupported data type for parameter: " + type.getCanonicalName());
}
if (StringDt.class.isAssignableFrom(type)) {
myParamType = SearchParamTypeEnum.STRING;
} else if (QualifiedDateParam.class.isAssignableFrom(type)) {
myParamType = SearchParamTypeEnum.DATE;
} else if (CodingListParam.class.isAssignableFrom(type)) {
myParamType = SearchParamTypeEnum.TOKEN;
} else if (IdentifierDt.class.isAssignableFrom(type)) {
myParamType = SearchParamTypeEnum.TOKEN;
} else {
throw new ConfigurationException("Unknown search parameter type: " + type);
}
// if (theInnerCollectionType != null) {
// this.parser = new CollectionBinder(this.parser, theInnerCollectionType);
// }
@ -88,4 +105,9 @@ public class SearchParameter implements IParameter {
}
@Override
public SearchParamTypeEnum getParamType() {
return myParamType;
}
}

View File

@ -17,6 +17,7 @@ import ca.uhn.fhir.model.dstu.resource.Conformance.RestResourceSearchParam;
import ca.uhn.fhir.model.dstu.valueset.RestfulConformanceModeEnum;
import ca.uhn.fhir.model.dstu.valueset.RestfulOperationSystemEnum;
import ca.uhn.fhir.model.dstu.valueset.RestfulOperationTypeEnum;
import ca.uhn.fhir.model.primitive.BooleanDt;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.rest.annotation.Metadata;
@ -102,14 +103,29 @@ public class ServerConformanceProvider implements IResourceProvider {
} else {
searchParam = nameToSearchParam.get(nextParameter.getName());
}
if (searchParam !=null) {
searchParam.setType(nextParameter.getParamType());
}
} else if (searchParamChain == null) {
searchParam.addChain(nextParameter.getName());
searchParamChain = searchParam.getChain().get(searchParam.getChain().size()-1);
UndeclaredExtension ext = new UndeclaredExtension();
ext.setUrl(ExtensionConstants.CONF_CHAIN_REQUIRED);
ext.setValue(new BooleanDt(nextParameter.isRequired()));
searchParamChain.getUndeclaredExtensions().add(ext);
} else {
UndeclaredExtension ext = new UndeclaredExtension();
ext.setUrl(ExtensionConstants.CONF_ALSO_CHAIN);
ext.setValue(new StringDt(nextParameter.getName()));
searchParamChain.getUndeclaredExtensions().add(ext);
UndeclaredExtension extReq = new UndeclaredExtension();
extReq.setUrl(ExtensionConstants.CONF_CHAIN_REQUIRED);
extReq.setValue(new BooleanDt(nextParameter.isRequired()));
ext.getUndeclaredExtensions().add(extReq);
}
}

View File

@ -4,4 +4,6 @@ public class ExtensionConstants {
public static final String CONF_ALSO_CHAIN = "http://hl7api.sourceforge.net/hapi-fhir/extensions.xml#alsoChain";
public static final String CONF_CHAIN_REQUIRED = "http://hl7api.sourceforge.net/hapi-fhir/extensions.xml#chainRequired";
}

View File

@ -73,5 +73,17 @@ public class JsonParserTest {
}
public void testSimpleParse() throws DataFormatException, IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/example-patient-general.json"));
FhirContext ctx = new FhirContext(Patient.class);
IParser p = ctx.newJsonParser();
Patient res = p.parseResource(Patient.class, msg);
String encoded = ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(res);
ourLog.info(encoded);
}
}

View File

@ -81,7 +81,6 @@ public class ResfulServerMethodTest {
builder.setConnectionManager(connectionManager);
ourClient = builder.build();
}
@AfterClass
@ -137,19 +136,22 @@ public class ResfulServerMethodTest {
IParser parser = ourCtx.newXmlParser().setPrettyPrint(true);
Conformance bundle = parser.parseResource(Conformance.class, responseContent);
IParser p = ourCtx.newJsonParser().setPrettyPrint(true);
p.encodeResourceToWriter(bundle, new OutputStreamWriter(System.out));
{
IParser p = ourCtx.newXmlParser().setPrettyPrint(true);
String enc = p.encodeResourceToString(bundle);
ourLog.info("Response:\n{}", enc);
assertTrue(enc.contains(ExtensionConstants.CONF_ALSO_CHAIN));
p = ourCtx.newXmlParser().setPrettyPrint(true);
enc = p.encodeResourceToString(bundle);
ourLog.info("Response:\n{}", enc);
assertTrue(enc.contains(ExtensionConstants.CONF_ALSO_CHAIN));
}
// {
// IParser p = ourCtx.newJsonParser().setPrettyPrint(true);
//
// p.encodeResourceToWriter(bundle, new OutputStreamWriter(System.out));
//
// String enc = p.encodeResourceToString(bundle);
// ourLog.info("Response:\n{}", enc);
// assertTrue(enc.contains(ExtensionConstants.CONF_ALSO_CHAIN));
//
// }
}
@Test
@ -434,7 +436,6 @@ public class ResfulServerMethodTest {
}
public static class DummyRestfulServer extends RestfulServer {
private static final long serialVersionUID = 1L;
@ -457,7 +458,6 @@ public class ResfulServerMethodTest {
}
/**
* Created by dsotnikov on 2/25/2014.
*/
@ -603,6 +603,4 @@ public class ResfulServerMethodTest {
}
}