Merge branch 'master' of ssh://git.code.sf.net/p/hl7api/fhircode
This commit is contained in:
commit
ce17e82f9d
|
@ -0,0 +1,4 @@
|
|||
|
||||
* Implement JSON parser and encoder
|
||||
* Implement strategy for narrative generation
|
||||
|
|
@ -81,5 +81,6 @@
|
|||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
|
||||
<classpathentry kind="var" path="M2_REPO/org/mockito/mockito-all/1.9.5/mockito-all-1.9.5.jar"/>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
||||
|
|
|
@ -106,7 +106,12 @@
|
|||
<version>9.1.1.v20140108</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-all</artifactId>
|
||||
<version>1.9.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
|
|
|
@ -1,7 +1,10 @@
|
|||
package ca.uhn.fhir.context;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import ca.uhn.fhir.model.api.IElement;
|
||||
import ca.uhn.fhir.model.api.IResource;
|
||||
|
@ -14,6 +17,10 @@ public class FhirContext {
|
|||
private RuntimeChildUndeclaredExtensionDefinition myRuntimeChildUndeclaredExtensionDefinition;
|
||||
|
||||
public FhirContext(Class<? extends IResource>... theResourceTypes) {
|
||||
this(Arrays.asList(theResourceTypes));
|
||||
}
|
||||
|
||||
public FhirContext(Collection<Class<? extends IResource>> theResourceTypes) {
|
||||
ModelScanner scanner = new ModelScanner(theResourceTypes);
|
||||
myNameToElementDefinition = Collections.unmodifiableMap(scanner.getNameToResourceDefinitions());
|
||||
myClassToElementDefinition = Collections.unmodifiableMap(scanner.getClassToElementDefinitions());
|
||||
|
|
|
@ -60,9 +60,9 @@ class ModelScanner {
|
|||
|
||||
private RuntimeChildUndeclaredExtensionDefinition myRuntimeChildUndeclaredExtensionDefinition;
|
||||
|
||||
ModelScanner(Class<? extends IResource>... theResourceTypes) throws ConfigurationException {
|
||||
ModelScanner(Collection<Class<? extends IResource>> theResourceTypes) throws ConfigurationException {
|
||||
|
||||
Set<Class<? extends IElement>> toScan = new HashSet<Class<? extends IElement>>(Arrays.asList(theResourceTypes));
|
||||
Set<Class<? extends IElement>> toScan = new HashSet<Class<? extends IElement>>(theResourceTypes);
|
||||
toScan.add(NarrativeDt.class);
|
||||
toScan.add(DateDt.class);
|
||||
toScan.add(CodeDt.class);
|
||||
|
|
|
@ -0,0 +1,23 @@
|
|||
package ca.uhn.fhir.ws;
|
||||
|
||||
import ca.uhn.fhir.model.api.IResource;
|
||||
|
||||
public interface IResourceProvider<T extends IResource> {
|
||||
|
||||
/**
|
||||
* Returns the type of resource returned by this provider
|
||||
*
|
||||
* @return Returns the type of resource returned by this provider
|
||||
*/
|
||||
Class<T> getResourceType();
|
||||
|
||||
/**
|
||||
* Retrieve the resource by its identifier
|
||||
*
|
||||
* @param theId
|
||||
* The resource identity
|
||||
* @return The resource
|
||||
*/
|
||||
T getResourceById(long theId);
|
||||
|
||||
}
|
|
@ -0,0 +1,202 @@
|
|||
package ca.uhn.fhir.ws;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import ca.uhn.fhir.context.FhirContext;
|
||||
import ca.uhn.fhir.model.api.IResource;
|
||||
import ca.uhn.fhir.parser.XmlParser;
|
||||
import ca.uhn.fhir.ws.exceptions.MethodNotFoundException;
|
||||
import ca.uhn.fhir.ws.operations.DELETE;
|
||||
import ca.uhn.fhir.ws.operations.GET;
|
||||
import ca.uhn.fhir.ws.operations.POST;
|
||||
import ca.uhn.fhir.ws.operations.PUT;
|
||||
|
||||
public abstract class RestfulServer extends HttpServlet {
|
||||
|
||||
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(RestfulServer.class);
|
||||
|
||||
// map of request handler resources keyed by resource name
|
||||
private Map<String, Resource> resources = new HashMap<String, Resource>();
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Map<Class<? extends IResource>, IResourceProvider<?>> myTypeToProvider = new HashMap<Class<? extends IResource>, IResourceProvider<?>>();
|
||||
|
||||
public abstract Collection<IResourceProvider<?>> getResourceProviders();
|
||||
|
||||
@Override
|
||||
public void init() throws ServletException {
|
||||
try {
|
||||
ourLog.info("Initializing HAPI FHIR restful server");
|
||||
|
||||
Collection<IResourceProvider<?>> resourceProvider = getResourceProviders();
|
||||
for (IResourceProvider<?> nextProvider : resourceProvider) {
|
||||
if (myTypeToProvider.containsKey(nextProvider.getResourceType())) {
|
||||
throw new ServletException("Multiple providers for type: " + nextProvider.getResourceType().getCanonicalName());
|
||||
}
|
||||
myTypeToProvider.put(nextProvider.getResourceType(), nextProvider);
|
||||
}
|
||||
|
||||
ourLog.info("Got {} resource providers",myTypeToProvider.size());
|
||||
|
||||
myFhirContext = new FhirContext(myTypeToProvider.keySet());
|
||||
|
||||
findResourceMethods(nextProvider.getClass());
|
||||
|
||||
|
||||
} catch (Exception ex) {
|
||||
ourLog.error("An error occurred while loading request handlers!", ex);
|
||||
throw new ServletException("Failed to initialize FHIR Restful server", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void addResourceMethod(Resource resource, Method method) throws Exception {
|
||||
|
||||
Class<?>[] params = method.getParameterTypes();
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
rm.setResourceType(method.getReturnType());
|
||||
|
||||
// each operation name must have a request type annotation and be unique
|
||||
if (null != method.getAnnotation(GET.class)) {
|
||||
rm.setRequestType(ResourceMethod.RequestType.GET);
|
||||
} else if (null != method.getAnnotation(PUT.class)) {
|
||||
rm.setRequestType(ResourceMethod.RequestType.PUT);
|
||||
} else if (null != method.getAnnotation(POST.class)) {
|
||||
rm.setRequestType(ResourceMethod.RequestType.POST);
|
||||
} else if (null != method.getAnnotation(DELETE.class)) {
|
||||
rm.setRequestType(ResourceMethod.RequestType.DELETE);
|
||||
}
|
||||
rm.setParameters(Util.getResourceParameters(method));
|
||||
resource.addMethod(rm);
|
||||
}
|
||||
|
||||
private void findResourceMethods(Class<? extends IResourceProvider> theClass1) throws Exception {
|
||||
for (Method m : theClass1.getDeclaredMethods()) {
|
||||
if (Modifier.isPublic(m.getModifiers())) {
|
||||
|
||||
String resourceName = Util.getResourceName(m);
|
||||
Resource r = resources.get(resourceName);
|
||||
if (null == r) {
|
||||
r = new Resource();
|
||||
r.setResourceName(resourceName);
|
||||
resources.put(resourceName, r);
|
||||
}
|
||||
addResourceMethod(r, m);
|
||||
|
||||
ourLog.debug("found handler: " + m.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
handleRequest(ResourceMethod.RequestType.DELETE, request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
handleRequest(ResourceMethod.RequestType.GET, request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
handleRequest(ResourceMethod.RequestType.POST, request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
handleRequest(ResourceMethod.RequestType.PUT, request, response);
|
||||
}
|
||||
|
||||
protected void handleRequest(ResourceMethod.RequestType requestType, HttpServletRequest request, HttpServletResponse response) {
|
||||
try {
|
||||
|
||||
response.setContentType(request.getHeader("Accept"));
|
||||
String resourceName = request.getRequestURI();
|
||||
Map<String, String> params = Util.getQueryParams(request.getQueryString());
|
||||
|
||||
Resource resource = resources.get(resourceName);
|
||||
if (null == resource)
|
||||
throw new MethodNotFoundException("No resource available for " + resourceName);
|
||||
|
||||
ResourceMethod resourceMethod = resource.getMethod(params.keySet());
|
||||
if (null == resourceMethod)
|
||||
throw new MethodNotFoundException("No resource method available for the supplied parameters " + params);
|
||||
|
||||
FhirContext ctx = new FhirContext(resourceMethod.getResourceType());
|
||||
XmlParser p = new XmlParser(ctx);
|
||||
response.getWriter().write(p.encodeResourceToString(resourceMethod.invoke(params)));
|
||||
} catch (Throwable t) {
|
||||
// TODO: handle errors
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive method used to find all classes in a given directory and
|
||||
* subdirs.
|
||||
*
|
||||
* @param directory
|
||||
* The base directory
|
||||
* @param packageName
|
||||
* The package name for classes found inside the base directory
|
||||
* @return The classes
|
||||
* @throws ClassNotFoundException
|
||||
*/
|
||||
private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
|
||||
List<Class<?>> classes = new ArrayList<Class<?>>();
|
||||
if (!directory.exists()) {
|
||||
return classes;
|
||||
}
|
||||
File[] files = directory.listFiles();
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
assert !file.getName().contains(".");
|
||||
classes.addAll(findClasses(file, packageName + "." + file.getName()));
|
||||
} else if (file.getName().endsWith(".class")) {
|
||||
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
|
||||
}
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
|
||||
private static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException {
|
||||
|
||||
if (null == packageName)
|
||||
throw new ClassNotFoundException("package name must be specified for JSON operations");
|
||||
|
||||
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
|
||||
assert classLoader != null;
|
||||
String path = packageName.replace('.', '/');
|
||||
Enumeration<URL> resources = classLoader.getResources(path);
|
||||
List<File> dirs = new ArrayList<File>();
|
||||
while (resources.hasMoreElements()) {
|
||||
URL resource = resources.nextElement();
|
||||
dirs.add(new File(resource.getFile()));
|
||||
}
|
||||
|
||||
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
|
||||
for (File directory : dirs) {
|
||||
classes.addAll(findClasses(directory, packageName));
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
}
|
|
@ -1,230 +0,0 @@
|
|||
package ca.uhn.fhir.ws;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import ca.uhn.fhir.context.FhirContext;
|
||||
import ca.uhn.fhir.parser.XmlParser;
|
||||
import ca.uhn.fhir.ws.exceptions.MethodNotFoundException;
|
||||
import ca.uhn.fhir.ws.operations.DELETE;
|
||||
import ca.uhn.fhir.ws.operations.GET;
|
||||
import ca.uhn.fhir.ws.operations.POST;
|
||||
import ca.uhn.fhir.ws.operations.PUT;
|
||||
|
||||
public class Service extends HttpServlet {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(Service.class);
|
||||
private static final String handlerPackage = "ca.uhn.rest.handlers";
|
||||
|
||||
//map of request handler resources keyed by resource name
|
||||
private static Map<String, Resource> resources = new HashMap<String, Resource>();
|
||||
|
||||
/**
|
||||
* looks up all the methods from the classes specified in jsonHandlerPackage environment variable, and puts them in a map,
|
||||
* keyed on the method name.
|
||||
* The handlers for incoming requests will be looked up based on the name.
|
||||
* Method names must be public, static, unique, and must be annotated with JsonOperation.
|
||||
*/
|
||||
|
||||
private List<String> findRESTHanlderPackages(Context env) throws Exception {
|
||||
|
||||
List<String> packages = new ArrayList<String>();
|
||||
|
||||
int i = 1;
|
||||
String origName = handlerPackage;
|
||||
String name = origName;
|
||||
|
||||
while (true) {
|
||||
String handlerPackage = null;
|
||||
try {
|
||||
log.debug("Looking up:: " + name);
|
||||
handlerPackage = (String) env.lookup(name);
|
||||
} catch (NamingException ne) {
|
||||
log.debug("NamingException", ne);
|
||||
}
|
||||
if (handlerPackage != null) {
|
||||
log.debug("Found:: " + name);
|
||||
packages.add(handlerPackage);
|
||||
name = origName + i;
|
||||
i++;
|
||||
} else {
|
||||
log.debug("Not Found:: " + name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (packages.isEmpty()) {
|
||||
throw new Exception("No packages defined as '" + handlerPackage + "' in web.xml");
|
||||
}
|
||||
return packages;
|
||||
}
|
||||
|
||||
private void addResourceMethod(Resource resource, Method method) throws Exception {
|
||||
|
||||
Class<?>[] params = method.getParameterTypes();
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
rm.setResourceType(method.getReturnType());
|
||||
|
||||
//each operation name must have a request type annotation and be unique
|
||||
if (null != method.getAnnotation(GET.class)) {
|
||||
rm.setRequestType(ResourceMethod.RequestType.GET);
|
||||
} else if (null != method.getAnnotation(PUT.class)) {
|
||||
rm.setRequestType(ResourceMethod.RequestType.PUT);
|
||||
} else if (null != method.getAnnotation(POST.class)) {
|
||||
rm.setRequestType(ResourceMethod.RequestType.POST);
|
||||
} else if (null != method.getAnnotation(DELETE.class)) {
|
||||
rm.setRequestType(ResourceMethod.RequestType.DELETE);
|
||||
}
|
||||
rm.setParameters(Util.getResourceParameters(method));
|
||||
resource.addMethod(rm);
|
||||
}
|
||||
|
||||
private void findResourceMethods(Class<?> handler) throws Exception {
|
||||
for (Method m : handler.getDeclaredMethods()) {
|
||||
//only static methods are valid request handlers
|
||||
if (Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) {
|
||||
|
||||
String resourceName = Util.getResourceName(m);
|
||||
Resource r = resources.get(resourceName);
|
||||
if (null == r) {
|
||||
r = new Resource();
|
||||
r.setResourceName(resourceName);
|
||||
resources.put(resourceName, r);
|
||||
}
|
||||
addResourceMethod(r, m);
|
||||
|
||||
log.debug("found handler: " + m.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void init() {
|
||||
try {
|
||||
Context env = (Context) new InitialContext().lookup("java:comp/env");
|
||||
List<String> packages = findRESTHanlderPackages(env);
|
||||
|
||||
for (String packagePath : packages) {
|
||||
log.info("searching for JSON operation handlers in package: " + packagePath);
|
||||
List<Class<?>> handlers = getClasses(packagePath);
|
||||
for (Class<?> handler : handlers) {
|
||||
log.info("found class: " + handler.getName());
|
||||
findResourceMethods(handler);
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.error("An error occurred while loading request handlers!", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
handleRequest(ResourceMethod.RequestType.GET, request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
handleRequest(ResourceMethod.RequestType.POST, request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPut(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
handleRequest(ResourceMethod.RequestType.PUT, request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
handleRequest(ResourceMethod.RequestType.DELETE, request, response);
|
||||
}
|
||||
|
||||
protected void handleRequest(ResourceMethod.RequestType requestType, HttpServletRequest request, HttpServletResponse response) {
|
||||
try {
|
||||
|
||||
response.setContentType(request.getHeader("Accept"));
|
||||
String resourceName = request.getRequestURI();
|
||||
Map<String, String> params = Util.getQueryParams(request.getQueryString());
|
||||
|
||||
Resource resource = resources.get(resourceName);
|
||||
if (null == resource) throw new MethodNotFoundException("No resource available for " + resourceName);
|
||||
|
||||
ResourceMethod resourceMethod = resource.getMethod(params.keySet());
|
||||
if (null == resourceMethod) throw new MethodNotFoundException("No resource method available for the supplied parameters " + params);
|
||||
|
||||
FhirContext ctx = new FhirContext(resourceMethod.getResourceType());
|
||||
XmlParser p = new XmlParser(ctx);
|
||||
response.getWriter().write(p.encodeResourceToString(resourceMethod.invoke(params)));
|
||||
} catch (Throwable t) {
|
||||
//TODO: handle errors
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private static List<Class<?>> getClasses(String packageName)
|
||||
throws ClassNotFoundException, IOException {
|
||||
|
||||
if (null == packageName) throw new ClassNotFoundException("package name must be specified for JSON operations");
|
||||
|
||||
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
|
||||
assert classLoader != null;
|
||||
String path = packageName.replace('.', '/');
|
||||
Enumeration<URL> resources = classLoader.getResources(path);
|
||||
List<File> dirs = new ArrayList<File>();
|
||||
while (resources.hasMoreElements()) {
|
||||
URL resource = resources.nextElement();
|
||||
dirs.add(new File(resource.getFile()));
|
||||
}
|
||||
|
||||
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
|
||||
for (File directory : dirs) {
|
||||
classes.addAll(findClasses(directory, packageName));
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive method used to find all classes in a given directory and subdirs.
|
||||
*
|
||||
* @param directory The base directory
|
||||
* @param packageName The package name for classes found inside the base directory
|
||||
* @return The classes
|
||||
* @throws ClassNotFoundException
|
||||
*/
|
||||
private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
|
||||
List<Class<?>> classes = new ArrayList<Class<?>>();
|
||||
if (!directory.exists()) {
|
||||
return classes;
|
||||
}
|
||||
File[] files = directory.listFiles();
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
assert !file.getName().contains(".");
|
||||
classes.addAll(findClasses(file, packageName + "." + file.getName()));
|
||||
} else if (file.getName().endsWith(".class")) {
|
||||
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
|
||||
}
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package ca.uhn.fhir.testutil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Provides server ports
|
||||
*/
|
||||
public class RandomServerPortProvider {
|
||||
|
||||
private static List<Integer> ourPorts = new ArrayList<Integer>();
|
||||
|
||||
public static int findFreePort() {
|
||||
ServerSocket server;
|
||||
try {
|
||||
server = new ServerSocket(0);
|
||||
int port = server.getLocalPort();
|
||||
ourPorts.add(port);
|
||||
server.close();
|
||||
Thread.sleep(500);
|
||||
return port;
|
||||
} catch (IOException e) {
|
||||
throw new Error(e);
|
||||
} catch (InterruptedException e) {
|
||||
throw new Error(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Integer> list() {
|
||||
return ourPorts;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package ca.uhn.fhir.ws;
|
||||
|
||||
import ca.uhn.fhir.model.dstu.resource.Patient;
|
||||
import ca.uhn.fhir.ws.operations.GET;
|
||||
import ca.uhn.fhir.ws.parameters.Required;
|
||||
|
||||
/**
|
||||
* Created by dsotnikov on 2/25/2014.
|
||||
*/
|
||||
public class DummyPatientResourceProvider implements IResourceProvider<Patient> {
|
||||
|
||||
@GET
|
||||
@ResourceName(value="Patient")
|
||||
public Patient getPatient(@Required(name="mrn") String mrn) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<Patient> getResourceType() {
|
||||
return Patient.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Patient getResourceById(long theId) {
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package ca.uhn.fhir.ws;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
public class DummyRestfulServer extends RestfulServer {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Collection<IResourceProvider<?>> myResourceProviders;
|
||||
|
||||
public DummyRestfulServer(IResourceProvider<?>... theResourceProviders) {
|
||||
myResourceProviders = Arrays.asList(theResourceProviders);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<IResourceProvider<?>> getResourceProviders() {
|
||||
return myResourceProviders;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,18 +0,0 @@
|
|||
package ca.uhn.fhir.ws;
|
||||
|
||||
import ca.uhn.fhir.model.api.IResource;
|
||||
import ca.uhn.fhir.model.dstu.resource.Patient;
|
||||
import ca.uhn.fhir.ws.operations.GET;
|
||||
import ca.uhn.fhir.ws.parameters.Required;
|
||||
|
||||
/**
|
||||
* Created by dsotnikov on 2/25/2014.
|
||||
*/
|
||||
public class PatientResource {
|
||||
|
||||
@GET
|
||||
@ResourceName(value="Patient")
|
||||
public static Patient getPatient(@Required(name="mrn") String mrn) {
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,173 @@
|
|||
package ca.uhn.fhir.ws;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.impl.conn.PoolingClientConnectionManager;
|
||||
import org.apache.http.impl.conn.SchemeRegistryFactory;
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.eclipse.jetty.servlet.ServletHandler;
|
||||
import org.eclipse.jetty.servlet.ServletHolder;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import ca.uhn.fhir.model.dstu.resource.Patient;
|
||||
import ca.uhn.fhir.testutil.RandomServerPortProvider;
|
||||
|
||||
/**
|
||||
* Created by dsotnikov on 2/25/2014.
|
||||
*/
|
||||
public class ResfulServerTest extends TestCase {
|
||||
|
||||
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ResfulServerTest.class);
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
/*
|
||||
* System.setProperty("java.naming.factory.initial",
|
||||
* "org.apache.naming.java.javaURLContextFactory");
|
||||
* System.setProperty("java.naming.factory.url.pkgs",
|
||||
* "org.apache.naming"); InitialContext context = new InitialContext();
|
||||
* //context.bind("java:comp", "env");
|
||||
* context.bind(context.composeName("java:comp", "env"),
|
||||
* "ca.uhn.rest.handlers");
|
||||
*
|
||||
* //Context subcontext = context.createSubcontext("java:comp/env");
|
||||
* //context.bind("java:comp/env/ca.uhn.rest.handlers", "ca.uhn.test");
|
||||
*
|
||||
* Context env = (Context) new InitialContext().lookup("java:comp/env");
|
||||
*
|
||||
* //System.out.println((String) env.lookup("ca.uhn.rest.handlers"));
|
||||
*/
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServlet() throws Exception {
|
||||
int port = RandomServerPortProvider.findFreePort();
|
||||
Server server = new Server(port);
|
||||
|
||||
DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider();
|
||||
|
||||
ServletHandler proxyHandler = new ServletHandler();
|
||||
ServletHolder servletHolder = new ServletHolder(new DummyRestfulServer(patientProvider));
|
||||
proxyHandler.addServletWithMapping(servletHolder, "/");
|
||||
server.setHandler(proxyHandler);
|
||||
server.start();
|
||||
|
||||
PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(SchemeRegistryFactory.createDefault(), 5000, TimeUnit.MILLISECONDS);
|
||||
HttpClient client = new DefaultHttpClient(connectionManager);
|
||||
|
||||
HttpPost httpPost = new HttpPost("http://localhost:" + port + "/foo/bar?bar=123&more=params");
|
||||
httpPost.setEntity(new StringEntity("test", ContentType.create("application/json", "UTF-8")));
|
||||
HttpResponse status = client.execute(httpPost);
|
||||
|
||||
ourLog.info("Response was: {}", status);
|
||||
|
||||
// server.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequiredParamsMissing() {
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
List<Parameter> methodParams = new ArrayList<Parameter>();
|
||||
|
||||
methodParams.add(new Parameter("firstName", false));
|
||||
methodParams.add(new Parameter("lastName", false));
|
||||
methodParams.add(new Parameter("mrn", true));
|
||||
|
||||
rm.setParameters(methodParams);
|
||||
|
||||
Set<String> inputParams = new HashSet<String>();
|
||||
inputParams.add("firstName");
|
||||
inputParams.add("lastName");
|
||||
|
||||
assertEquals(false, rm.matches(inputParams)); // False
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequiredParamsOnly() {
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
List<Parameter> methodParams = new ArrayList<Parameter>();
|
||||
|
||||
methodParams.add(new Parameter("firstName", false));
|
||||
methodParams.add(new Parameter("lastName", false));
|
||||
methodParams.add(new Parameter("mrn", true));
|
||||
|
||||
rm.setParameters(methodParams);
|
||||
|
||||
Set<String> inputParams = new HashSet<String>();
|
||||
inputParams.add("mrn");
|
||||
assertEquals(true, rm.matches(inputParams)); // True
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMixedParams() {
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
List<Parameter> methodParams = new ArrayList<Parameter>();
|
||||
|
||||
methodParams.add(new Parameter("firstName", false));
|
||||
methodParams.add(new Parameter("lastName", false));
|
||||
methodParams.add(new Parameter("mrn", true));
|
||||
|
||||
rm.setParameters(methodParams);
|
||||
|
||||
Set<String> inputParams = new HashSet<String>();
|
||||
inputParams.add("firstName");
|
||||
inputParams.add("mrn");
|
||||
|
||||
assertEquals(true, rm.matches(inputParams)); // True
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAllParams() {
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
List<Parameter> methodParams = new ArrayList<Parameter>();
|
||||
|
||||
methodParams.add(new Parameter("firstName", false));
|
||||
methodParams.add(new Parameter("lastName", false));
|
||||
methodParams.add(new Parameter("mrn", true));
|
||||
|
||||
rm.setParameters(methodParams);
|
||||
|
||||
Set<String> inputParams = new HashSet<String>();
|
||||
inputParams.add("firstName");
|
||||
inputParams.add("lastName");
|
||||
inputParams.add("mrn");
|
||||
|
||||
assertEquals(true, rm.matches(inputParams)); // True
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAllParamsWithExtra() {
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
List<Parameter> methodParams = new ArrayList<Parameter>();
|
||||
|
||||
methodParams.add(new Parameter("firstName", false));
|
||||
methodParams.add(new Parameter("lastName", false));
|
||||
methodParams.add(new Parameter("mrn", true));
|
||||
|
||||
rm.setParameters(methodParams);
|
||||
|
||||
Set<String> inputParams = new HashSet<String>();
|
||||
inputParams.add("firstName");
|
||||
inputParams.add("lastName");
|
||||
inputParams.add("mrn");
|
||||
inputParams.add("foo");
|
||||
|
||||
assertEquals(false, rm.matches(inputParams)); // False
|
||||
}
|
||||
|
||||
}
|
|
@ -1,176 +0,0 @@
|
|||
package ca.uhn.fhir.ws;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.impl.conn.PoolingClientConnectionManager;
|
||||
import org.apache.http.impl.conn.SchemeRegistryFactory;
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.eclipse.jetty.servlet.ServletHandler;
|
||||
import org.eclipse.jetty.servlet.ServletHolder;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Created by dsotnikov on 2/25/2014.
|
||||
*/
|
||||
public class ResourceTest extends TestCase {
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
/*
|
||||
System.setProperty("java.naming.factory.initial", "org.apache.naming.java.javaURLContextFactory");
|
||||
System.setProperty("java.naming.factory.url.pkgs", "org.apache.naming");
|
||||
InitialContext context = new InitialContext();
|
||||
//context.bind("java:comp", "env");
|
||||
context.bind(context.composeName("java:comp", "env"), "ca.uhn.rest.handlers");
|
||||
|
||||
//Context subcontext = context.createSubcontext("java:comp/env");
|
||||
//context.bind("java:comp/env/ca.uhn.rest.handlers", "ca.uhn.test");
|
||||
|
||||
Context env = (Context) new InitialContext().lookup("java:comp/env");
|
||||
|
||||
//System.out.println((String) env.lookup("ca.uhn.rest.handlers"));
|
||||
*/
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServlet() throws Exception {
|
||||
|
||||
Server server = new Server(3000);
|
||||
|
||||
ServletHandler proxyHandler = new ServletHandler();
|
||||
ServletHolder servletHolder = new ServletHolder(new Service());
|
||||
proxyHandler.addServletWithMapping(servletHolder, "/");
|
||||
server.setHandler(proxyHandler);
|
||||
server.start();
|
||||
|
||||
PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(SchemeRegistryFactory.createDefault(), 5000, TimeUnit.MILLISECONDS);
|
||||
HttpClient client = new DefaultHttpClient(connectionManager);
|
||||
|
||||
|
||||
HttpPost httpPost = new HttpPost("http://localhost:3000/foo/bar?bar=123&more=params");
|
||||
httpPost.setEntity(new StringEntity("test", "application/json", "UTF-8"));
|
||||
HttpResponse status = client.execute(httpPost);
|
||||
System.out.println(status);
|
||||
|
||||
// server.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResource() throws Exception {
|
||||
|
||||
//TODO: better params handling
|
||||
for (Method m : PatientResource.class.getDeclaredMethods()) {
|
||||
Util.getResourceParameters(m);
|
||||
|
||||
Integer i = 0;
|
||||
Class<?> c = i.getClass();
|
||||
System.out.println(c.getCanonicalName());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequiredParamsMissing() {
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
List<Parameter> methodParams = new ArrayList<Parameter>();
|
||||
|
||||
methodParams.add(new Parameter("firstName", false));
|
||||
methodParams.add(new Parameter("lastName", false));
|
||||
methodParams.add(new Parameter("mrn", true));
|
||||
|
||||
rm.setParameters(methodParams);
|
||||
|
||||
Set<String> inputParams = new HashSet<String>();
|
||||
inputParams.add("firstName");
|
||||
inputParams.add("lastName");
|
||||
|
||||
assertEquals(false, rm.matches(inputParams)); //False
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequiredParamsOnly() {
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
List<Parameter> methodParams = new ArrayList<Parameter>();
|
||||
|
||||
methodParams.add(new Parameter("firstName", false));
|
||||
methodParams.add(new Parameter("lastName", false));
|
||||
methodParams.add(new Parameter("mrn", true));
|
||||
|
||||
rm.setParameters(methodParams);
|
||||
|
||||
Set<String> inputParams = new HashSet<String>();
|
||||
inputParams.add("mrn");
|
||||
assertEquals(true, rm.matches(inputParams)); //True
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMixedParams() {
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
List<Parameter> methodParams = new ArrayList<Parameter>();
|
||||
|
||||
methodParams.add(new Parameter("firstName", false));
|
||||
methodParams.add(new Parameter("lastName", false));
|
||||
methodParams.add(new Parameter("mrn", true));
|
||||
|
||||
rm.setParameters(methodParams);
|
||||
|
||||
Set<String> inputParams = new HashSet<String>();
|
||||
inputParams.add("firstName");
|
||||
inputParams.add("mrn");
|
||||
|
||||
assertEquals(true, rm.matches(inputParams)); //True
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAllParams() {
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
List<Parameter> methodParams = new ArrayList<Parameter>();
|
||||
|
||||
methodParams.add(new Parameter("firstName", false));
|
||||
methodParams.add(new Parameter("lastName", false));
|
||||
methodParams.add(new Parameter("mrn", true));
|
||||
|
||||
rm.setParameters(methodParams);
|
||||
|
||||
Set<String> inputParams = new HashSet<String>();
|
||||
inputParams.add("firstName");
|
||||
inputParams.add("lastName");
|
||||
inputParams.add("mrn");
|
||||
|
||||
assertEquals(true, rm.matches(inputParams)); //True
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAllParamsWithExtra() {
|
||||
ResourceMethod rm = new ResourceMethod();
|
||||
List<Parameter> methodParams = new ArrayList<Parameter>();
|
||||
|
||||
methodParams.add(new Parameter("firstName", false));
|
||||
methodParams.add(new Parameter("lastName", false));
|
||||
methodParams.add(new Parameter("mrn", true));
|
||||
|
||||
rm.setParameters(methodParams);
|
||||
|
||||
Set<String> inputParams = new HashSet<String>();
|
||||
inputParams.add("firstName");
|
||||
inputParams.add("lastName");
|
||||
inputParams.add("mrn");
|
||||
inputParams.add("foo");
|
||||
|
||||
assertEquals(false, rm.matches(inputParams)); //False
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue