001/* 002 * #%L 003 * HAPI FHIR - Server Framework 004 * %% 005 * Copyright (C) 2014 - 2024 Smile CDR, Inc. 006 * %% 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 * #L% 019 */ 020package ca.uhn.fhir.rest.server; 021 022import ca.uhn.fhir.context.ConfigurationException; 023import ca.uhn.fhir.context.FhirContext; 024import ca.uhn.fhir.context.RuntimeResourceDefinition; 025import ca.uhn.fhir.context.api.AddProfileTagEnum; 026import ca.uhn.fhir.context.api.BundleInclusionRule; 027import ca.uhn.fhir.i18n.Msg; 028import ca.uhn.fhir.interceptor.api.HookParams; 029import ca.uhn.fhir.interceptor.api.IInterceptorService; 030import ca.uhn.fhir.interceptor.api.Pointcut; 031import ca.uhn.fhir.interceptor.executor.InterceptorService; 032import ca.uhn.fhir.model.primitive.InstantDt; 033import ca.uhn.fhir.parser.IParser; 034import ca.uhn.fhir.rest.annotation.Destroy; 035import ca.uhn.fhir.rest.annotation.IdParam; 036import ca.uhn.fhir.rest.annotation.Initialize; 037import ca.uhn.fhir.rest.api.Constants; 038import ca.uhn.fhir.rest.api.EncodingEnum; 039import ca.uhn.fhir.rest.api.MethodOutcome; 040import ca.uhn.fhir.rest.api.PreferReturnEnum; 041import ca.uhn.fhir.rest.api.RequestTypeEnum; 042import ca.uhn.fhir.rest.api.RestOperationTypeEnum; 043import ca.uhn.fhir.rest.api.server.BaseParseAction; 044import ca.uhn.fhir.rest.api.server.IFhirVersionServer; 045import ca.uhn.fhir.rest.api.server.IRestfulServer; 046import ca.uhn.fhir.rest.api.server.RequestDetails; 047import ca.uhn.fhir.rest.server.RestfulServerUtils.ResponseEncoding; 048import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; 049import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; 050import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; 051import ca.uhn.fhir.rest.server.exceptions.NotModifiedException; 052import ca.uhn.fhir.rest.server.exceptions.ResourceGoneException; 053import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; 054import ca.uhn.fhir.rest.server.interceptor.ExceptionHandlingInterceptor; 055import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor; 056import ca.uhn.fhir.rest.server.method.BaseMethodBinding; 057import ca.uhn.fhir.rest.server.method.ConformanceMethodBinding; 058import ca.uhn.fhir.rest.server.method.MethodMatchEnum; 059import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; 060import ca.uhn.fhir.rest.server.tenant.ITenantIdentificationStrategy; 061import ca.uhn.fhir.util.CoverageIgnore; 062import ca.uhn.fhir.util.OperationOutcomeUtil; 063import ca.uhn.fhir.util.ReflectionUtil; 064import ca.uhn.fhir.util.UrlPathTokenizer; 065import ca.uhn.fhir.util.UrlUtil; 066import ca.uhn.fhir.util.VersionUtil; 067import com.google.common.collect.Lists; 068import jakarta.annotation.Nonnull; 069import jakarta.annotation.Nullable; 070import jakarta.servlet.ServletException; 071import jakarta.servlet.UnavailableException; 072import jakarta.servlet.http.HttpServlet; 073import jakarta.servlet.http.HttpServletRequest; 074import jakarta.servlet.http.HttpServletResponse; 075import org.apache.commons.lang3.RandomStringUtils; 076import org.apache.commons.lang3.StringUtils; 077import org.apache.commons.lang3.Validate; 078import org.hl7.fhir.instance.model.api.IBaseConformance; 079import org.hl7.fhir.instance.model.api.IBaseOperationOutcome; 080import org.hl7.fhir.instance.model.api.IBaseResource; 081import org.hl7.fhir.instance.model.api.IIdType; 082import org.slf4j.Logger; 083import org.slf4j.LoggerFactory; 084 085import java.io.IOException; 086import java.io.InputStream; 087import java.io.Writer; 088import java.lang.annotation.Annotation; 089import java.lang.reflect.Method; 090import java.lang.reflect.Modifier; 091import java.util.ArrayList; 092import java.util.Arrays; 093import java.util.Collection; 094import java.util.Collections; 095import java.util.Date; 096import java.util.HashMap; 097import java.util.HashSet; 098import java.util.Iterator; 099import java.util.List; 100import java.util.ListIterator; 101import java.util.Map; 102import java.util.Map.Entry; 103import java.util.Set; 104import java.util.concurrent.locks.Lock; 105import java.util.concurrent.locks.ReentrantLock; 106import java.util.jar.Manifest; 107 108import static ca.uhn.fhir.util.StringUtil.toUtf8String; 109import static java.util.stream.Collectors.toList; 110import static org.apache.commons.lang3.StringUtils.isBlank; 111import static org.apache.commons.lang3.StringUtils.isNotBlank; 112 113/** 114 * This class is the central class for the HAPI FHIR Plain Server framework. 115 * <p> 116 * See <a href="https://hapifhir.io/hapi-fhir/docs/server_plain/">HAPI FHIR Plain Server</a> 117 * for information on how to use this framework. 118 */ 119@SuppressWarnings("WeakerAccess") 120public class RestfulServer extends HttpServlet implements IRestfulServer<ServletRequestDetails> { 121 122 /** 123 * All incoming requests will have an attribute added to {@link HttpServletRequest#getAttribute(String)} 124 * with this key. The value will be a Java {@link Date} with the time that request processing began. 125 */ 126 public static final String REQUEST_START_TIME = RestfulServer.class.getName() + "REQUEST_START_TIME"; 127 /** 128 * Default setting for {@link #setETagSupport(ETagSupportEnum) ETag Support}: {@link ETagSupportEnum#ENABLED} 129 */ 130 public static final ETagSupportEnum DEFAULT_ETAG_SUPPORT = ETagSupportEnum.ENABLED; 131 /** 132 * Requests will have an HttpServletRequest attribute set with this name, containing the servlet 133 * context, in order to avoid a dependency on Servlet-API 3.0+ 134 */ 135 public static final String SERVLET_CONTEXT_ATTRIBUTE = "ca.uhn.fhir.rest.server.RestfulServer.servlet_context"; 136 /** 137 * Default value for {@link #setDefaultPreferReturn(PreferReturnEnum)} 138 */ 139 public static final PreferReturnEnum DEFAULT_PREFER_RETURN = PreferReturnEnum.REPRESENTATION; 140 141 private static final ExceptionHandlingInterceptor DEFAULT_EXCEPTION_HANDLER = new ExceptionHandlingInterceptor(); 142 private static final Logger ourLog = LoggerFactory.getLogger(RestfulServer.class); 143 private static final long serialVersionUID = 1L; 144 private final List<Object> myPlainProviders = new ArrayList<>(); 145 private final List<IResourceProvider> myResourceProviders = new ArrayList<>(); 146 private IInterceptorService myInterceptorService; 147 private BundleInclusionRule myBundleInclusionRule = BundleInclusionRule.BASED_ON_INCLUDES; 148 private boolean myDefaultPrettyPrint = false; 149 private EncodingEnum myDefaultResponseEncoding = EncodingEnum.JSON; 150 private ETagSupportEnum myETagSupport = DEFAULT_ETAG_SUPPORT; 151 private FhirContext myFhirContext; 152 private boolean myIgnoreServerParsedRequestParameters = true; 153 private String myImplementationDescription; 154 private String myCopyright; 155 private IPagingProvider myPagingProvider; 156 private Integer myDefaultPageSize; 157 private Integer myMaximumPageSize; 158 private boolean myStatelessPagingDefault = false; 159 private Lock myProviderRegistrationMutex = new ReentrantLock(); 160 private Map<String, ResourceBinding> myResourceNameToBinding = new HashMap<>(); 161 private IServerAddressStrategy myServerAddressStrategy = new IncomingRequestAddressStrategy(); 162 private ResourceBinding myServerBinding = new ResourceBinding(); 163 private ResourceBinding myGlobalBinding = new ResourceBinding(); 164 private ConformanceMethodBinding myServerConformanceMethod; 165 private Object myServerConformanceProvider; 166 private String myServerName = "HAPI FHIR Server"; 167 /** 168 * This is configurable but by default we just use HAPI version 169 */ 170 private String myServerVersion = createPoweredByHeaderProductVersion(); 171 172 private boolean myStarted; 173 private boolean myUncompressIncomingContents = true; 174 private ITenantIdentificationStrategy myTenantIdentificationStrategy; 175 private PreferReturnEnum myDefaultPreferReturn = DEFAULT_PREFER_RETURN; 176 private ElementsSupportEnum myElementsSupport = ElementsSupportEnum.EXTENDED; 177 178 /** 179 * Constructor. Note that if no {@link FhirContext} is passed in to the server (either through the constructor, or 180 * through {@link #setFhirContext(FhirContext)}) the server will determine which 181 * version of FHIR to support through classpath scanning. This is brittle, and it is highly recommended to explicitly 182 * specify a FHIR version. 183 */ 184 public RestfulServer() { 185 this(null); 186 } 187 188 /** 189 * Constructor 190 */ 191 public RestfulServer(FhirContext theCtx) { 192 this(theCtx, new InterceptorService("RestfulServer")); 193 } 194 195 public RestfulServer(FhirContext theCtx, IInterceptorService theInterceptorService) { 196 myFhirContext = theCtx; 197 setInterceptorService(theInterceptorService); 198 } 199 200 /** 201 * @since 5.5.0 202 */ 203 public ConformanceMethodBinding getServerConformanceMethod() { 204 return myServerConformanceMethod; 205 } 206 207 private void addContentLocationHeaders( 208 RequestDetails theRequest, 209 HttpServletResponse servletResponse, 210 MethodOutcome response, 211 String resourceName) { 212 if (response != null && response.getId() != null) { 213 addLocationHeader(theRequest, servletResponse, response, Constants.HEADER_LOCATION, resourceName); 214 addLocationHeader(theRequest, servletResponse, response, Constants.HEADER_CONTENT_LOCATION, resourceName); 215 } 216 } 217 218 /** 219 * This method is called prior to sending a response to incoming requests. It is used to add custom headers. 220 * <p> 221 * Use caution if overriding this method: it is recommended to call <code>super.addHeadersToResponse</code> to avoid 222 * inadvertently disabling functionality. 223 * </p> 224 */ 225 public void addHeadersToResponse(HttpServletResponse theHttpResponse) { 226 String poweredByHeader = createPoweredByHeader(); 227 if (isNotBlank(poweredByHeader)) { 228 theHttpResponse.addHeader(Constants.POWERED_BY_HEADER, poweredByHeader); 229 } 230 } 231 232 private void addLocationHeader( 233 RequestDetails theRequest, 234 HttpServletResponse theResponse, 235 MethodOutcome response, 236 String headerLocation, 237 String resourceName) { 238 StringBuilder b = new StringBuilder(); 239 b.append(theRequest.getFhirServerBase()); 240 b.append('/'); 241 b.append(resourceName); 242 b.append('/'); 243 b.append(response.getId().getIdPart()); 244 if (response.getId().hasVersionIdPart()) { 245 b.append("/" + Constants.PARAM_HISTORY + "/"); 246 b.append(response.getId().getVersionIdPart()); 247 } 248 theResponse.addHeader(headerLocation, b.toString()); 249 } 250 251 public RestfulServerConfiguration createConfiguration() { 252 RestfulServerConfiguration result = new RestfulServerConfiguration(); 253 result.setResourceBindings(getResourceBindings()); 254 result.setServerBindings(getServerBindings()); 255 result.setGlobalBindings(getGlobalBindings()); 256 result.setImplementationDescription(getImplementationDescription()); 257 result.setServerVersion(getServerVersion()); 258 result.setServerName(getServerName()); 259 result.setFhirContext(getFhirContext()); 260 result.setServerAddressStrategy(myServerAddressStrategy); 261 try (InputStream inputStream = getClass().getResourceAsStream("/META-INF/MANIFEST.MF")) { 262 if (inputStream != null) { 263 Manifest manifest = new Manifest(inputStream); 264 String value = manifest.getMainAttributes().getValue("Build-Time"); 265 result.setConformanceDate(new InstantDt(value)); 266 } 267 } catch (Exception e) { 268 // fall through 269 } 270 result.computeSharedSupertypeForResourcePerName(getResourceProviders()); 271 return result; 272 } 273 274 private List<BaseMethodBinding> getGlobalBindings() { 275 return myGlobalBinding.getMethodBindings(); 276 } 277 278 protected List<String> createPoweredByAttributes() { 279 return Lists.newArrayList( 280 "FHIR Server", 281 "FHIR " + myFhirContext.getVersion().getVersion().getFhirVersionString() + "/" 282 + myFhirContext.getVersion().getVersion().name()); 283 } 284 285 /** 286 * Subclasses may override to provide their own powered by 287 * header. Note that if you want to be nice and still credit HAPI 288 * FHIR you could consider overriding 289 * {@link #createPoweredByAttributes()} instead and adding your own 290 * fragments to the list. 291 */ 292 protected String createPoweredByHeader() { 293 StringBuilder b = new StringBuilder(); 294 b.append(createPoweredByHeaderProductName()); 295 b.append(" "); 296 b.append(createPoweredByHeaderProductVersion()); 297 b.append(" "); 298 b.append(createPoweredByHeaderComponentName()); 299 b.append(" ("); 300 301 List<String> poweredByAttributes = createPoweredByAttributes(); 302 for (ListIterator<String> iter = poweredByAttributes.listIterator(); iter.hasNext(); ) { 303 if (iter.nextIndex() > 0) { 304 b.append("; "); 305 } 306 b.append(iter.next()); 307 } 308 309 b.append(")"); 310 return b.toString(); 311 } 312 313 /** 314 * Subclasses my override 315 * 316 * @see #createPoweredByHeader() 317 */ 318 protected String createPoweredByHeaderComponentName() { 319 return "REST Server"; 320 } 321 322 /** 323 * Subclasses my override 324 * 325 * @see #createPoweredByHeader() 326 */ 327 protected String createPoweredByHeaderProductName() { 328 return "HAPI FHIR"; 329 } 330 331 /** 332 * Subclasses my override 333 * 334 * @see #createPoweredByHeader() 335 */ 336 protected String createPoweredByHeaderProductVersion() { 337 String version = VersionUtil.getVersion(); 338 if (VersionUtil.isSnapshot()) { 339 version = version + "/" + VersionUtil.getBuildNumber() + "/" + VersionUtil.getBuildDate(); 340 } 341 return version; 342 } 343 344 @Override 345 public void destroy() { 346 if (getResourceProviders() != null) { 347 for (IResourceProvider iResourceProvider : getResourceProviders()) { 348 invokeDestroy(iResourceProvider); 349 } 350 } 351 352 if (myServerConformanceProvider != null) { 353 invokeDestroy(myServerConformanceProvider); 354 } 355 356 if (getPlainProviders() != null) { 357 for (Object next : getPlainProviders()) { 358 invokeDestroy(next); 359 } 360 } 361 362 if (myServerConformanceMethod != null) { 363 myServerConformanceMethod.close(); 364 } 365 myResourceNameToBinding.values().stream() 366 .flatMap(t -> t.getMethodBindings().stream()) 367 .forEach(t -> t.close()); 368 myGlobalBinding.getMethodBindings().forEach(t -> t.close()); 369 myServerBinding.getMethodBindings().forEach(t -> t.close()); 370 371 myResourceNameToBinding.clear(); 372 myGlobalBinding.getMethodBindings().clear(); 373 myServerBinding.getMethodBindings().clear(); 374 } 375 376 /** 377 * Figure out and return whichever method binding is appropriate for 378 * the given request 379 */ 380 public BaseMethodBinding determineResourceMethod(RequestDetails requestDetails, String requestPath) { 381 RequestTypeEnum requestType = requestDetails.getRequestType(); 382 383 ResourceBinding resourceBinding = null; 384 BaseMethodBinding resourceMethod = null; 385 String resourceName = requestDetails.getResourceName(); 386 if (myServerConformanceMethod.incomingServerRequestMatchesMethod(requestDetails) != MethodMatchEnum.NONE) { 387 resourceMethod = myServerConformanceMethod; 388 } else if (resourceName == null) { 389 resourceBinding = myServerBinding; 390 } else { 391 resourceBinding = myResourceNameToBinding.get(resourceName); 392 if (resourceBinding == null) { 393 throwUnknownResourceTypeException(resourceName); 394 } 395 } 396 397 if (resourceMethod == null) { 398 if (resourceBinding != null) { 399 resourceMethod = resourceBinding.getMethod(requestDetails); 400 } 401 if (resourceMethod == null) { 402 resourceMethod = myGlobalBinding.getMethod(requestDetails); 403 } 404 } 405 if (resourceMethod == null) { 406 if (isBlank(requestPath)) { 407 throw new InvalidRequestException( 408 Msg.code(287) + myFhirContext.getLocalizer().getMessage(RestfulServer.class, "rootRequest")); 409 } 410 throwUnknownFhirOperationException(requestDetails, requestPath, requestType); 411 } 412 return resourceMethod; 413 } 414 415 @Override 416 protected void doDelete(HttpServletRequest request, HttpServletResponse response) 417 throws ServletException, IOException { 418 handleRequest(RequestTypeEnum.DELETE, request, response); 419 } 420 421 @Override 422 protected void doGet(HttpServletRequest request, HttpServletResponse response) 423 throws ServletException, IOException { 424 handleRequest(RequestTypeEnum.GET, request, response); 425 } 426 427 @Override 428 protected void doOptions(HttpServletRequest theReq, HttpServletResponse theResp) 429 throws ServletException, IOException { 430 handleRequest(RequestTypeEnum.OPTIONS, theReq, theResp); 431 } 432 433 @Override 434 protected void doPost(HttpServletRequest request, HttpServletResponse response) 435 throws ServletException, IOException { 436 handleRequest(RequestTypeEnum.POST, request, response); 437 } 438 439 @Override 440 protected void doPut(HttpServletRequest request, HttpServletResponse response) 441 throws ServletException, IOException { 442 handleRequest(RequestTypeEnum.PUT, request, response); 443 } 444 445 private void findResourceMethods(Object theProvider) { 446 447 ourLog.debug("Scanning type for RESTful methods: {}", theProvider.getClass()); 448 int count = 0; 449 450 Class<?> clazz = theProvider.getClass(); 451 Class<?> supertype = clazz.getSuperclass(); 452 while (!Object.class.equals(supertype)) { 453 count += findResourceMethodsOnInterfaces(theProvider, supertype.getInterfaces()); 454 count += findResourceMethods(theProvider, supertype); 455 supertype = supertype.getSuperclass(); 456 } 457 458 try { 459 count += findResourceMethodsOnInterfaces(theProvider, clazz.getInterfaces()); 460 count += findResourceMethods(theProvider, clazz); 461 } catch (ConfigurationException e) { 462 throw new ConfigurationException( 463 Msg.code(288) + "Failure scanning class " + clazz.getSimpleName() + ": " + e.getMessage(), e); 464 } 465 if (count == 0) { 466 throw new ConfigurationException( 467 Msg.code(289) + "Did not find any annotated RESTful methods on provider class " 468 + theProvider.getClass().getName()); 469 } 470 } 471 472 private int findResourceMethodsOnInterfaces(Object theProvider, Class<?>[] interfaces) { 473 int count = 0; 474 for (Class<?> anInterface : interfaces) { 475 count += findResourceMethodsOnInterfaces(theProvider, anInterface.getInterfaces()); 476 count += findResourceMethods(theProvider, anInterface); 477 } 478 return count; 479 } 480 481 private int findResourceMethods(Object theProvider, Class<?> clazz) throws ConfigurationException { 482 int count = 0; 483 484 for (Method m : ReflectionUtil.getDeclaredMethods(clazz)) { 485 BaseMethodBinding foundMethodBinding = BaseMethodBinding.bindMethod(m, getFhirContext(), theProvider); 486 if (foundMethodBinding == null) { 487 continue; 488 } 489 490 count++; 491 492 if (foundMethodBinding instanceof ConformanceMethodBinding) { 493 myServerConformanceMethod = (ConformanceMethodBinding) foundMethodBinding; 494 if (myServerConformanceProvider == null) { 495 myServerConformanceProvider = theProvider; 496 } 497 continue; 498 } 499 500 if (!Modifier.isPublic(m.getModifiers())) { 501 throw new ConfigurationException(Msg.code(290) + "Method '" + m.getName() 502 + "' is not public, FHIR RESTful methods must be public"); 503 } 504 if (Modifier.isStatic(m.getModifiers())) { 505 throw new ConfigurationException(Msg.code(291) + "Method '" + m.getName() 506 + "' is static, FHIR RESTful methods must not be static"); 507 } 508 ourLog.trace("Scanning public method: {}#{}", theProvider.getClass(), m.getName()); 509 510 // Interceptor call: SERVER_PROVIDER_METHOD_BOUND 511 if (myInterceptorService.hasHooks(Pointcut.SERVER_PROVIDER_METHOD_BOUND)) { 512 HookParams params = new HookParams().add(BaseMethodBinding.class, foundMethodBinding); 513 BaseMethodBinding newMethodBinding = (BaseMethodBinding) 514 myInterceptorService.callHooksAndReturnObject(Pointcut.SERVER_PROVIDER_METHOD_BOUND, params); 515 if (newMethodBinding == null) { 516 ourLog.info( 517 "Method binding {} was discarded by interceptor and will not be registered", 518 foundMethodBinding); 519 continue; 520 } 521 foundMethodBinding = newMethodBinding; 522 } 523 524 String resourceName = foundMethodBinding.getResourceName(); 525 ResourceBinding resourceBinding; 526 if (resourceName == null) { 527 if (foundMethodBinding.isGlobalMethod()) { 528 resourceBinding = myGlobalBinding; 529 } else { 530 resourceBinding = myServerBinding; 531 } 532 } else { 533 RuntimeResourceDefinition definition = getFhirContext().getResourceDefinition(resourceName); 534 if (myResourceNameToBinding.containsKey(definition.getName())) { 535 resourceBinding = myResourceNameToBinding.get(definition.getName()); 536 } else { 537 resourceBinding = new ResourceBinding(); 538 resourceBinding.setResourceName(resourceName); 539 myResourceNameToBinding.put(resourceName, resourceBinding); 540 } 541 } 542 543 List<Class<?>> allowableParams = foundMethodBinding.getAllowableParamAnnotations(); 544 if (allowableParams != null) { 545 for (Annotation[] nextParamAnnotations : m.getParameterAnnotations()) { 546 for (Annotation annotation : nextParamAnnotations) { 547 Package pack = annotation.annotationType().getPackage(); 548 if (pack.equals(IdParam.class.getPackage())) { 549 if (!allowableParams.contains(annotation.annotationType())) { 550 throw new ConfigurationException(Msg.code(292) + "Method[" + m 551 + "] is not allowed to have a parameter annotated with " + annotation); 552 } 553 } 554 } 555 } 556 } 557 558 resourceBinding.addMethod(foundMethodBinding); 559 ourLog.trace(" * Method: {}#{} is a handler", theProvider.getClass(), m.getName()); 560 } 561 562 return count; 563 } 564 565 /** 566 * @deprecated As of HAPI FHIR 1.5, this property has been moved to 567 * {@link FhirContext#setAddProfileTagWhenEncoding(AddProfileTagEnum)} 568 */ 569 @Override 570 @Deprecated 571 public AddProfileTagEnum getAddProfileTag() { 572 return myFhirContext.getAddProfileTagWhenEncoding(); 573 } 574 575 /** 576 * Sets the profile tagging behaviour for the server. When set to a value other than {@link AddProfileTagEnum#NEVER} 577 * (which is the default), the server will automatically add a profile tag based on 578 * the class of the resource(s) being returned. 579 * 580 * @param theAddProfileTag The behaviour enum (must not be null) 581 * @deprecated As of HAPI FHIR 1.5, this property has been moved to 582 * {@link FhirContext#setAddProfileTagWhenEncoding(AddProfileTagEnum)} 583 */ 584 @Deprecated 585 @CoverageIgnore 586 public void setAddProfileTag(AddProfileTagEnum theAddProfileTag) { 587 Validate.notNull(theAddProfileTag, "theAddProfileTag must not be null"); 588 myFhirContext.setAddProfileTagWhenEncoding(theAddProfileTag); 589 } 590 591 @Override 592 public BundleInclusionRule getBundleInclusionRule() { 593 return myBundleInclusionRule; 594 } 595 596 /** 597 * Set how bundle factory should decide whether referenced resources should be included in bundles 598 * 599 * @param theBundleInclusionRule - inclusion rule (@see BundleInclusionRule for behaviors) 600 */ 601 public void setBundleInclusionRule(BundleInclusionRule theBundleInclusionRule) { 602 myBundleInclusionRule = theBundleInclusionRule; 603 } 604 605 /** 606 * Returns the default encoding to return (XML/JSON) if an incoming request does not specify a preference (either 607 * with the <code>_format</code> URL parameter, or with an <code>Accept</code> header 608 * in the request. The default is {@link EncodingEnum#XML}. Will not return null. 609 */ 610 @Override 611 public EncodingEnum getDefaultResponseEncoding() { 612 return myDefaultResponseEncoding; 613 } 614 615 /** 616 * Sets the default encoding to return (XML/JSON) if an incoming request does not specify a preference (either with 617 * the <code>_format</code> URL parameter, or with an <code>Accept</code> header in 618 * the request. The default is {@link EncodingEnum#XML}. 619 * <p> 620 * Note when testing this feature: Some browsers will include "application/xml" in their Accept header, which means 621 * that the 622 * </p> 623 */ 624 public void setDefaultResponseEncoding(EncodingEnum theDefaultResponseEncoding) { 625 Validate.notNull(theDefaultResponseEncoding, "theDefaultResponseEncoding can not be null"); 626 myDefaultResponseEncoding = theDefaultResponseEncoding; 627 } 628 629 @Override 630 public ETagSupportEnum getETagSupport() { 631 return myETagSupport; 632 } 633 634 /** 635 * Sets (enables/disables) the server support for ETags. Must not be <code>null</code>. Default is 636 * {@link #DEFAULT_ETAG_SUPPORT} 637 * 638 * @param theETagSupport The ETag support mode 639 */ 640 public void setETagSupport(ETagSupportEnum theETagSupport) { 641 if (theETagSupport == null) { 642 throw new NullPointerException(Msg.code(293) + "theETagSupport can not be null"); 643 } 644 myETagSupport = theETagSupport; 645 } 646 647 @Override 648 public ElementsSupportEnum getElementsSupport() { 649 return myElementsSupport; 650 } 651 652 /** 653 * Sets the elements support mode. 654 * 655 * @see <a href="http://hapifhir.io/doc_rest_server.html#extended_elements_support">Extended Elements Support</a> 656 */ 657 public void setElementsSupport(ElementsSupportEnum theElementsSupport) { 658 Validate.notNull(theElementsSupport, "theElementsSupport must not be null"); 659 myElementsSupport = theElementsSupport; 660 } 661 662 /** 663 * Gets the {@link FhirContext} associated with this server. For efficient processing, resource providers and plain 664 * providers should generally use this context if one is needed, as opposed to 665 * creating their own. 666 */ 667 @Override 668 public FhirContext getFhirContext() { 669 if (myFhirContext == null) { 670 // TODO: Use of a deprecated method should be resolved. 671 myFhirContext = new FhirContext(); 672 } 673 return myFhirContext; 674 } 675 676 public void setFhirContext(FhirContext theFhirContext) { 677 Validate.notNull(theFhirContext, "FhirContext must not be null"); 678 myFhirContext = theFhirContext; 679 } 680 681 public String getImplementationDescription() { 682 return myImplementationDescription; 683 } 684 685 public void setImplementationDescription(String theImplementationDescription) { 686 myImplementationDescription = theImplementationDescription; 687 } 688 689 /** 690 * Returns the server copyright (will be added to the CapabilityStatement). Note that FHIR allows Markdown in this string. 691 */ 692 public String getCopyright() { 693 return myCopyright; 694 } 695 696 /** 697 * Sets the server copyright (will be added to the CapabilityStatement). Note that FHIR allows Markdown in this string. 698 */ 699 public void setCopyright(String theCopyright) { 700 myCopyright = theCopyright; 701 } 702 703 /** 704 * Returns a list of all registered server interceptors 705 * 706 * @deprecated As of HAPI FHIR 3.8.0, use {@link #getInterceptorService()} to access the interceptor service. You can register and unregister interceptors using this service. 707 */ 708 @Deprecated 709 @Override 710 public List<IServerInterceptor> getInterceptors_() { 711 List<IServerInterceptor> retVal = getInterceptorService().getAllRegisteredInterceptors().stream() 712 .filter(t -> t instanceof IServerInterceptor) 713 .map(t -> (IServerInterceptor) t) 714 .collect(toList()); 715 return Collections.unmodifiableList(retVal); 716 } 717 718 /** 719 * Returns the interceptor registry for this service. Use this registry to register and unregister 720 * 721 * @since 3.8.0 722 */ 723 @Override 724 public IInterceptorService getInterceptorService() { 725 return myInterceptorService; 726 } 727 728 /** 729 * Sets the interceptor registry for this service. Use this registry to register and unregister 730 * 731 * @since 3.8.0 732 */ 733 public void setInterceptorService(@Nonnull IInterceptorService theInterceptorService) { 734 Validate.notNull(theInterceptorService, "theInterceptorService must not be null"); 735 myInterceptorService = theInterceptorService; 736 } 737 738 /** 739 * Sets (or clears) the list of interceptors 740 * 741 * @param theList The list of interceptors (may be null) 742 * @deprecated As of HAPI FHIR 3.8.0, use {@link #getInterceptorService()} to access the interceptor service. You can register and unregister interceptors using this service. 743 */ 744 @Deprecated 745 public void setInterceptors(@Nonnull List<?> theList) { 746 myInterceptorService.unregisterAllInterceptors(); 747 myInterceptorService.registerInterceptors(theList); 748 } 749 750 /** 751 * Sets (or clears) the list of interceptors 752 * 753 * @param theInterceptors The list of interceptors (may be null) 754 * @deprecated As of HAPI FHIR 3.8.0, use {@link #getInterceptorService()} to access the interceptor service. You can register and unregister interceptors using this service. 755 */ 756 @Deprecated 757 public void setInterceptors(IServerInterceptor... theInterceptors) { 758 Validate.noNullElements(theInterceptors, "theInterceptors must not contain any null elements"); 759 setInterceptors(Arrays.asList(theInterceptors)); 760 } 761 762 @Override 763 public IPagingProvider getPagingProvider() { 764 return myPagingProvider; 765 } 766 767 /** 768 * Sets the paging provider to use, or <code>null</code> to use no paging (which is the default). 769 * This will set defaultPageSize and maximumPageSize from the paging provider. 770 */ 771 public void setPagingProvider(IPagingProvider thePagingProvider) { 772 myPagingProvider = thePagingProvider; 773 if (myPagingProvider != null) { 774 setDefaultPageSize(myPagingProvider.getDefaultPageSize()); 775 setMaximumPageSize(myPagingProvider.getMaximumPageSize()); 776 } 777 } 778 779 @Override 780 public Integer getDefaultPageSize() { 781 return myDefaultPageSize; 782 } 783 784 /** 785 * Sets the default page size to use, or <code>null</code> if no default page size 786 */ 787 public void setDefaultPageSize(Integer thePageSize) { 788 myDefaultPageSize = thePageSize; 789 } 790 791 @Override 792 public Integer getMaximumPageSize() { 793 return myMaximumPageSize; 794 } 795 796 /** 797 * Sets the maximum page size to use, or <code>null</code> if no maximum page size 798 */ 799 public void setMaximumPageSize(Integer theMaximumPageSize) { 800 myMaximumPageSize = theMaximumPageSize; 801 } 802 803 /** 804 * Provides the non-resource specific providers which implement method calls on this server 805 * 806 * @see #getResourceProviders() 807 */ 808 public Collection<Object> getPlainProviders() { 809 return myPlainProviders; 810 } 811 812 /** 813 * Sets the non-resource specific providers which implement method calls on this server. 814 * 815 * @see #setResourceProviders(Collection) 816 * @deprecated This method causes inconsistent behaviour depending on the order it is called in. Use {@link #registerProviders(Object...)} instead. 817 */ 818 @Deprecated 819 public void setPlainProviders(Object... theProv) { 820 setPlainProviders(Arrays.asList(theProv)); 821 } 822 823 /** 824 * Sets the non-resource specific providers which implement method calls on this server. 825 * 826 * @see #setResourceProviders(Collection) 827 * @deprecated This method causes inconsistent behaviour depending on the order it is called in. Use {@link #registerProviders(Object...)} instead. 828 */ 829 @Deprecated 830 public void setPlainProviders(Collection<Object> theProviders) { 831 Validate.noNullElements(theProviders, "theProviders must not contain any null elements"); 832 833 myPlainProviders.clear(); 834 myPlainProviders.addAll(theProviders); 835 } 836 837 /** 838 * Allows users of RestfulServer to override the getRequestPath method to let them build their custom request path 839 * implementation 840 * 841 * @param requestFullPath the full request path 842 * @param servletContextPath the servelet context path 843 * @param servletPath the servelet path 844 * @return created resource path 845 */ 846 // NOTE: Don't make this a static method!! People want to override it 847 protected String getRequestPath(String requestFullPath, String servletContextPath, String servletPath) { 848 return requestFullPath.substring(escapedLength(servletContextPath) + escapedLength(servletPath)); 849 } 850 851 public Collection<ResourceBinding> getResourceBindings() { 852 return myResourceNameToBinding.values(); 853 } 854 855 public Collection<BaseMethodBinding> getProviderMethodBindings(Object theProvider) { 856 Set<BaseMethodBinding> retVal = new HashSet<>(); 857 for (ResourceBinding resourceBinding : getResourceBindings()) { 858 for (BaseMethodBinding methodBinding : resourceBinding.getMethodBindings()) { 859 if (theProvider.equals(methodBinding.getProvider())) { 860 retVal.add(methodBinding); 861 } 862 } 863 } 864 865 return retVal; 866 } 867 868 /** 869 * Provides the resource providers for this server 870 */ 871 public List<IResourceProvider> getResourceProviders() { 872 return Collections.unmodifiableList(myResourceProviders); 873 } 874 875 /** 876 * Sets the resource providers for this server 877 */ 878 public void setResourceProviders(IResourceProvider... theResourceProviders) { 879 myResourceProviders.clear(); 880 if (theResourceProviders != null) { 881 myResourceProviders.addAll(Arrays.asList(theResourceProviders)); 882 } 883 } 884 885 /** 886 * Sets the resource providers for this server 887 */ 888 public void setResourceProviders(Collection<IResourceProvider> theProviders) { 889 Validate.noNullElements(theProviders, "theProviders must not contain any null elements"); 890 891 myResourceProviders.clear(); 892 myResourceProviders.addAll(theProviders); 893 } 894 895 /** 896 * Get the server address strategy, which is used to determine what base URL to provide clients to refer to this 897 * server. Defaults to an instance of {@link IncomingRequestAddressStrategy} 898 */ 899 public IServerAddressStrategy getServerAddressStrategy() { 900 return myServerAddressStrategy; 901 } 902 903 /** 904 * Provide a server address strategy, which is used to determine what base URL to provide clients to refer to this 905 * server. Defaults to an instance of {@link IncomingRequestAddressStrategy} 906 */ 907 public void setServerAddressStrategy(IServerAddressStrategy theServerAddressStrategy) { 908 Validate.notNull(theServerAddressStrategy, "Server address strategy can not be null"); 909 myServerAddressStrategy = theServerAddressStrategy; 910 } 911 912 /** 913 * Returns the server base URL (with no trailing '/') for a given request 914 */ 915 public String getServerBaseForRequest(ServletRequestDetails theRequest) { 916 String fhirServerBase; 917 fhirServerBase = 918 myServerAddressStrategy.determineServerBase(getServletContext(), theRequest.getServletRequest()); 919 assert isNotBlank(fhirServerBase) : "Server Address Strategy did not return a value"; 920 921 if (fhirServerBase.endsWith("/")) { 922 fhirServerBase = fhirServerBase.substring(0, fhirServerBase.length() - 1); 923 } 924 925 if (myTenantIdentificationStrategy != null) { 926 fhirServerBase = myTenantIdentificationStrategy.massageServerBaseUrl(fhirServerBase, theRequest); 927 } 928 929 return fhirServerBase; 930 } 931 932 /** 933 * Returns the method bindings for this server which are not specific to any particular resource type. This method is 934 * internal to HAPI and developers generally do not need to interact with it. Use 935 * with caution, as it may change. 936 */ 937 public List<BaseMethodBinding> getServerBindings() { 938 return myServerBinding.getMethodBindings(); 939 } 940 941 /** 942 * Returns the server conformance provider, which is the provider that is used to generate the server's conformance 943 * (metadata) statement if one has been explicitly defined. 944 * <p> 945 * By default, the ServerConformanceProvider for the declared version of FHIR is used, but this can be changed, or 946 * set to <code>null</code> to use the appropriate one for the given FHIR version. 947 * </p> 948 */ 949 public Object getServerConformanceProvider() { 950 return myServerConformanceProvider; 951 } 952 953 /** 954 * Returns the server conformance provider, which is the provider that is used to generate the server's conformance 955 * (metadata) statement. 956 * <p> 957 * By default, the ServerConformanceProvider implementation for the declared version of FHIR is used, but this can be 958 * changed, or set to <code>null</code> if you do not wish to export a conformance 959 * statement. 960 * </p> 961 * This method should only be called before the server is initialized. 962 * Calling it after the server has started is allowed, but you should be 963 * very careful in this case that you only call it while no traffic is 964 * hitting the server. 965 * 966 * @throws IllegalStateException Note that this method can only be called prior to {@link #init() initialization} and will throw an 967 * {@link IllegalStateException} if called after that. 968 */ 969 public void setServerConformanceProvider(@Nonnull Object theServerConformanceProvider) { 970 Validate.notNull(theServerConformanceProvider, "theServerConformanceProvider must not be null"); 971 972 if (myServerConformanceProvider != null) { 973 unregisterProvider(myServerConformanceProvider); 974 } 975 976 // call the setRestfulServer() method to point the Conformance 977 // Provider to this server instance. This is done to avoid 978 // passing the server into the constructor. Having that sort 979 // of cross linkage causes reference cycles in Spring wiring 980 try { 981 Method setRestfulServer = 982 theServerConformanceProvider.getClass().getMethod("setRestfulServer", RestfulServer.class); 983 if (setRestfulServer != null) { 984 setRestfulServer.invoke(theServerConformanceProvider, this); 985 } 986 } catch (Exception e) { 987 ourLog.warn("Error calling IServerConformanceProvider.setRestfulServer", e); 988 } 989 myServerConformanceProvider = theServerConformanceProvider; 990 991 findResourceMethods(myServerConformanceProvider); 992 } 993 994 /** 995 * Gets the server's name, as exported in conformance profiles exported by the server. This is informational only, 996 * but can be helpful to set with something appropriate. 997 * 998 * @see RestfulServer#setServerName(String) 999 */ 1000 public String getServerName() { 1001 return myServerName; 1002 } 1003 1004 /** 1005 * Sets the server's name, as exported in conformance profiles exported by the server. This is informational only, 1006 * but can be helpful to set with something appropriate. 1007 */ 1008 public void setServerName(String theServerName) { 1009 myServerName = theServerName; 1010 } 1011 1012 /** 1013 * Gets the server's version, as exported in conformance profiles exported by the server. This is informational only, 1014 * but can be helpful to set with something appropriate. 1015 */ 1016 public String getServerVersion() { 1017 return myServerVersion; 1018 } 1019 1020 /** 1021 * Gets the server's version, as exported in conformance profiles exported by the server. This is informational only, 1022 * but can be helpful to set with something appropriate. 1023 */ 1024 public void setServerVersion(String theServerVersion) { 1025 myServerVersion = theServerVersion; 1026 } 1027 1028 @SuppressWarnings("WeakerAccess") 1029 protected void handleRequest( 1030 RequestTypeEnum theRequestType, HttpServletRequest theRequest, HttpServletResponse theResponse) 1031 throws ServletException, IOException { 1032 String fhirServerBase; 1033 ServletRequestDetails requestDetails = newRequestDetails(theRequestType, theRequest, theResponse); 1034 1035 String requestId = getOrCreateRequestId(theRequest); 1036 requestDetails.setRequestId(requestId); 1037 addRequestIdToResponse(requestDetails, requestId); 1038 1039 theRequest.setAttribute(SERVLET_CONTEXT_ATTRIBUTE, getServletContext()); 1040 1041 try { 1042 1043 /* *********************************** 1044 * Parse out the request parameters 1045 * ***********************************/ 1046 1047 String requestFullPath = StringUtils.defaultString(theRequest.getRequestURI()); 1048 String servletPath = StringUtils.defaultString(theRequest.getServletPath()); 1049 StringBuffer requestUrl = theRequest.getRequestURL(); 1050 String servletContextPath = IncomingRequestAddressStrategy.determineServletContextPath(theRequest, this); 1051 1052 /* 1053 * Just for debugging.. 1054 */ 1055 if (ourLog.isTraceEnabled()) { 1056 ourLog.trace("Request FullPath: {}", requestFullPath); 1057 ourLog.trace("Servlet Path: {}", servletPath); 1058 ourLog.trace("Request Url: {}", requestUrl); 1059 ourLog.trace("Context Path: {}", servletContextPath); 1060 } 1061 1062 String completeUrl; 1063 Map<String, String[]> params = null; 1064 if (isNotBlank(theRequest.getQueryString())) { 1065 completeUrl = requestUrl + "?" + theRequest.getQueryString(); 1066 /* 1067 * By default, we manually parse the request params (the URL params, or the body for 1068 * POST form queries) since Java containers can't be trusted to use UTF-8 encoding 1069 * when parsing. Specifically Tomcat 7 and Glassfish 4.0 use 8859-1 for some dumb 1070 * reason.... grr..... 1071 */ 1072 if (isIgnoreServerParsedRequestParameters()) { 1073 String contentType = theRequest.getHeader(Constants.HEADER_CONTENT_TYPE); 1074 if (theRequestType == RequestTypeEnum.POST 1075 && isNotBlank(contentType) 1076 && contentType.startsWith(Constants.CT_X_FORM_URLENCODED)) { 1077 String requestBody = toUtf8String(requestDetails.loadRequestContents()); 1078 params = UrlUtil.parseQueryStrings(theRequest.getQueryString(), requestBody); 1079 } else if (theRequestType == RequestTypeEnum.GET) { 1080 params = UrlUtil.parseQueryString(theRequest.getQueryString()); 1081 } 1082 } 1083 } else { 1084 completeUrl = requestUrl.toString(); 1085 } 1086 1087 if (params == null) { 1088 1089 // If the request is coming in with a content-encoding, don't try to 1090 // load the params from the content. 1091 if (isNotBlank(theRequest.getHeader(Constants.HEADER_CONTENT_ENCODING))) { 1092 if (isNotBlank(theRequest.getQueryString())) { 1093 params = UrlUtil.parseQueryString(theRequest.getQueryString()); 1094 } else { 1095 params = Collections.emptyMap(); 1096 } 1097 } 1098 1099 if (params == null) { 1100 params = new HashMap<>(theRequest.getParameterMap()); 1101 } 1102 } 1103 1104 requestDetails.setParameters(params); 1105 1106 /* ************************* 1107 * Notify interceptors about the incoming request 1108 * *************************/ 1109 1110 // Interceptor: SERVER_INCOMING_REQUEST_PRE_PROCESSED 1111 if (myInterceptorService.hasHooks(Pointcut.SERVER_INCOMING_REQUEST_PRE_PROCESSED)) { 1112 HookParams preProcessedParams = new HookParams(); 1113 preProcessedParams.add(HttpServletRequest.class, theRequest); 1114 preProcessedParams.add(HttpServletResponse.class, theResponse); 1115 if (!myInterceptorService.callHooks( 1116 Pointcut.SERVER_INCOMING_REQUEST_PRE_PROCESSED, preProcessedParams)) { 1117 return; 1118 } 1119 } 1120 1121 String requestPath = getRequestPath(requestFullPath, servletContextPath, servletPath); 1122 1123 if (requestPath.length() > 0 && requestPath.charAt(0) == '/') { 1124 requestPath = requestPath.substring(1); 1125 } 1126 1127 IIdType id; 1128 populateRequestDetailsFromRequestPath(requestDetails, requestPath); 1129 1130 fhirServerBase = getServerBaseForRequest(requestDetails); 1131 1132 if (theRequestType == RequestTypeEnum.PUT) { 1133 String contentLocation = theRequest.getHeader(Constants.HEADER_CONTENT_LOCATION); 1134 if (contentLocation != null) { 1135 id = myFhirContext.getVersion().newIdType(); 1136 id.setValue(contentLocation); 1137 requestDetails.setId(id); 1138 } 1139 } 1140 1141 String acceptEncoding = theRequest.getHeader(Constants.HEADER_ACCEPT_ENCODING); 1142 boolean respondGzip = false; 1143 if (acceptEncoding != null) { 1144 String[] parts = acceptEncoding.trim().split("\\s*,\\s*"); 1145 for (String string : parts) { 1146 if (string.equals("gzip")) { 1147 respondGzip = true; 1148 break; 1149 } 1150 } 1151 } 1152 requestDetails.setRespondGzip(respondGzip); 1153 requestDetails.setRequestPath(requestPath); 1154 requestDetails.setFhirServerBase(fhirServerBase); 1155 requestDetails.setCompleteUrl(completeUrl); 1156 1157 // Interceptor: SERVER_INCOMING_REQUEST_PRE_HANDLER_SELECTED 1158 if (myInterceptorService.hasHooks(Pointcut.SERVER_INCOMING_REQUEST_PRE_HANDLER_SELECTED)) { 1159 HookParams preProcessedParams = new HookParams(); 1160 preProcessedParams.add(HttpServletRequest.class, theRequest); 1161 preProcessedParams.add(HttpServletResponse.class, theResponse); 1162 preProcessedParams.add(RequestDetails.class, requestDetails); 1163 preProcessedParams.add(ServletRequestDetails.class, requestDetails); 1164 if (!myInterceptorService.callHooks( 1165 Pointcut.SERVER_INCOMING_REQUEST_PRE_HANDLER_SELECTED, preProcessedParams)) { 1166 return; 1167 } 1168 } 1169 1170 validateRequest(requestDetails); 1171 1172 BaseMethodBinding resourceMethod = determineResourceMethod(requestDetails, requestPath); 1173 1174 RestOperationTypeEnum operation = resourceMethod.getRestOperationType(requestDetails); 1175 requestDetails.setRestOperationType(operation); 1176 1177 // Interceptor: SERVER_INCOMING_REQUEST_POST_PROCESSED 1178 if (myInterceptorService.hasHooks(Pointcut.SERVER_INCOMING_REQUEST_POST_PROCESSED)) { 1179 HookParams postProcessedParams = new HookParams(); 1180 postProcessedParams.add(RequestDetails.class, requestDetails); 1181 postProcessedParams.add(ServletRequestDetails.class, requestDetails); 1182 postProcessedParams.add(HttpServletRequest.class, theRequest); 1183 postProcessedParams.add(HttpServletResponse.class, theResponse); 1184 if (!myInterceptorService.callHooks( 1185 Pointcut.SERVER_INCOMING_REQUEST_POST_PROCESSED, postProcessedParams)) { 1186 return; 1187 } 1188 } 1189 1190 /* 1191 * Actually invoke the server method. This call is to a HAPI method binding, which 1192 * is an object that wraps a specific implementing (user-supplied) method, but 1193 * handles its input and provides its output back to the client. 1194 * 1195 * This is basically the end of processing for a successful request, since the 1196 * method binding replies to the client and closes the response. 1197 */ 1198 resourceMethod.invokeServer(this, requestDetails); 1199 1200 // Invoke interceptors 1201 HookParams hookParams = new HookParams(); 1202 hookParams.add(RequestDetails.class, requestDetails); 1203 hookParams.add(ServletRequestDetails.class, requestDetails); 1204 myInterceptorService.callHooks(Pointcut.SERVER_PROCESSING_COMPLETED_NORMALLY, hookParams); 1205 1206 } catch (NotModifiedException | AuthenticationException e) { 1207 1208 HookParams handleExceptionParams = new HookParams(); 1209 handleExceptionParams.add(RequestDetails.class, requestDetails); 1210 handleExceptionParams.add(ServletRequestDetails.class, requestDetails); 1211 handleExceptionParams.add(HttpServletRequest.class, theRequest); 1212 handleExceptionParams.add(HttpServletResponse.class, theResponse); 1213 handleExceptionParams.add(BaseServerResponseException.class, e); 1214 if (!myInterceptorService.callHooks(Pointcut.SERVER_HANDLE_EXCEPTION, handleExceptionParams)) { 1215 return; 1216 } 1217 1218 writeExceptionToResponse(theResponse, e); 1219 1220 } catch (Throwable e) { 1221 1222 /* 1223 * We have caught an exception during request processing. This might be because a handling method threw 1224 * something they wanted to throw (e.g. UnprocessableEntityException because the request 1225 * had business requirement problems) or it could be due to bugs (e.g. NullPointerException). 1226 * 1227 * First we let the interceptors have a crack at converting the exception into something HAPI can use 1228 * (BaseServerResponseException) 1229 */ 1230 HookParams preProcessParams = new HookParams(); 1231 preProcessParams.add(RequestDetails.class, requestDetails); 1232 preProcessParams.add(ServletRequestDetails.class, requestDetails); 1233 preProcessParams.add(HttpServletRequest.class, theRequest); 1234 preProcessParams.add(HttpServletResponse.class, theResponse); 1235 preProcessParams.add(Throwable.class, e); 1236 BaseServerResponseException exception = 1237 (BaseServerResponseException) myInterceptorService.callHooksAndReturnObject( 1238 Pointcut.SERVER_PRE_PROCESS_OUTGOING_EXCEPTION, preProcessParams); 1239 1240 /* 1241 * If none of the interceptors converted the exception, default behaviour is to keep the exception as-is if it 1242 * extends BaseServerResponseException, otherwise wrap it in an 1243 * InternalErrorException. 1244 */ 1245 if (exception == null) { 1246 exception = DEFAULT_EXCEPTION_HANDLER.preProcessOutgoingException(requestDetails, e, theRequest); 1247 } 1248 1249 /* 1250 * If it's a 410 Gone, we want to include a location header in the response 1251 * if we can, since that can include the resource version which is nice 1252 * for the user. 1253 */ 1254 if (exception instanceof ResourceGoneException) { 1255 IIdType resourceId = ((ResourceGoneException) exception).getResourceId(); 1256 if (resourceId != null && resourceId.hasResourceType() && resourceId.hasIdPart()) { 1257 String baseUrl = 1258 myServerAddressStrategy.determineServerBase(theRequest.getServletContext(), theRequest); 1259 resourceId = resourceId.withServerBase(baseUrl, resourceId.getResourceType()); 1260 requestDetails.getResponse().addHeader(Constants.HEADER_LOCATION, resourceId.getValue()); 1261 } 1262 } 1263 1264 /* 1265 * Next, interceptors get a shot at handling the exception 1266 */ 1267 HookParams handleExceptionParams = new HookParams(); 1268 handleExceptionParams.add(RequestDetails.class, requestDetails); 1269 handleExceptionParams.add(ServletRequestDetails.class, requestDetails); 1270 handleExceptionParams.add(HttpServletRequest.class, theRequest); 1271 handleExceptionParams.add(HttpServletResponse.class, theResponse); 1272 handleExceptionParams.add(BaseServerResponseException.class, exception); 1273 if (!myInterceptorService.callHooks(Pointcut.SERVER_HANDLE_EXCEPTION, handleExceptionParams)) { 1274 return; 1275 } 1276 1277 /* 1278 * If we're handling an exception, no summary mode should be applied 1279 */ 1280 requestDetails.removeParameter(Constants.PARAM_SUMMARY); 1281 requestDetails.removeParameter(Constants.PARAM_ELEMENTS); 1282 requestDetails.removeParameter(Constants.PARAM_ELEMENTS + Constants.PARAM_ELEMENTS_EXCLUDE_MODIFIER); 1283 1284 /* 1285 * If nobody handles it, default behaviour is to stream back the OperationOutcome to the client. 1286 */ 1287 DEFAULT_EXCEPTION_HANDLER.handleException(requestDetails, exception, theRequest, theResponse); 1288 1289 } finally { 1290 1291 HookParams params = new HookParams(); 1292 params.add(RequestDetails.class, requestDetails); 1293 params.addIfMatchesType(ServletRequestDetails.class, requestDetails); 1294 myInterceptorService.callHooks(Pointcut.SERVER_PROCESSING_COMPLETED, params); 1295 } 1296 } 1297 1298 /** 1299 * Subclasses may override this to customize the way that the RequestDetails object is created. Generally speaking, the 1300 * right way to do this is to override this method, but call the super-implementation (<code>super.newRequestDetails</code>) 1301 * and then customize the returned object before returning it. 1302 * 1303 * @param theRequestType The HTTP request verb 1304 * @param theRequest The servlet request 1305 * @param theResponse The servlet response 1306 * @return A ServletRequestDetails instance to be passed to any resource providers, interceptors, etc. that are invoked as a part of serving this request. 1307 */ 1308 @Nonnull 1309 protected ServletRequestDetails newRequestDetails( 1310 RequestTypeEnum theRequestType, HttpServletRequest theRequest, HttpServletResponse theResponse) { 1311 ServletRequestDetails requestDetails = newRequestDetails(); 1312 requestDetails.setServer(this); 1313 requestDetails.setRequestType(theRequestType); 1314 requestDetails.setServletRequest(theRequest); 1315 requestDetails.setServletResponse(theResponse); 1316 return requestDetails; 1317 } 1318 1319 /** 1320 * @deprecated Deprecated in HAPI FHIR 4.1.0 - Users wishing to override this method should override {@link #newRequestDetails(RequestTypeEnum, HttpServletRequest, HttpServletResponse)} instead 1321 */ 1322 @Deprecated 1323 protected ServletRequestDetails newRequestDetails() { 1324 return new ServletRequestDetails(getInterceptorService()); 1325 } 1326 1327 protected void addRequestIdToResponse(ServletRequestDetails theRequestDetails, String theRequestId) { 1328 theRequestDetails.getResponse().addHeader(Constants.HEADER_REQUEST_ID, theRequestId); 1329 } 1330 1331 /** 1332 * Reads a request ID from the request headers via the {@link Constants#HEADER_REQUEST_ID} 1333 * header, or generates one if none is supplied. 1334 * <p> 1335 * Note that the generated request ID is a random 64-bit long integer encoded as 1336 * hexadecimal. It is not generated using any cryptographic algorithms or a secure 1337 * PRNG, so it should not be used for anything other than troubleshooting purposes. 1338 * </p> 1339 */ 1340 protected String getOrCreateRequestId(HttpServletRequest theRequest) { 1341 String requestId = ServletRequestTracing.maybeGetRequestId(theRequest); 1342 1343 // TODO can we delete this and newRequestId() 1344 // and use ServletRequestTracing.getOrGenerateRequestId() instead? 1345 // newRequestId() is protected. Do you think anyone actually overrode it? 1346 if (isBlank(requestId)) { 1347 int requestIdLength = Constants.REQUEST_ID_LENGTH; 1348 requestId = newRequestId(requestIdLength); 1349 } 1350 1351 return requestId; 1352 } 1353 1354 /** 1355 * Generate a new request ID string. Subclasses may ovrride. 1356 */ 1357 protected String newRequestId(int theRequestIdLength) { 1358 String requestId; 1359 requestId = RandomStringUtils.randomAlphanumeric(theRequestIdLength); 1360 return requestId; 1361 } 1362 1363 protected void validateRequest(ServletRequestDetails theRequestDetails) { 1364 String[] elements = theRequestDetails.getParameters().get(Constants.PARAM_ELEMENTS); 1365 if (elements != null) { 1366 for (String next : elements) { 1367 if (next.indexOf(':') != -1) { 1368 throw new InvalidRequestException(Msg.code(295) + "Invalid _elements value: \"" + next + "\""); 1369 } 1370 } 1371 } 1372 1373 elements = theRequestDetails 1374 .getParameters() 1375 .get(Constants.PARAM_ELEMENTS + Constants.PARAM_ELEMENTS_EXCLUDE_MODIFIER); 1376 if (elements != null) { 1377 for (String next : elements) { 1378 if (next.indexOf(':') != -1) { 1379 throw new InvalidRequestException(Msg.code(296) + "Invalid _elements value: \"" + next + "\""); 1380 } 1381 } 1382 } 1383 } 1384 1385 /** 1386 * Initializes the server. Note that this method is final to avoid accidentally introducing bugs in implementations, 1387 * but subclasses may put initialization code in {@link #initialize()}, which is 1388 * called immediately before beginning initialization of the restful server's internal init. 1389 */ 1390 @Override 1391 public final void init() throws ServletException { 1392 myProviderRegistrationMutex.lock(); 1393 try { 1394 initialize(); 1395 1396 Object confProvider; 1397 try { 1398 ourLog.info("Initializing HAPI FHIR restful server running in " 1399 + getFhirContext().getVersion().getVersion().name() + " mode"); 1400 1401 Collection<IResourceProvider> resourceProvider = getResourceProviders(); 1402 // 'true' tells registerProviders() that 1403 // this call is part of initialization 1404 registerProviders(resourceProvider, true); 1405 1406 Collection<Object> providers = getPlainProviders(); 1407 // 'true' tells registerProviders() that 1408 // this call is part of initialization 1409 registerProviders(providers, true); 1410 1411 confProvider = getServerConformanceProvider(); 1412 if (confProvider == null) { 1413 IFhirVersionServer versionServer = 1414 (IFhirVersionServer) getFhirContext().getVersion().getServerVersion(); 1415 confProvider = versionServer.createServerConformanceProvider(this); 1416 } 1417 setServerConformanceProvider(confProvider); 1418 1419 ourLog.trace("Invoking provider initialize methods"); 1420 if (getResourceProviders() != null) { 1421 for (IResourceProvider iResourceProvider : getResourceProviders()) { 1422 invokeInitialize(iResourceProvider); 1423 } 1424 } 1425 1426 invokeInitialize(confProvider); 1427 if (getPlainProviders() != null) { 1428 for (Object next : getPlainProviders()) { 1429 invokeInitialize(next); 1430 } 1431 } 1432 1433 /* 1434 * This is a bit odd, but we have a placeholder @GetPage method for now 1435 * that gets the server to bind for the paging request. At some point 1436 * it would be nice to set things up so that client code could provide 1437 * an alternate implementation, but this isn't currently possible.. 1438 */ 1439 findResourceMethods(new PageProvider()); 1440 1441 } catch (Exception e) { 1442 ourLog.error("An error occurred while loading request handlers!", e); 1443 throw new ServletException( 1444 Msg.code(297) + "Failed to initialize FHIR Restful server: " + e.getMessage(), e); 1445 } 1446 1447 myStarted = true; 1448 ourLog.info("A FHIR has been lit on this server"); 1449 } finally { 1450 myProviderRegistrationMutex.unlock(); 1451 } 1452 } 1453 1454 /** 1455 * This method may be overridden by subclasses to do perform initialization that needs to be performed prior to the 1456 * server being used. 1457 * 1458 * @throws ServletException If the initialization failed. Note that you should consider throwing {@link UnavailableException} 1459 * (which extends {@link ServletException}), as this is a flag to the servlet container 1460 * that the servlet is not usable. 1461 */ 1462 protected void initialize() throws ServletException { 1463 // nothing by default 1464 } 1465 1466 private void invokeDestroy(Object theProvider) { 1467 invokeDestroy(theProvider, theProvider.getClass()); 1468 } 1469 1470 private void invokeDestroy(Object theProvider, Class<?> clazz) { 1471 for (Method m : ReflectionUtil.getDeclaredMethods(clazz)) { 1472 Destroy destroy = m.getAnnotation(Destroy.class); 1473 if (destroy != null) { 1474 invokeInitializeOrDestroyMethod(theProvider, m, "destroy"); 1475 } 1476 } 1477 1478 Class<?> supertype = clazz.getSuperclass(); 1479 if (!Object.class.equals(supertype)) { 1480 invokeDestroy(theProvider, supertype); 1481 } 1482 } 1483 1484 private void invokeInitialize(Object theProvider) { 1485 invokeInitialize(theProvider, theProvider.getClass()); 1486 } 1487 1488 private void invokeInitialize(Object theProvider, Class<?> clazz) { 1489 for (Method m : ReflectionUtil.getDeclaredMethods(clazz)) { 1490 Initialize initialize = m.getAnnotation(Initialize.class); 1491 if (initialize != null) { 1492 invokeInitializeOrDestroyMethod(theProvider, m, "initialize"); 1493 } 1494 } 1495 1496 Class<?> supertype = clazz.getSuperclass(); 1497 if (!Object.class.equals(supertype)) { 1498 invokeInitialize(theProvider, supertype); 1499 } 1500 } 1501 1502 private void invokeInitializeOrDestroyMethod(Object theProvider, Method m, String theMethodDescription) { 1503 1504 Class<?>[] paramTypes = m.getParameterTypes(); 1505 Object[] params = new Object[paramTypes.length]; 1506 1507 int index = 0; 1508 for (Class<?> nextParamType : paramTypes) { 1509 1510 if (RestfulServer.class.equals(nextParamType) || IRestfulServerDefaults.class.equals(nextParamType)) { 1511 params[index] = this; 1512 } 1513 1514 index++; 1515 } 1516 1517 try { 1518 m.invoke(theProvider, params); 1519 } catch (Exception e) { 1520 ourLog.error("Exception occurred in " + theMethodDescription + " method '" + m.getName() + "'", e); 1521 } 1522 } 1523 1524 /** 1525 * Should the server "pretty print" responses by default (requesting clients can always override this default by 1526 * supplying an <code>Accept</code> header in the request, or a <code>_pretty</code> 1527 * parameter in the request URL. 1528 * <p> 1529 * The default is <code>false</code> 1530 * </p> 1531 * <p> 1532 * Note that this setting is ignored by {@link ca.uhn.fhir.rest.server.interceptor.ResponseHighlighterInterceptor} 1533 * when streaming HTML, although even when that interceptor it used this setting will 1534 * still be honoured when streaming raw FHIR. 1535 * </p> 1536 * 1537 * @return Returns the default pretty print setting 1538 */ 1539 @Override 1540 public boolean isDefaultPrettyPrint() { 1541 return myDefaultPrettyPrint; 1542 } 1543 1544 /** 1545 * Should the server "pretty print" responses by default (requesting clients can always override this default by 1546 * supplying an <code>Accept</code> header in the request, or a <code>_pretty</code> 1547 * parameter in the request URL. 1548 * <p> 1549 * The default is <code>false</code> 1550 * </p> 1551 * <p> 1552 * Note that this setting is ignored by {@link ca.uhn.fhir.rest.server.interceptor.ResponseHighlighterInterceptor} 1553 * when streaming HTML, although even when that interceptor it used this setting will 1554 * still be honoured when streaming raw FHIR. 1555 * </p> 1556 * 1557 * @param theDefaultPrettyPrint The default pretty print setting 1558 */ 1559 public void setDefaultPrettyPrint(boolean theDefaultPrettyPrint) { 1560 myDefaultPrettyPrint = theDefaultPrettyPrint; 1561 } 1562 1563 /** 1564 * If set to <code>true</code> (the default is <code>true</code>) this server will not 1565 * use the parsed request parameters (URL parameters and HTTP POST form contents) but 1566 * will instead parse these values manually from the request URL and request body. 1567 * <p> 1568 * This is useful because many servlet containers (e.g. Tomcat, Glassfish) will use 1569 * ISO-8859-1 encoding to parse escaped URL characters instead of using UTF-8 1570 * as is specified by FHIR. 1571 * </p> 1572 */ 1573 public boolean isIgnoreServerParsedRequestParameters() { 1574 return myIgnoreServerParsedRequestParameters; 1575 } 1576 1577 /** 1578 * If set to <code>true</code> (the default is <code>true</code>) this server will not 1579 * use the parsed request parameters (URL parameters and HTTP POST form contents) but 1580 * will instead parse these values manually from the request URL and request body. 1581 * <p> 1582 * This is useful because many servlet containers (e.g. Tomcat, Glassfish) will use 1583 * ISO-8859-1 encoding to parse escaped URL characters instead of using UTF-8 1584 * as is specified by FHIR. 1585 * </p> 1586 */ 1587 public void setIgnoreServerParsedRequestParameters(boolean theIgnoreServerParsedRequestParameters) { 1588 myIgnoreServerParsedRequestParameters = theIgnoreServerParsedRequestParameters; 1589 } 1590 1591 /** 1592 * Should the server attempt to decompress incoming request contents (default is <code>true</code>). Typically this 1593 * should be set to <code>true</code> unless the server has other configuration to 1594 * deal with decompressing request bodies (e.g. a filter applied to the whole server). 1595 */ 1596 public boolean isUncompressIncomingContents() { 1597 return myUncompressIncomingContents; 1598 } 1599 1600 /** 1601 * Should the server attempt to decompress incoming request contents (default is <code>true</code>). Typically this 1602 * should be set to <code>true</code> unless the server has other configuration to 1603 * deal with decompressing request bodies (e.g. a filter applied to the whole server). 1604 */ 1605 public void setUncompressIncomingContents(boolean theUncompressIncomingContents) { 1606 myUncompressIncomingContents = theUncompressIncomingContents; 1607 } 1608 1609 private String resolveRequestPath(RequestDetails theRequestDetails, String theRequestPath) { 1610 if (myTenantIdentificationStrategy != null) { 1611 theRequestPath = myTenantIdentificationStrategy.resolveRelativeUrl(theRequestPath, theRequestDetails); 1612 } 1613 return theRequestPath; 1614 } 1615 1616 public void populateRequestDetailsFromRequestPath(RequestDetails theRequestDetails, String theRequestPath) { 1617 String resolvedRequestPath = resolveRequestPath(theRequestDetails, theRequestPath); 1618 UrlPathTokenizer tok = new UrlPathTokenizer(resolvedRequestPath); 1619 1620 if (myTenantIdentificationStrategy != null) { 1621 myTenantIdentificationStrategy.extractTenant(tok, theRequestDetails); 1622 } 1623 1624 IIdType id = null; 1625 String operation = null; 1626 String compartment = null; 1627 String resourceName = null; 1628 if (tok.hasMoreTokens()) { 1629 resourceName = tok.nextTokenUnescapedAndSanitized(); 1630 if (partIsOperation(resourceName)) { 1631 operation = resourceName; 1632 resourceName = null; 1633 } 1634 } 1635 theRequestDetails.setResourceName(resourceName); 1636 1637 if (tok.hasMoreTokens()) { 1638 String nextString = tok.nextTokenUnescapedAndSanitized(); 1639 if (partIsOperation(nextString)) { 1640 operation = nextString; 1641 } else { 1642 id = myFhirContext.getVersion().newIdType(); 1643 id.setParts(null, resourceName, UrlUtil.unescape(nextString), null); 1644 } 1645 } 1646 1647 if (tok.hasMoreTokens()) { 1648 String nextString = tok.nextTokenUnescapedAndSanitized(); 1649 if (nextString.equals(Constants.PARAM_HISTORY)) { 1650 if (tok.hasMoreTokens()) { 1651 String versionString = tok.nextTokenUnescapedAndSanitized(); 1652 if (id == null) { 1653 throw new InvalidRequestException( 1654 Msg.code(298) + "Don't know how to handle request path: " + resolvedRequestPath); 1655 } 1656 id.setParts(null, resourceName, id.getIdPart(), UrlUtil.unescape(versionString)); 1657 } else { 1658 operation = Constants.PARAM_HISTORY; 1659 } 1660 } else if (partIsOperation(nextString)) { 1661 if (operation != null) { 1662 throw new InvalidRequestException( 1663 Msg.code(299) + "URL Path contains two operations: " + resolvedRequestPath); 1664 } 1665 operation = nextString; 1666 } else { 1667 compartment = nextString; 1668 } 1669 } 1670 1671 // Secondary is for things like ..../_tags/_delete 1672 String secondaryOperation = null; 1673 1674 while (tok.hasMoreTokens()) { 1675 String nextString = tok.nextTokenUnescapedAndSanitized(); 1676 if (operation == null) { 1677 operation = nextString; 1678 } else if (secondaryOperation == null) { 1679 secondaryOperation = nextString; 1680 } else { 1681 throw new InvalidRequestException(Msg.code(300) + "URL path has unexpected token '" + nextString 1682 + "' at the end: " + resolvedRequestPath); 1683 } 1684 } 1685 1686 theRequestDetails.setId(id); 1687 theRequestDetails.setOperation(operation); 1688 theRequestDetails.setSecondaryOperation(secondaryOperation); 1689 theRequestDetails.setCompartmentName(compartment); 1690 } 1691 1692 /** 1693 * Registers an interceptor. This method is a convenience method which calls 1694 * <code>getInterceptorService().registerInterceptor(theInterceptor);</code> 1695 * 1696 * @param theInterceptor The interceptor, must not be null 1697 */ 1698 public void registerInterceptor(Object theInterceptor) { 1699 Validate.notNull(theInterceptor, "Interceptor can not be null"); 1700 getInterceptorService().registerInterceptor(theInterceptor); 1701 } 1702 1703 /** 1704 * Register a single provider. This could be a Resource Provider or a "plain" provider not associated with any 1705 * resource. 1706 */ 1707 public void registerProvider(Object provider) { 1708 if (provider != null) { 1709 Collection<Object> providerList = new ArrayList<>(1); 1710 providerList.add(provider); 1711 registerProviders(providerList); 1712 } 1713 } 1714 1715 /** 1716 * Register a group of providers. These could be Resource Providers (classes implementing {@link IResourceProvider}) or "plain" providers, or a mixture of the two. 1717 * 1718 * @param theProviders a {@code Collection} of theProviders. The parameter could be null or an empty {@code Collection} 1719 */ 1720 public void registerProviders(Object... theProviders) { 1721 Validate.noNullElements(theProviders); 1722 registerProviders(Arrays.asList(theProviders)); 1723 } 1724 1725 /** 1726 * Register a group of theProviders. These could be Resource Providers, "plain" theProviders or a mixture of the two. 1727 * 1728 * @param theProviders a {@code Collection} of theProviders. The parameter could be null or an empty {@code Collection} 1729 */ 1730 public void registerProviders(Collection<?> theProviders) { 1731 Validate.noNullElements(theProviders, "theProviders must not contain any null elements"); 1732 1733 myProviderRegistrationMutex.lock(); 1734 try { 1735 if (!myStarted) { 1736 for (Object provider : theProviders) { 1737 ourLog.debug("Registration of provider [" 1738 + provider.getClass().getName() + "] will be delayed until FHIR server startup"); 1739 if (provider instanceof IResourceProvider) { 1740 myResourceProviders.add((IResourceProvider) provider); 1741 } else { 1742 myPlainProviders.add(provider); 1743 } 1744 } 1745 return; 1746 } 1747 } finally { 1748 myProviderRegistrationMutex.unlock(); 1749 } 1750 registerProviders(theProviders, false); 1751 } 1752 1753 /* 1754 * Inner method to actually register theProviders 1755 */ 1756 protected void registerProviders(@Nullable Collection<?> theProviders, boolean inInit) { 1757 Validate.noNullElements(theProviders, "theProviders must not contain any null elements"); 1758 1759 List<IResourceProvider> newResourceProviders = new ArrayList<>(); 1760 List<Object> newPlainProviders = new ArrayList<>(); 1761 1762 if (theProviders != null) { 1763 for (Object provider : theProviders) { 1764 if (provider instanceof IResourceProvider) { 1765 IResourceProvider rsrcProvider = (IResourceProvider) provider; 1766 Class<? extends IBaseResource> resourceType = rsrcProvider.getResourceType(); 1767 if (resourceType == null) { 1768 throw new NullPointerException(Msg.code(301) + "getResourceType() on class '" 1769 + rsrcProvider.getClass().getCanonicalName() + "' returned null"); 1770 } 1771 if (!inInit) { 1772 myResourceProviders.add(rsrcProvider); 1773 } 1774 newResourceProviders.add(rsrcProvider); 1775 } else { 1776 if (!inInit) { 1777 myPlainProviders.add(provider); 1778 } 1779 newPlainProviders.add(provider); 1780 } 1781 } 1782 if (!newResourceProviders.isEmpty()) { 1783 ourLog.info( 1784 "Added {} resource provider(s). Total {}", 1785 newResourceProviders.size(), 1786 myResourceProviders.size()); 1787 for (IResourceProvider provider : newResourceProviders) { 1788 findResourceMethods(provider); 1789 } 1790 } 1791 if (!newPlainProviders.isEmpty()) { 1792 ourLog.info("Added {} plain provider(s). Total {}", newPlainProviders.size(), myPlainProviders.size()); 1793 for (Object provider : newPlainProviders) { 1794 findResourceMethods(provider); 1795 } 1796 } 1797 if (!inInit) { 1798 ourLog.trace("Invoking provider initialize methods"); 1799 if (!newResourceProviders.isEmpty()) { 1800 for (IResourceProvider provider : newResourceProviders) { 1801 invokeInitialize(provider); 1802 } 1803 } 1804 if (!newPlainProviders.isEmpty()) { 1805 for (Object provider : newPlainProviders) { 1806 invokeInitialize(provider); 1807 } 1808 } 1809 } 1810 } 1811 } 1812 1813 /* 1814 * Remove registered RESTful methods for a Provider (and all superclasses) when it is being unregistered 1815 */ 1816 private void removeResourceMethods(Object theProvider) { 1817 ourLog.info("Removing RESTful methods for: {}", theProvider.getClass()); 1818 Class<?> clazz = theProvider.getClass(); 1819 Class<?> supertype = clazz.getSuperclass(); 1820 Collection<String> resourceNames = new ArrayList<>(); 1821 while (!Object.class.equals(supertype)) { 1822 removeResourceMethods(theProvider, supertype, resourceNames); 1823 removeResourceMethodsOnInterfaces(theProvider, supertype.getInterfaces(), resourceNames); 1824 supertype = supertype.getSuperclass(); 1825 } 1826 removeResourceMethods(theProvider, clazz, resourceNames); 1827 removeResourceMethodsOnInterfaces(theProvider, clazz.getInterfaces(), resourceNames); 1828 removeResourceNameBindings(resourceNames, theProvider); 1829 } 1830 1831 private void removeResourceNameBindings(Collection<String> resourceNames, Object theProvider) { 1832 for (String resourceName : resourceNames) { 1833 ResourceBinding resourceBinding = myResourceNameToBinding.get(resourceName); 1834 if (resourceBinding == null) { 1835 continue; 1836 } 1837 1838 for (Iterator<BaseMethodBinding> it = 1839 resourceBinding.getMethodBindings().iterator(); 1840 it.hasNext(); ) { 1841 BaseMethodBinding binding = it.next(); 1842 if (theProvider.equals(binding.getProvider())) { 1843 it.remove(); 1844 ourLog.info("{} binding of {} was removed", resourceName, binding); 1845 } 1846 } 1847 1848 if (resourceBinding.getMethodBindings().isEmpty()) { 1849 myResourceNameToBinding.remove(resourceName); 1850 } 1851 } 1852 } 1853 1854 private void removeResourceMethodsOnInterfaces( 1855 Object theProvider, Class<?>[] interfaces, Collection<String> resourceNames) { 1856 for (Class<?> anInterface : interfaces) { 1857 removeResourceMethods(theProvider, anInterface, resourceNames); 1858 removeResourceMethodsOnInterfaces(theProvider, anInterface.getInterfaces(), resourceNames); 1859 } 1860 } 1861 1862 /* 1863 * Collect the set of RESTful methods for a single class when it is being unregistered 1864 */ 1865 private void removeResourceMethods(Object theProvider, Class<?> clazz, Collection<String> resourceNames) 1866 throws ConfigurationException { 1867 for (Method m : ReflectionUtil.getDeclaredMethods(clazz)) { 1868 BaseMethodBinding foundMethodBinding = BaseMethodBinding.bindMethod(m, getFhirContext(), theProvider); 1869 if (foundMethodBinding == null) { 1870 continue; // not a bound method 1871 } 1872 if (foundMethodBinding instanceof ConformanceMethodBinding) { 1873 myServerConformanceMethod = null; 1874 continue; 1875 } 1876 String resourceName = foundMethodBinding.getResourceName(); 1877 if (!resourceNames.contains(resourceName)) { 1878 resourceNames.add(resourceName); 1879 } 1880 } 1881 } 1882 1883 public Object returnResponse( 1884 ServletRequestDetails theRequest, 1885 BaseParseAction<?> outcome, 1886 int operationStatus, 1887 boolean allowPrefer, 1888 MethodOutcome response, 1889 String resourceName) 1890 throws IOException { 1891 HttpServletResponse servletResponse = theRequest.getServletResponse(); 1892 servletResponse.setStatus(operationStatus); 1893 servletResponse.setCharacterEncoding(Constants.CHARSET_NAME_UTF8); 1894 addHeadersToResponse(servletResponse); 1895 if (allowPrefer) { 1896 addContentLocationHeaders(theRequest, servletResponse, response, resourceName); 1897 } 1898 Writer writer; 1899 if (outcome != null) { 1900 ResponseEncoding encoding = RestfulServerUtils.determineResponseEncodingWithDefault(theRequest); 1901 servletResponse.setContentType(encoding.getResourceContentType()); 1902 writer = servletResponse.getWriter(); 1903 IParser parser = encoding.getEncoding().newParser(getFhirContext()); 1904 parser.setPrettyPrint(RestfulServerUtils.prettyPrintResponse(this, theRequest)); 1905 outcome.execute(parser, writer); 1906 } else { 1907 servletResponse.setContentType(Constants.CT_TEXT_WITH_UTF8); 1908 writer = servletResponse.getWriter(); 1909 } 1910 return writer; 1911 } 1912 1913 @Override 1914 protected void service(HttpServletRequest theReq, HttpServletResponse theResp) 1915 throws ServletException, IOException { 1916 theReq.setAttribute(REQUEST_START_TIME, new Date()); 1917 1918 RequestTypeEnum method; 1919 try { 1920 method = RequestTypeEnum.valueOf(theReq.getMethod()); 1921 } catch (IllegalArgumentException e) { 1922 super.service(theReq, theResp); 1923 return; 1924 } 1925 1926 switch (method) { 1927 case DELETE: 1928 doDelete(theReq, theResp); 1929 break; 1930 case GET: 1931 doGet(theReq, theResp); 1932 break; 1933 case OPTIONS: 1934 doOptions(theReq, theResp); 1935 break; 1936 case POST: 1937 doPost(theReq, theResp); 1938 break; 1939 case PUT: 1940 doPut(theReq, theResp); 1941 break; 1942 case PATCH: 1943 case TRACE: 1944 case TRACK: 1945 case HEAD: 1946 case CONNECT: 1947 default: 1948 handleRequest(method, theReq, theResp); 1949 break; 1950 } 1951 } 1952 1953 /** 1954 * Sets the non-resource specific providers which implement method calls on this server 1955 * 1956 * @see #setResourceProviders(Collection) 1957 */ 1958 public void setProviders(Object... theProviders) { 1959 Validate.noNullElements(theProviders, "theProviders must not contain any null elements"); 1960 1961 myPlainProviders.clear(); 1962 if (theProviders != null) { 1963 myPlainProviders.addAll(Arrays.asList(theProviders)); 1964 } 1965 } 1966 1967 /** 1968 * If provided (default is <code>null</code>), the tenant identification 1969 * strategy provides a mechanism for a multitenant server to identify which tenant 1970 * a given request corresponds to. 1971 */ 1972 public void setTenantIdentificationStrategy(ITenantIdentificationStrategy theTenantIdentificationStrategy) { 1973 myTenantIdentificationStrategy = theTenantIdentificationStrategy; 1974 } 1975 1976 protected void throwUnknownFhirOperationException( 1977 RequestDetails requestDetails, String requestPath, RequestTypeEnum theRequestType) { 1978 FhirContext fhirContext = myFhirContext; 1979 throwUnknownFhirOperationException(requestDetails, requestPath, theRequestType, fhirContext); 1980 } 1981 1982 protected void throwUnknownResourceTypeException(String theResourceName) { 1983 /* perform a 'distinct' in case there are multiple concrete IResourceProviders declared for the same FHIR-Resource. (A concrete IResourceProvider for Patient@Read and a separate concrete for Patient@Search for example */ 1984 /* perform a 'sort' to provide an easier to read alphabetized list (vs how the different FHIR-resource IResourceProviders happened to be registered */ 1985 List<String> knownDistinctAndSortedResourceTypes = myResourceProviders.stream() 1986 .map(t -> t.getResourceType().getSimpleName()) 1987 .distinct() 1988 .sorted() 1989 .collect(toList()); 1990 throw new ResourceNotFoundException(Msg.code(302) + "Unknown resource type '" + theResourceName 1991 + "' - Server knows how to handle: " + knownDistinctAndSortedResourceTypes); 1992 } 1993 1994 /** 1995 * Unregisters an interceptor. This method is a convenience method which calls 1996 * <code>getInterceptorService().unregisterInterceptor(theInterceptor);</code> 1997 * 1998 * @param theInterceptor The interceptor, must not be null 1999 */ 2000 public void unregisterInterceptor(Object theInterceptor) { 2001 Validate.notNull(theInterceptor, "Interceptor can not be null"); 2002 getInterceptorService().unregisterInterceptor(theInterceptor); 2003 } 2004 2005 /** 2006 * Unregister one provider (either a Resource provider or a plain provider) 2007 */ 2008 public void unregisterProvider(Object provider) { 2009 if (provider != null) { 2010 Collection<Object> providerList = new ArrayList<>(1); 2011 providerList.add(provider); 2012 unregisterProviders(providerList); 2013 } 2014 } 2015 2016 /** 2017 * Unregister a {@code Collection} of providers 2018 */ 2019 public void unregisterProviders(Collection<?> providers) { 2020 if (providers != null) { 2021 for (Object provider : providers) { 2022 removeResourceMethods(provider); 2023 if (provider instanceof IResourceProvider) { 2024 myResourceProviders.remove(provider); 2025 } else { 2026 myPlainProviders.remove(provider); 2027 } 2028 invokeDestroy(provider); 2029 } 2030 } 2031 } 2032 2033 /** 2034 * Unregisters all plain and resource providers (but not the conformance provider). 2035 */ 2036 public void unregisterAllProviders() { 2037 unregisterAllProviders(myPlainProviders); 2038 unregisterAllProviders(myResourceProviders); 2039 } 2040 2041 private void unregisterAllProviders(List<?> theProviders) { 2042 while (theProviders.size() > 0) { 2043 unregisterProvider(theProviders.get(0)); 2044 } 2045 } 2046 2047 private void writeExceptionToResponse(HttpServletResponse theResponse, BaseServerResponseException theException) 2048 throws IOException { 2049 theResponse.setStatus(theException.getStatusCode()); 2050 addHeadersToResponse(theResponse); 2051 if (theException.hasResponseHeaders()) { 2052 for (Entry<String, List<String>> nextEntry : 2053 theException.getResponseHeaders().entrySet()) { 2054 for (String nextValue : nextEntry.getValue()) { 2055 if (isNotBlank(nextValue)) { 2056 theResponse.addHeader(nextEntry.getKey(), nextValue); 2057 } 2058 } 2059 } 2060 } 2061 theResponse.setContentType("text/plain"); 2062 theResponse.setCharacterEncoding("UTF-8"); 2063 String message = UrlUtil.sanitizeUrlPart(theException.getMessage()); 2064 theResponse.getWriter().write(message); 2065 } 2066 2067 /** 2068 * By default, server create/update/patch/transaction methods return a copy of the resource 2069 * as it was stored. This may be overridden by the client using the 2070 * <code>Prefer</code> header. 2071 * <p> 2072 * This setting changes the default behaviour if no Prefer header is supplied by the client. 2073 * The default is {@link PreferReturnEnum#REPRESENTATION} 2074 * </p> 2075 * 2076 * @see <a href="http://hl7.org/fhir/http.html#ops">HL7 FHIR Specification</a> section on the Prefer header 2077 */ 2078 @Override 2079 public PreferReturnEnum getDefaultPreferReturn() { 2080 return myDefaultPreferReturn; 2081 } 2082 2083 /** 2084 * By default, server create/update/patch/transaction methods return a copy of the resource 2085 * as it was stored. This may be overridden by the client using the 2086 * <code>Prefer</code> header. 2087 * <p> 2088 * This setting changes the default behaviour if no Prefer header is supplied by the client. 2089 * The default is {@link PreferReturnEnum#REPRESENTATION} 2090 * </p> 2091 * 2092 * @see <a href="http://hl7.org/fhir/http.html#ops">HL7 FHIR Specification</a> section on the Prefer header 2093 */ 2094 public void setDefaultPreferReturn(PreferReturnEnum theDefaultPreferReturn) { 2095 Validate.notNull(theDefaultPreferReturn, "theDefaultPreferReturn must not be null"); 2096 myDefaultPreferReturn = theDefaultPreferReturn; 2097 } 2098 2099 /** 2100 * Create a CapabilityStatement based on the given request 2101 */ 2102 public IBaseConformance getCapabilityStatement(ServletRequestDetails theRequestDetails) { 2103 // Create a cloned request details so we can make it indicate that this is a capabilities request 2104 ServletRequestDetails requestDetails = new ServletRequestDetails(theRequestDetails); 2105 requestDetails.setRestOperationType(RestOperationTypeEnum.METADATA); 2106 2107 return myServerConformanceMethod.provideCapabilityStatement(this, requestDetails); 2108 } 2109 2110 /** 2111 * Count length of URL string, but treating unescaped sequences (e.g. ' ') as their unescaped equivalent (%20) 2112 */ 2113 protected static int escapedLength(String theServletPath) { 2114 int delta = 0; 2115 for (int i = 0; i < theServletPath.length(); i++) { 2116 char next = theServletPath.charAt(i); 2117 if (next == ' ') { 2118 delta = delta + 2; 2119 } 2120 } 2121 return theServletPath.length() + delta; 2122 } 2123 2124 public static void throwUnknownFhirOperationException( 2125 RequestDetails requestDetails, 2126 String requestPath, 2127 RequestTypeEnum theRequestType, 2128 FhirContext theFhirContext) { 2129 String message = theFhirContext 2130 .getLocalizer() 2131 .getMessage( 2132 RestfulServer.class, 2133 "unknownMethod", 2134 theRequestType.name(), 2135 requestPath, 2136 requestDetails.getParameters().keySet()); 2137 2138 IBaseOperationOutcome oo = OperationOutcomeUtil.newInstance(theFhirContext); 2139 OperationOutcomeUtil.addIssue(theFhirContext, oo, "error", message, null, "not-supported"); 2140 2141 throw new InvalidRequestException(Msg.code(303) + message, oo); 2142 } 2143 2144 private static boolean partIsOperation(String nextString) { 2145 return nextString.length() > 0 2146 && (nextString.charAt(0) == '_' 2147 || nextString.charAt(0) == '$' 2148 || nextString.equals(Constants.URL_TOKEN_METADATA)); 2149 } 2150 2151 // /** 2152 // * Returns the read method binding for the given resource type, or 2153 // * returns <code>null</code> if not 2154 // * @param theResourceType The resource type, e.g. "Patient" 2155 // * @return The read method binding, or null 2156 // */ 2157 // public ReadMethodBinding findReadMethodBinding(String theResourceType) { 2158 // ReadMethodBinding retVal = null; 2159 // 2160 // ResourceBinding type = myResourceNameToBinding.get(theResourceType); 2161 // if (type != null) { 2162 // for (BaseMethodBinding<?> next : type.getMethodBindings()) { 2163 // if (next instanceof ReadMethodBinding) { 2164 // retVal = (ReadMethodBinding) next; 2165 // } 2166 // } 2167 // } 2168 // 2169 // return retVal; 2170 // } 2171}