From 6d58df0f44d093e7a8b42903f7fbcb07c5c83673 Mon Sep 17 00:00:00 2001 From: James Agnew Date: Sun, 3 Dec 2023 11:15:37 -0500 Subject: [PATCH] Jakarta/Javax Servlet Migration (#5429) * Servlet migrsation changes * Apply spotless * Work on migration * Start working on JPA migration * Test fixes * Test fixes * Test fixes * Work * Work on servlet migration * Work on migration * Work on fixes * Imports fix * Work on tests * Test fix * All tests passing * Work on migration * Schema generator * Refactor ID strategy * Some test fixes * Test fixes * API additions * Work on websockets * Test fixe * Version bump * Work on migration * All tests have passed! * Work on test fixes * Fixes * Work on fixes * CDR fix * Work on migration * Fixes * Spotless * Disable onetoone ban * Adjust migratyions * Transaction service fix * Add tinyint to migrator * Work * Migration * Compile fix * Add license * Test fix * Test fix * Cleanup * Cleanup attempt * Test fix * Reslve fixmes * Remove legacy lastn implementation * Test cleanup * Cleanup * Remove dead import * Bad import setups * Review comments * Review fixes * Build fix * Test fix * Spotless * Account for CR changes * Compile fixes * Rollback one change * Test tweak * License header * Test fix * Test fix part 2: * Clean up tx isolation * Spotless * Spotless apply * Drop min SQL Server level * Attempted test fix * Test fix * Test fix * Test fix * Bump hibernate * Test fix * Test fixes * Test fixes * Test fixes * Test cleanup * One more test fix * Test fix * Try to fix test * Clean up expunge * Test fix * Remove unneeded task * Spotless * Bump compiler plugin * Spotless * Compile fix * Add license headers * License header * Test fixes * Bump animal sniffer * Spotless * Bump Jetty version * Test fix and version bump * Cleanup --------- Co-authored-by: Tadgh --- .mvn/wrapper/MavenWrapperDownloader.java | 13 +- hapi-deployable-pom/pom.xml | 11 +- hapi-fhir-android/pom.xml | 8 +- hapi-fhir-base/pom.xml | 17 +- .../context/support/LookupCodeRequest.java | 19 + .../ca/uhn/fhir/interceptor/api/Pointcut.java | 54 +- .../ca/uhn/fhir/model/api/BaseElement.java | 6 +- .../ca/uhn/fhir/model/api/IFhirVersion.java | 9 +- .../narrative2/NarrativeTemplateManifest.java | 11 +- .../uhn/fhir/rest/annotation/Operation.java | 4 +- .../ca/uhn/fhir/rest/annotation/Read.java | 5 +- .../uhn/fhir/rest/annotation/Transaction.java | 5 +- .../rest/annotation/TransactionParam.java | 5 +- .../ca/uhn/fhir/rest/annotation/Validate.java | 5 +- .../fhir/rest/gclient/TokenClientParam.java | 4 +- .../uhn/fhir/rest/param/ParamPrefixEnum.java | 4 +- .../java/ca/uhn/fhir/util/AttachmentUtil.java | 6 +- .../java/ca/uhn/fhir/util/rdf/RDFUtil.java | 3 +- .../schematron/SchematronBaseValidator.java | 9 +- .../ca/uhn/fhir/i18n/HapiLocalizerTest.java | 10 +- .../api/ResourceMetadataKeyEnumTest.java | 3 +- .../java/ca/uhn/fhir/model/api/TagTest.java | 5 +- .../rest/api/CacheControlDirectiveTest.java | 4 +- .../uhn/fhir/rest/api/EncodingEnumTest.java | 2 +- .../uhn/fhir/rest/api/MethodOutcomeTest.java | 3 +- .../ca/uhn/fhir/rest/param/DateParamTest.java | 4 +- .../fhir/rest/param/QualifierDetailsTest.java | 3 +- .../uhn/fhir/rest/param/StringParamTest.java | 12 +- .../BaseServerResponseExceptionTest.java | 2 +- .../ca/uhn/fhir/util/DateRangeUtilTest.java | 5 +- .../java/ca/uhn/fhir/util/LogUtilTest.java | 6 +- .../ca/uhn/fhir/util/ReflectionUtilTest.java | 12 +- .../validation/ResultSeverityEnumTest.java | 4 +- hapi-fhir-bom/pom.xml | 4 +- hapi-fhir-checkstyle/pom.xml | 4 +- .../src/checkstyle/hapi-base-checkstyle.xml | 7 + hapi-fhir-cli/hapi-fhir-cli-api/pom.xml | 74 +- .../ca/uhn/fhir/cli/BulkImportCommand.java | 12 +- .../fhir/cli/ReindexTerminologyCommand.java | 3 +- .../fhir/cli/WebsocketSubscribeCommand.java | 47 +- ...mandIT.java => BulkImportCommandTest.java} | 19 +- .../HapiClearMigrationLockCommandTest.java | 9 +- .../HapiFlywayMigrateDatabaseCommandTest.java | 3 +- .../fhir/cli/HeaderPassthroughOptionTest.java | 39 +- hapi-fhir-cli/hapi-fhir-cli-app/pom.xml | 2 +- hapi-fhir-cli/pom.xml | 2 +- hapi-fhir-client-okhttp/pom.xml | 7 +- .../okhttp/GenericOkHttpClientDstu2Test.java | 869 ++++++++--------- hapi-fhir-client/pom.xml | 2 +- .../rest/client/apache/ApacheHttpClient.java | 16 +- .../client/apache/ApacheHttpResponse.java | 16 +- .../rest/client/apache/BaseHttpClient.java | 4 +- .../client/apache/GZipContentInterceptor.java | 4 +- .../interceptor/BasicAuthInterceptor.java | 4 +- .../client/interceptor/CookieInterceptor.java | 4 +- .../rest/client/method/BaseMethodBinding.java | 40 +- .../BaseOutcomeReturningMethodBinding.java | 4 +- ...indingWithResourceIdButNoResourceBody.java | 7 +- .../client/method/ConditionalParamBinder.java | 4 +- .../client/method/DeleteMethodBinding.java | 5 +- .../client/method/HistoryMethodBinding.java | 4 +- .../rest/client/method/NullParameter.java | 4 +- .../client/method/OperationMethodBinding.java | 8 +- .../client/method/PatchMethodBinding.java | 11 +- .../rest/client/method/RawParamsParmeter.java | 4 +- .../rest/client/method/ReadMethodBinding.java | 13 +- .../rest/client/method/SearchParameter.java | 61 +- .../client/method/TransactionParameter.java | 8 +- hapi-fhir-converter/pom.xml | 38 +- .../VersionedApiConverterInterceptor.java | 4 +- ...ersionedApiConverterInterceptorR4Test.java | 53 +- hapi-fhir-dist/pom.xml | 16 +- hapi-fhir-docs/pom.xml | 10 +- .../fhir/docs/AuthorizationInterceptors.java | 9 +- .../AuthorizingTesterUiClientFactory.java | 3 +- .../ca/uhn/hapi/fhir/docs/BalpExample.java | 2 +- .../fhir/docs/ClientTransactionExamples.java | 8 +- .../java/ca/uhn/hapi/fhir/docs/Copier.java | 6 +- .../ca/uhn/hapi/fhir/docs/Dstu2Examples.java | 2 +- .../hapi/fhir/docs/ExampleRestfulClient.java | 3 +- .../hapi/fhir/docs/ExampleRestfulServlet.java | 4 +- .../uhn/hapi/fhir/docs/ExtensionsDstu3.java | 9 +- .../uhn/hapi/fhir/docs/FhirContextIntro.java | 6 +- .../ca/uhn/hapi/fhir/docs/FhirDataModel.java | 12 +- .../fhir/docs/JaxRsConformanceProvider.java | 10 +- .../fhir/docs/JaxRsPatientRestProvider.java | 22 +- .../uhn/hapi/fhir/docs/PartitionExamples.java | 2 +- .../fhir/docs/RequestCounterInterceptor.java | 5 +- .../docs/RequestExceptionInterceptor.java | 4 +- .../RestfulPatientResourceProviderMore.java | 63 +- .../hapi/fhir/docs/SecurityInterceptors.java | 5 +- .../hapi/fhir/docs/ServerETagExamples.java | 5 +- .../uhn/hapi/fhir/docs/ServerOperations.java | 10 +- .../uhn/hapi/fhir/docs/ServletExamples.java | 4 +- .../uhn/hapi/fhir/docs/ValidatorExamples.java | 2 +- .../hapi/fhir/changelog/7_0_0/changes.yaml | 25 + .../fhir/docs/server_jpa/database_support.md | 25 +- hapi-fhir-jacoco/pom.xml | 2 +- hapi-fhir-jaxrsserver-base/pom.xml | 27 +- .../fhir/jaxrs/client/JaxRsHttpClient.java | 14 +- .../fhir/jaxrs/client/JaxRsHttpRequest.java | 8 +- .../fhir/jaxrs/client/JaxRsHttpResponse.java | 6 +- .../client/JaxRsRestfulClientFactory.java | 6 +- .../server/AbstractJaxRsBundleProvider.java | 16 +- .../AbstractJaxRsConformanceProvider.java | 12 +- .../server/AbstractJaxRsPageProvider.java | 12 +- .../jaxrs/server/AbstractJaxRsProvider.java | 12 +- .../server/AbstractJaxRsResourceProvider.java | 15 +- .../JaxRsExceptionInterceptor.java | 8 +- .../interceptor/JaxRsResponseException.java | 3 +- .../fhir/jaxrs/server/util/JaxRsRequest.java | 4 +- .../fhir/jaxrs/server/util/JaxRsResponse.java | 4 +- .../client/GenericJaxRsClientDstu2Test.java | 915 ++++++++--------- .../client/GenericJaxRsClientDstu3Test.java | 916 ++++++++---------- .../client/JaxRsRestfulClientFactoryTest.java | 4 +- .../ca/uhn/fhir/jaxrs/client/MyFilter.java | 8 +- ...xRsConformanceProviderDstu2Hl7OrgTest.java | 6 +- ...ctJaxRsConformanceProviderDstu2_1Test.java | 8 +- ...ractJaxRsConformanceProviderDstu3Test.java | 6 +- ...bstractJaxRsConformanceProviderR4Test.java | 6 +- .../AbstractJaxRsConformanceProviderTest.java | 6 +- .../server/AbstractJaxRsProviderTest.java | 8 +- ...bstractJaxRsResourceProviderDstu3Test.java | 4 +- .../AbstractJaxRsResourceProviderTest.java | 4 +- .../JaxRsExceptionInterceptorTest.java | 43 +- .../JaxRsResponseExceptionTest.java | 10 +- .../TestJaxRsConformanceRestProvider.java | 8 +- ...TestJaxRsConformanceRestProviderDstu3.java | 14 +- .../test/TestJaxRsMockPageProvider.java | 9 +- .../test/TestJaxRsMockPageProviderDstu3.java | 8 +- .../TestJaxRsMockPatientRestProvider.java | 54 +- ...xRsMockPatientRestProviderDstu2Hl7Org.java | 10 +- ...stJaxRsMockPatientRestProviderDstu2_1.java | 47 +- ...TestJaxRsMockPatientRestProviderDstu3.java | 10 +- .../TestJaxRsMockPatientRestProviderR4.java | 47 +- .../server/util/JaxRsRequestDstu3Test.java | 6 +- .../jaxrs/server/util/JaxRsRequestTest.java | 7 +- .../server/util/JaxRsResponseDstu3Test.java | 2 +- .../jaxrs/server/util/JaxRsResponseTest.java | 2 +- hapi-fhir-jpa/pom.xml | 12 +- ...ocalContainerEntityManagerFactoryBean.java | 9 +- .../jpa/sched/BaseSchedulerServiceImpl.java | 2 +- .../util/DerbyTenSevenHapiFhirDialect.java | 33 +- .../jpa/util}/ISequenceValueMassager.java | 10 +- hapi-fhir-jpaserver-base/pom.xml | 191 ++-- .../uhn/fhir/jpa/batch2/JpaBatch2Config.java | 3 +- .../jpa/batch2/JpaJobPersistenceImpl.java | 7 +- .../DatabaseBlobBinaryStorageSvcImpl.java | 6 +- ...BulkDataExportJobSchedulingHelperImpl.java | 2 +- .../export/svc/JpaBulkExportProcessor.java | 2 +- .../bulk/imprt/svc/BulkDataImportSvcImpl.java | 2 +- .../fhir/jpa/config/Batch2SupportConfig.java | 3 +- .../fhir/jpa/config/EnversAuditConfig.java | 3 +- .../config/HapiFhirHibernateJpaDialect.java | 2 +- .../ca/uhn/fhir/jpa/config/JpaConfig.java | 12 +- .../util/HapiEntityManagerFactoryUtil.java | 66 +- .../ca/uhn/fhir/jpa/dao/BaseHapiFhirDao.java | 20 +- .../fhir/jpa/dao/BaseHapiFhirResourceDao.java | 17 +- .../fhir/jpa/dao/BaseHapiFhirSystemDao.java | 18 +- .../uhn/fhir/jpa/dao/FhirSystemDaoDstu2.java | 2 +- .../fhir/jpa/dao/FulltextSearchSvcImpl.java | 6 +- .../ca/uhn/fhir/jpa/dao/HistoryBuilder.java | 51 +- ...JpaPersistedResourceValidationSupport.java | 2 +- .../jpa/dao/JpaResourceDaoCodeSystem.java | 2 +- .../jpa/dao/JpaResourceDaoComposition.java | 2 +- .../fhir/jpa/dao/JpaResourceDaoEncounter.java | 2 +- .../jpa/dao/JpaResourceDaoObservation.java | 73 +- .../fhir/jpa/dao/JpaResourceDaoPatient.java | 2 +- .../dao/ObservationLastNIndexPersistSvc.java | 260 ----- .../fhir/jpa/dao/TransactionProcessor.java | 36 +- .../dao/data/IResourceHistoryTableDao.java | 10 +- .../data/custom/IResourceTableDaoImpl.java | 4 +- .../jpa/dao/dstu3/FhirSystemDaoDstu3.java | 2 +- .../dao/expunge/ExpungeEverythingService.java | 75 +- .../dao/index/DaoSearchParamSynchronizer.java | 18 +- .../fhir/jpa/dao/index/IdHelperService.java | 36 +- ...rchParamWithInlineReferencesExtractor.java | 6 +- .../fhir/jpa/dao/mdm/MdmLinkDaoJpaImpl.java | 64 +- .../fhir/jpa/dao/mdm/MdmMetricSvcJpaImpl.java | 8 +- .../uhn/fhir/jpa/dao/r4/FhirSystemDaoR4.java | 2 +- .../fhir/jpa/dao/r4b/FhirSystemDaoR4B.java | 2 +- .../uhn/fhir/jpa/dao/r5/FhirSystemDaoR5.java | 2 +- .../uhn/fhir/jpa/dao/search/PathContext.java | 74 ++ .../delete/DeleteConflictFinderService.java | 8 +- .../delete/batch2/DeleteExpungeSvcImpl.java | 2 +- .../jpa/entity/Batch2JobInstanceEntity.java | 26 +- .../jpa/entity/Batch2WorkChunkEntity.java | 32 +- .../entity/BulkExportCollectionEntity.java | 26 +- .../BulkExportCollectionFileEntity.java | 22 +- .../fhir/jpa/entity/BulkExportJobEntity.java | 28 +- .../fhir/jpa/entity/BulkImportJobEntity.java | 26 +- .../jpa/entity/BulkImportJobFileEntity.java | 24 +- .../jpa/entity/HapiFhirEnversRevision.java | 14 +- .../java/ca/uhn/fhir/jpa/entity/MdmLink.java | 38 +- .../uhn/fhir/jpa/entity/PartitionEntity.java | 11 +- .../jpa/entity/ResourceReindexJobEntity.java | 18 +- .../fhir/jpa/entity/ResourceSearchView.java | 16 +- .../java/ca/uhn/fhir/jpa/entity/Search.java | 43 +- .../ca/uhn/fhir/jpa/entity/SearchInclude.java | 23 +- .../ca/uhn/fhir/jpa/entity/SearchResult.java | 2 +- .../fhir/jpa/entity/SubscriptionTable.java | 2 +- .../uhn/fhir/jpa/entity/TermCodeSystem.java | 2 +- .../jpa/entity/TermCodeSystemVersion.java | 30 +- .../ca/uhn/fhir/jpa/entity/TermConcept.java | 38 +- .../jpa/entity/TermConceptDesignation.java | 24 +- .../uhn/fhir/jpa/entity/TermConceptMap.java | 2 +- .../fhir/jpa/entity/TermConceptMapGroup.java | 2 +- .../entity/TermConceptMapGroupElement.java | 2 +- .../TermConceptMapGroupElementTarget.java | 2 +- .../entity/TermConceptParentChildLink.java | 31 +- .../fhir/jpa/entity/TermConceptProperty.java | 32 +- .../ca/uhn/fhir/jpa/entity/TermValueSet.java | 38 +- .../fhir/jpa/entity/TermValueSetConcept.java | 30 +- .../TermValueSetConceptDesignation.java | 14 +- .../jpa/entity/TermValueSetConceptView.java | 8 +- .../entity/TermValueSetConceptViewOracle.java | 8 +- .../tasks/HapiFhirJpaMigrationTasks.java | 4 + .../fhir/jpa/packages/JpaPackageCache.java | 28 +- .../jpa/packages/PackageInstallerSvcImpl.java | 2 +- .../jpa/partition/PartitionLookupSvcImpl.java | 2 +- .../BaseJpaResourceProviderCodeSystem.java | 2 +- .../BaseJpaResourceProviderComposition.java | 2 +- .../BaseJpaResourceProviderConceptMap.java | 3 +- .../BaseJpaResourceProviderEncounter.java | 4 +- ...BaseJpaResourceProviderEncounterDstu2.java | 4 +- .../BaseJpaResourceProviderObservation.java | 4 +- .../BaseJpaResourceProviderPatient.java | 4 +- .../jpa/provider/BaseJpaSystemProvider.java | 2 +- .../provider/JpaConformanceProviderDstu2.java | 2 +- .../jpa/provider/ProcessMessageProvider.java | 3 +- .../provider/TerminologyUploaderProvider.java | 6 +- .../provider/ValueSetOperationProvider.java | 2 +- .../ValueSetOperationProviderDstu2.java | 2 +- .../dstu3/JpaConformanceProviderDstu3.java | 2 +- .../r4/MemberMatchR4ResourceProvider.java | 2 +- .../HapiHSearchAnalysisConfigurers.java | 58 +- .../search/PersistedJpaBundleProvider.java | 4 +- .../fhir/jpa/search/ResourceSearchUrlSvc.java | 2 +- .../jpa/search/SynchronousSearchSvcImpl.java | 2 +- .../jpa/search/builder/SearchBuilder.java | 25 +- .../BaseQuantityPredicateBuilder.java | 2 +- .../builder/sql/SearchQueryBuilder.java | 13 +- .../builder/sql/SearchQueryExecutor.java | 21 +- .../jpa/search/builder/tasks/SearchTask.java | 2 - .../cache/DatabaseSearchCacheSvcImpl.java | 2 +- .../lastn/ElasticsearchRestClientFactory.java | 15 +- .../search/lastn/ElasticsearchSvcImpl.java | 790 +-------------- .../jpa/search/lastn/IElasticsearchSvc.java | 57 -- .../reindex/ResourceReindexingSvcImpl.java | 10 +- .../jpa/search/warm/CacheWarmingSvcImpl.java | 2 +- .../term/TermCodeSystemStorageSvcImpl.java | 6 +- .../term/TermConceptClientMappingSvcImpl.java | 18 +- .../ca/uhn/fhir/jpa/term/TermReadSvcImpl.java | 12 +- .../jpa/util/PersistenceContextProvider.java | 4 +- .../fhir/jpa/util/QueryParameterUtils.java | 6 +- .../jpa/util/ScrollableResultsIterator.java | 2 +- .../validation/JpaValidationSupportChain.java | 5 +- .../index/DaoSearchParamSynchronizerTest.java | 2 +- .../pom.xml | 42 +- .../config/ElasticsearchWithPrefixConfig.java | 34 +- .../jpa/dao/r4/ElasticsearchPrefixTest.java | 20 +- .../FhirResourceDaoR4SearchLastNAsyncIT.java | 17 +- .../r4/FhirResourceDaoR4SearchLastNIT.java | 58 +- ...LastNUsingExtendedHSearchIndexAsyncIT.java | 27 - ...earchLastNUsingExtendedHSearchIndexIT.java | 60 -- ...esourceDaoR4SearchWithElasticSearchIT.java | 2 +- .../fhir/jpa/dao/r4/HSearchSandboxTest.java | 2 +- ...bservationIndexedSearchParamLastNR4IT.java | 474 --------- .../TokenAutocompleteElasticsearchIT.java | 2 +- ...lasticsearchSvcMultipleObservationsIT.java | 511 ---------- ...tNElasticsearchSvcSingleObservationIT.java | 262 ----- .../search/lastn/LastNTestDataGenerator.java | 144 --- hapi-fhir-jpaserver-hfql/pom.xml | 6 +- .../fql/jdbc/RemoteHfqlExecutionResult.java | 2 +- .../jpa/fql/provider/HfqlRestProvider.java | 4 +- hapi-fhir-jpaserver-ips/pom.xml | 6 +- .../uhn/fhir/jpa/ips/api/SectionRegistry.java | 2 +- hapi-fhir-jpaserver-mdm/pom.xml | 6 +- .../mdm/broker/MdmQueueConsumerLoader.java | 3 +- .../jpa/mdm/svc/MdmControllerSvcImpl.java | 8 +- .../fhir/jpa/mdm/dao/MdmMetricSvcJpaIT.java | 3 +- .../fhir/jpa/mdm/helper/BaseMdmHelper.java | 2 +- .../MdmSearchExpandingInterceptorIT.java | 2 +- .../interceptor/MdmStorageInterceptorIT.java | 6 +- .../jpa/mdm/provider/BaseProviderR4Test.java | 2 + .../mdm/provider/MdmOperationPointcutsIT.java | 19 +- .../MdmProviderCrossPartitionR4Test.java | 3 +- .../fhir/jpa/mdm/svc/MdmMatchLinkSvcTest.java | 1 - .../clear/MdmLinkSlowDeletionSandboxIT.java | 6 +- hapi-fhir-jpaserver-model/pom.xml | 8 +- .../dialect/HapiFhirCockroachDialect.java | 42 + .../model/dialect/HapiFhirDerbyDialect.java | 42 + .../jpa/model/dialect/HapiFhirH2Dialect.java | 45 +- .../model/dialect/HapiFhirMariaDBDialect.java | 42 + .../model/dialect/HapiFhirMySQLDialect.java | 42 + .../model/dialect/HapiFhirOracleDialect.java | 42 + .../dialect/HapiFhirPostgres94Dialect.java | 14 +- .../dialect/HapiFhirPostgresDialect.java | 38 + .../dialect/HapiFhirSQLServerDialect.java | 42 + .../dialect/HapiSequenceStyleGenerator.java | 29 +- .../entity/AuditableBasePartitionable.java | 6 +- .../jpa/model/entity/BaseHasResource.java | 14 +- .../jpa/model/entity/BasePartitionable.java | 7 +- .../jpa/model/entity/BaseResourceIndex.java | 2 +- .../BaseResourceIndexedSearchParam.java | 10 +- ...aseResourceIndexedSearchParamQuantity.java | 5 +- .../ca/uhn/fhir/jpa/model/entity/BaseTag.java | 9 +- .../jpa/model/entity/BinaryStorageEntity.java | 15 +- .../uhn/fhir/jpa/model/entity/ForcedId.java | 28 +- .../jpa/model/entity/NpmPackageEntity.java | 24 +- .../model/entity/NpmPackageVersionEntity.java | 37 +- .../NpmPackageVersionResourceEntity.java | 36 +- .../entity/PartitionablePartitionId.java | 4 +- ...sistedResourceModifiedMessageEntityPK.java | 5 +- .../ResourceHistoryProvenanceEntity.java | 23 +- .../model/entity/ResourceHistoryTable.java | 7 +- .../jpa/model/entity/ResourceHistoryTag.java | 27 +- .../ResourceIndexedComboStringUnique.java | 3 +- .../ResourceIndexedComboTokenNonUnique.java | 25 +- .../ResourceIndexedSearchParamCoords.java | 27 +- .../ResourceIndexedSearchParamDate.java | 32 +- .../ResourceIndexedSearchParamNumber.java | 31 +- .../ResourceIndexedSearchParamQuantity.java | 26 +- ...eIndexedSearchParamQuantityNormalized.java | 26 +- .../ResourceIndexedSearchParamString.java | 25 +- .../ResourceIndexedSearchParamToken.java | 32 +- .../entity/ResourceIndexedSearchParamUri.java | 27 +- .../fhir/jpa/model/entity/ResourceLink.java | 30 +- .../model/entity/ResourceModifiedEntity.java | 13 +- .../model/entity/ResourceSearchUrlEntity.java | 15 +- .../fhir/jpa/model/entity/ResourceTable.java | 38 +- .../fhir/jpa/model/entity/ResourceTag.java | 27 +- .../entity/SearchParamPresentEntity.java | 2 +- .../jpa/model/entity/StorageSettings.java | 2 +- .../fhir/jpa/model/entity/TagDefinition.java | 29 +- .../uhn/fhir/jpa/model/util/JpaConstants.java | 1 - hapi-fhir-jpaserver-searchparam/pom.xml | 10 +- .../model/ReadPartitionIdRequestDetails.java | 2 +- .../fhir/jpa/cache/IResourceChangeEvent.java | 2 +- .../jpa/cache/IResourceChangeListener.java | 2 +- .../cache/IResourceChangeListenerCache.java | 2 +- ...IResourceChangeListenerCacheRefresher.java | 2 +- .../IResourceChangeListenerRegistry.java | 2 +- .../fhir/jpa/cache/IResourceVersionSvc.java | 2 +- .../fhir/jpa/cache/ResourceChangeEvent.java | 2 +- .../cache/ResourceChangeListenerCache.java | 2 +- .../ResourceChangeListenerCacheFactory.java | 2 +- ...ourceChangeListenerCacheRefresherImpl.java | 2 +- .../ResourceChangeListenerRegistryImpl.java | 2 +- ...urceChangeListenerRegistryInterceptor.java | 5 +- .../fhir/jpa/cache/ResourceChangeResult.java | 2 +- .../jpa/cache/ResourcePersistentIdMap.java | 2 +- .../fhir/jpa/cache/ResourceVersionCache.java | 2 +- .../fhir/jpa/cache/ResourceVersionMap.java | 2 +- .../partition/IRequestPartitionHelperSvc.java | 2 +- .../fhir/jpa/searchparam/MatchUrlService.java | 2 +- .../jpa/searchparam/ResourceMetaParams.java | 2 +- .../fhir/jpa/searchparam/ResourceSearch.java | 2 +- .../jpa/searchparam/SearchParamConstants.java | 2 +- .../jpa/searchparam/SearchParameterMap.java | 2 +- .../config/NicknameServiceConfig.java | 2 +- .../searchparam/config/SearchParamConfig.java | 2 +- .../extractor/BaseSearchParamExtractor.java | 4 +- .../CrossPartitionReferenceDetails.java | 2 +- .../extractor/GeopointNormalizer.java | 2 +- .../extractor/IResourceLinkResolver.java | 2 +- .../extractor/ISearchParamExtractor.java | 2 +- .../extractor/LogicalReferenceHelper.java | 2 +- .../jpa/searchparam/extractor/PathAndRef.java | 2 +- .../ResourceIndexedSearchParamComposite.java | 2 +- .../ResourceIndexedSearchParams.java | 2 +- .../extractor/SearchParamExtractorDstu2.java | 2 +- .../extractor/SearchParamExtractorDstu3.java | 4 +- .../extractor/SearchParamExtractorR4.java | 4 +- .../extractor/SearchParamExtractorR4B.java | 4 +- .../extractor/SearchParamExtractorR5.java | 4 +- .../SearchParamExtractorService.java | 2 +- .../StringTrimmingTrimmerMatcher.java | 2 +- .../AuthorizationSearchParamMatcher.java | 2 +- .../matcher/InMemoryMatchResult.java | 2 +- .../matcher/InMemoryResourceMatcher.java | 2 +- .../matcher/IndexedSearchParamExtractor.java | 2 +- .../matcher/SearchParamMatcher.java | 2 +- .../nickname/NicknameInterceptor.java | 2 +- .../SearchableHashMapResourceProvider.java | 2 +- .../registry/ISearchParamProvider.java | 2 +- .../ISearchParamRegistryController.java | 2 +- .../registry/JpaSearchParamCache.java | 2 +- .../registry/ReadOnlySearchParamCache.java | 2 +- .../registry/RuntimeSearchParamCache.java | 2 +- .../registry/SearchParamRegistryImpl.java | 6 +- .../SearchParameterCanonicalizer.java | 2 +- .../fhir/jpa/searchparam/retry/Retrier.java | 2 +- .../searchparam/util/Dstu3DistanceHelper.java | 2 +- .../jpa/searchparam/util/JpaParamUtil.java | 2 +- .../util/LastNParameterHelper.java | 2 +- .../util/RuntimeSearchParamHelper.java | 2 +- .../util/SearchParameterHelper.java | 2 +- .../jpa/searchparam/util/SourceParam.java | 2 +- hapi-fhir-jpaserver-subscription/pom.xml | 13 +- .../match/deliver/email/EmailDetails.java | 4 +- .../SubscriptionWebsocketHandler.java | 4 +- .../MatchingQueueSubscriberLoader.java | 3 +- .../match/registry/SubscriptionRegistry.java | 2 +- .../SubscriptionSubmitInterceptorLoader.java | 2 +- .../SubscriptionTriggeringSvcImpl.java | 2 +- ...castingSubscribableChannelWrapperTest.java | 2 +- ...aseSubscriptionDeliverySubscriberTest.java | 4 +- .../module/SubscriptionTestConfig.java | 2 +- ...kingQueueSubscribableChannelDstu3Test.java | 6 +- hapi-fhir-jpaserver-test-dstu2/pom.xml | 2 +- .../jpa/dao/dstu2/BaseJpaDstu2SystemTest.java | 6 +- .../fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java | 2 +- .../FhirResourceDaoDstu2SearchFtTest.java | 2 +- .../FhirResourceDaoDstu2SearchNoFtTest.java | 2 +- .../jpa/provider/SubscriptionsDstu2Test.java | 14 +- .../jpa/provider/SystemProviderDstu2Test.java | 4 +- ...temProviderTransactionSearchDstu2Test.java | 4 +- .../resthook/RestHookTestDstu2Test.java | 4 +- ...rRegisteredToStorageSettingsDstu2Test.java | 4 +- hapi-fhir-jpaserver-test-dstu3/pom.xml | 2 +- .../jpa/dao/dstu3/BaseJpaDstu3SystemTest.java | 6 +- .../FhirResourceDaoDstu3SearchFtTest.java | 2 +- .../FhirResourceDaoDstu3SearchNoFtTest.java | 2 +- .../jpa/dao/dstu3/FhirSystemDaoDstu3Test.java | 2 +- .../jpa/packages/IgInstallerDstu3Test.java | 37 +- .../uhn/fhir/jpa/packages/NpmDstu3Test.java | 65 +- .../dstu3/SubscriptionsDstu3Test.java | 14 +- ...temProviderTransactionSearchDstu3Test.java | 4 +- .../resthook/RestHookTestDstu3Test.java | 6 +- ...rRegisteredToStorageSettingsDstu3Test.java | 4 +- .../SubscriptionTriggeringDstu3Test.java | 6 +- hapi-fhir-jpaserver-test-r4/pom.xml | 13 +- .../jpa/batch2/Batch2JobMaintenanceIT.java | 2 +- .../binstore/BinaryAccessProviderTest.java | 6 +- .../bulk/imprt2/ConsumeFilesStepR4Test.java | 4 +- .../uhn/fhir/jpa/dao/BaseHapiFhirDaoTest.java | 18 +- .../jpa/dao/BaseHapiFhirResourceDaoTest.java | 4 +- .../jpa/dao/TransactionProcessorTest.java | 4 +- .../expunge/ResourceTableFKProviderTest.java | 6 +- .../fhir/jpa/dao/r4/BaseJpaR4SystemTest.java | 4 +- .../r4/FhirResourceDaoR4QueryCountTest.java | 19 +- .../dao/r4/FhirResourceDaoR4SearchFtTest.java | 2 +- .../r4/FhirResourceDaoR4SearchNoFtTest.java | 33 +- .../FhirResourceDaoR4SearchOptimizedTest.java | 18 +- .../r4/FhirResourceDaoR4SearchSqlTest.java | 6 +- .../dao/r4/FhirResourceDaoR4UpdateTest.java | 2 +- .../fhir/jpa/dao/r4/FhirSystemDaoR4Test.java | 2 +- .../jpa/dao/r4/PartitioningSqlR4Test.java | 38 +- .../fhir/jpa/delete/job/ReindexJobTest.java | 9 +- ...adingDeleteInterceptorMultiThreadTest.java | 4 +- .../ForceOffsetSearchModeInterceptorTest.java | 8 +- .../PartitioningInterceptorR4Test.java | 2 +- .../PatientIdPartitionInterceptorTest.java | 6 +- .../ca/uhn/fhir/jpa/packages/NpmR4Test.java | 44 +- .../fhir/jpa/packages/NpmSearchR4Test.java | 4 +- .../packages/loader/PackageLoaderSvcIT.java | 37 +- ...rtitionedSubscriptionTriggeringR4Test.java | 2 +- .../jpa/provider/r4/EmptyIndexesR4Test.java | 4 +- .../provider/r4/MultitenantServerR4Test.java | 2 +- ...minologyServiceResourceProviderR4Test.java | 2 +- ...sourceProviderCustomSearchParamR4Test.java | 8 +- .../r4/ResourceProviderInterceptorR4Test.java | 2 +- ...oviderOnlySomeResourcesProvidedR4Test.java | 4 +- ...sourceProviderR4RemoteTerminologyTest.java | 2 +- .../provider/r4/ResourceProviderR4Test.java | 12 +- ...rceProviderR4ValueSetNoVerCSNoVerTest.java | 8 +- .../jpa/provider/r4/SubscriptionsR4Test.java | 14 +- .../jpa/provider/r4/SystemProviderR4Test.java | 4 +- ...SystemProviderTransactionSearchR4Test.java | 4 +- .../stresstest/GiantTransactionPerfTest.java | 29 +- .../subscription/BaseSubscriptionsR4Test.java | 2 +- ...tivatesPreExistingSubscriptionsR4Test.java | 6 +- ...ptorRegisteredToStorageSettingsR4Test.java | 4 +- .../uhn/fhir/jpa/term/ITermReadSvcTest.java | 4 +- ...erminologySvcImplCurrentVersionR4Test.java | 4 +- .../ReindexTerminologyHSearchR4Test.java | 2 +- hapi-fhir-jpaserver-test-r4b/pom.xml | 2 +- .../uhn/fhir/jpa/dao/r4b/BaseJpaR4BTest.java | 2 +- .../BaseSubscriptionsR4BTest.java | 2 +- hapi-fhir-jpaserver-test-r5/pom.xml | 2 +- .../ca/uhn/fhir/jpa/dao/r5/BaseJpaR5Test.java | 2 +- .../r5/FhirSystemDaoTransactionR5Test.java | 2 +- .../subscription/BaseSubscriptionsR5Test.java | 8 +- hapi-fhir-jpaserver-test-utilities/pom.xml | 50 +- .../HapiEmbeddedDatabasesExtension.java | 23 +- ...nterceptorReadPartitionsBasedOnScopes.java | 2 +- .../uhn/fhir/jpa/packages/FakeNpmServlet.java | 6 +- .../CodeSystemLookupWithPropertiesUtil.java | 19 + .../r4/BaseResourceProviderR4Test.java | 4 +- .../jpa/subscription/NotificationServlet.java | 9 +- .../subscription/SocketImplementation.java | 18 +- .../uhn/fhir/jpa/test/BaseJpaDstu3Test.java | 2 +- .../ca/uhn/fhir/jpa/test/BaseJpaR4Test.java | 42 +- .../ca/uhn/fhir/jpa/test/BaseJpaTest.java | 2 +- .../BaseValueSetHSearchExpansionR4Test.java | 2 +- .../fhir/jpa/test/config/TestDstu2Config.java | 9 +- .../fhir/jpa/test/config/TestDstu3Config.java | 9 +- .../test/config/TestHSearchAddInConfig.java | 2 +- .../jpa/test/config/TestHapiJpaConfig.java | 19 + .../fhir/jpa/test/config/TestJPAConfig.java | 2 +- .../fhir/jpa/test/config/TestR4BConfig.java | 9 +- .../fhir/jpa/test/config/TestR4Config.java | 76 +- .../fhir/jpa/test/config/TestR5Config.java | 11 +- .../jpa/util/WebsocketSubscriptionClient.java | 26 +- .../jpa/config/DispatcherServletConfig.java | 2 +- .../HapiFhirHibernateJpaDialectTest.java | 4 +- .../jpa/dao/index/ResourceVersionSvcTest.java | 10 +- .../jpa/embedded/HapiSchemaMigrationTest.java | 4 + ...lIT.java => SchedulerServiceImplTest.java} | 6 +- .../SearchQueryBuilderDialectMySqlTest.java | 3 +- ...SearchQueryBuilderDialectPostgresTest.java | 7 +- ...earchQueryBuilderDialectSqlServerTest.java | 18 +- .../builder/sql/SearchQueryBuilderTest.java | 110 +-- .../jpa/term/LoincFullLoadR4SandboxIT.java | 8 +- hapi-fhir-jpaserver-uhnfhirtest/pom.xml | 70 +- .../ca/uhn/fhirtest/TestRestfulServer.java | 8 +- .../FhirTestBalpAuditContextServices.java | 3 +- .../uhn/fhirtest/config/FhirTesterConfig.java | 3 +- .../uhn/fhirtest/config/TestAuditConfig.java | 10 +- .../uhn/fhirtest/config/TestDstu2Config.java | 8 +- .../uhn/fhirtest/config/TestDstu3Config.java | 8 +- .../ca/uhn/fhirtest/config/TestR4BConfig.java | 8 +- .../ca/uhn/fhirtest/config/TestR4Config.java | 8 +- .../ca/uhn/fhirtest/config/TestR5Config.java | 8 +- .../interceptor/AnalyticsInterceptor.java | 2 +- .../fhirtest/joke/HolyFooCowInterceptor.java | 5 +- .../migrate/FhirTestAutoMigrator.java | 2 +- .../mvc/SubscriptionPlaygroundController.java | 2 +- .../java/ca/uhn/fhirtest/UhnFhirTestApp.java | 4 +- hapi-fhir-server-cds-hooks/pom.xml | 2 +- .../json/CdsServiceRequestContextJson.java | 3 + .../cdshooks/svc/CdsHooksContextBooter.java | 2 +- .../cdshooks/svc/CdsServiceRegistryImpl.java | 2 +- hapi-fhir-server-mdm/pom.xml | 2 +- .../fhir/mdm/provider/MdmProviderLoader.java | 3 +- hapi-fhir-server-openapi/pom.xml | 17 +- .../fhir/rest/openapi/OpenApiInterceptor.java | 10 +- .../rest/openapi/OpenApiInterceptorTest.java | 23 +- hapi-fhir-server/pom.xml | 6 +- .../rest/api/server/IRestfulResponse.java | 2 +- .../fhir/rest/api/server/RequestDetails.java | 9 +- .../server/storage/TransactionDetails.java | 11 +- .../server/ApacheProxyAddressStrategy.java | 4 +- .../HardcodedServerAddressStrategy.java | 5 +- .../rest/server/IServerAddressStrategy.java | 4 +- .../server/IServerConformanceProvider.java | 3 +- .../IncomingRequestAddressStrategy.java | 5 +- .../uhn/fhir/rest/server/ResourceBinding.java | 21 +- .../uhn/fhir/rest/server/RestfulServer.java | 18 +- .../fhir/rest/server/RestfulServerUtils.java | 41 +- .../rest/server/ServletRequestTracing.java | 4 +- .../BanUnsupportedHttpMethodsInterceptor.java | 4 +- .../server/interceptor/CorsInterceptor.java | 4 +- .../ExceptionHandlingInterceptor.java | 6 +- .../interceptor/IServerInterceptor.java | 10 +- .../interceptor/InterceptorAdapter.java | 6 +- .../interceptor/LoggingInterceptor.java | 6 +- .../RequestValidatingInterceptor.java | 4 +- .../ResponseHighlighterInterceptor.java | 6 +- .../SearchPreferHandlingInterceptor.java | 4 +- .../ServeMediaResourceRawInterceptor.java | 4 +- .../VerboseLoggingInterceptor.java | 4 +- .../auth/SearchNarrowingInterceptor.java | 4 +- .../BaseOutcomeReturningMethodBinding.java | 8 +- ...indingWithResourceIdButNoResourceBody.java | 6 +- .../BaseResourceReturningMethodBinding.java | 4 +- .../server/method/GraphQLMethodBinding.java | 4 +- .../fhir/rest/server/method/MethodUtil.java | 34 +- .../rest/server/method/SearchParameter.java | 64 +- .../rest/server/method/SortParameter.java | 8 +- .../server/method/SummaryEnumParameter.java | 5 +- .../ServerCapabilityStatementProvider.java | 4 +- .../server/servlet/ServletRequestDetails.java | 4 +- .../servlet/ServletRestfulResponse.java | 4 +- .../servlet/ServletSubRequestDetails.java | 5 +- .../server/util/ITestingUiClientFactory.java | 3 +- .../IncomingRequestAddressStrategyTest.java | 2 +- .../rest/server/SimpleBundleProviderTest.java | 2 +- .../server/interceptor/ConfigLoaderTest.java | 4 +- .../method/ConformanceMethodBindingTest.java | 2 +- .../server/method/MethodMatchEnumTest.java | 2 +- .../servlet/ServletRequestDetailsTest.java | 2 +- .../servlet/ServletRestfulResponseTest.java | 2 +- .../hapi-fhir-caching-api/pom.xml | 2 +- .../hapi-fhir-caching-caffeine/pom.xml | 4 +- .../hapi-fhir-caching-guava/pom.xml | 2 +- .../hapi-fhir-caching-testing/pom.xml | 2 +- hapi-fhir-serviceloaders/pom.xml | 2 +- .../pom.xml | 6 +- .../autoconfigure/FhirAutoConfiguration.java | 4 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../provider/PatientResourceProvider.java | 4 +- ...pleJerseyRestfulServerApplicationTest.java | 12 +- .../hapi-fhir-spring-boot-samples/pom.xml | 2 +- .../hapi-fhir-spring-boot-starter/pom.xml | 2 +- hapi-fhir-spring-boot/pom.xml | 2 +- hapi-fhir-sql-migrate/pom.xml | 4 +- .../uhn/fhir/jpa/migrate/DriverTypeEnum.java | 14 +- .../ca/uhn/fhir/jpa/migrate/JdbcUtils.java | 19 +- .../migrate/entity/HapiMigrationEntity.java | 10 +- .../jpa/migrate/taskdef/ColumnTypeEnum.java | 8 +- .../ColumnTypeToDriverTypeToSqlType.java | 14 +- .../jpa/migrate/taskdef/AddColumnTest.java | 2 +- hapi-fhir-storage-batch2-jobs/pom.xml | 6 +- .../jobs/export/BulkDataExportProvider.java | 2 +- .../jobs/imprt/BulkDataImportProvider.java | 2 +- .../jobs/imprt/BulkImportFileServlet.java | 6 +- .../jobs/imprt/BulkImportJobParameters.java | 8 +- .../fhir/batch2/jobs/BaseR4ServerTest.java | 4 +- .../imprt/BulkDataImportProviderTest.java | 2 +- .../pom.xml | 2 +- .../test/support/TestJobParameters.java | 2 +- hapi-fhir-storage-batch2/pom.xml | 20 +- .../coordinator/JobCoordinatorImpl.java | 4 +- .../JobParameterJsonValidator.java | 8 +- .../jobs/parameters/PartitionedUrl.java | 3 +- .../uhn/fhir/batch2/model/JobDefinition.java | 6 +- .../batch2/coordinator/TestJobParameters.java | 2 +- .../JobMaintenanceServiceImplTest.java | 4 +- hapi-fhir-storage-cr/pom.xml | 28 +- .../fhir/cr/dstu3/BaseCrDstu3TestServer.java | 4 +- .../ca/uhn/fhir/cr/r4/BaseCrR4TestServer.java | 4 +- hapi-fhir-storage-mdm/pom.xml | 2 +- .../MdmSubmitterInterceptorLoader.java | 3 +- .../batch2/clear/MdmClearJobParameters.java | 2 +- hapi-fhir-storage-test-utilities/pom.xml | 2 +- hapi-fhir-storage/pom.xml | 8 +- .../cache/BaseResourceCacheSynchronizer.java | 4 +- .../fhir/jpa/api/dao/IFhirResourceDao.java | 2 +- .../api/dao/IFhirResourceDaoComposition.java | 3 +- .../api/dao/IFhirResourceDaoEncounter.java | 3 +- .../api/dao/IFhirResourceDaoObservation.java | 3 +- .../jpa/api/dao/IFhirResourceDaoPatient.java | 3 +- .../binary/provider/BinaryAccessProvider.java | 4 +- .../ca/uhn/fhir/jpa/dao/ISearchBuilder.java | 2 +- .../dao/expunge/PartitionAwareSupplier.java | 6 +- .../jpa/dao/tx/HapiTransactionService.java | 29 +- .../SearchBuilderLoadIncludesParameters.java | 2 +- .../fhir/jpa/provider/BaseJpaProvider.java | 2 +- .../jpa/provider/BaseJpaResourceProvider.java | 4 +- .../provider/BaseStorageSystemProvider.java | 2 - .../impl/LinkedBlockingChannelFactory.java | 2 +- .../CircularQueueCaptureQueriesListener.java | 36 +- .../java/ca/uhn/fhir/jpa/util/SqlQuery.java | 3 + ...ncMemoryQueueBackedFhirClientBalpSink.java | 2 +- .../balp/BalpAuditCaptureInterceptor.java | 20 +- .../balp/IBalpAuditContextServices.java | 2 +- .../balp/BalpAuditCaptureInterceptorTest.java | 17 +- hapi-fhir-structures-dstu2.1/pom.xml | 69 +- .../server/ServerConformanceProvider.java | 8 +- .../rest/server/CreateBinaryDstu2_1Test.java | 172 ---- .../fhir/rest/server/CreateDstu2_1Test.java | 283 ------ .../rest/server/CustomTypeServerDstu2_1.java | 59 +- .../server/DeleteConditionalDstu2_1Test.java | 132 --- .../server/FormatParameterDstu2_1Test.java | 255 ----- .../MetadataConformanceDstu2_1Test.java | 191 ---- .../server/OperationServerDstu2_1Test.java | 786 --------------- ...ServerWithSearchParamTypesDstu2_1Test.java | 514 ---------- .../fhir/rest/server/PatchDstu2_1Test.java | 188 ---- .../uhn/fhir/rest/server/ReadDstu2_1Test.java | 122 --- .../server/SearchCountParamDstu2_1Test.java | 184 ---- .../fhir/rest/server/SearchDstu2_1Test.java | 142 --- .../server/SearchHasParamDstu2_1Test.java | 121 --- .../rest/server/SearchPostDstu2_1Test.java | 260 ----- .../rest/server/SearchSortDstu2_1Test.java | 132 --- .../SearchWithGenericListDstu2_1Test.java | 57 +- .../server/SearchWithIncludesDstu2_1Test.java | 135 --- ...hWithServerAddressStrategyDstu2_1Test.java | 172 ---- .../server/ServerExceptionDstu2_1Test.java | 137 --- .../server/ServerMimetypeDstu2_1Test.java | 422 -------- .../ServerUsingOldTypesDstu2_1Test.java | 2 +- ...nclassifiedServerExceptionDstu2_1Test.java | 108 --- .../fhir/rest/server/UpdateDstu2_1Test.java | 195 ---- .../fhir/rest/server/ValidateDstu2_1Test.java | 327 ------- hapi-fhir-structures-dstu2/pom.xml | 50 +- .../dstu2/ServerConformanceProvider.java | 4 +- ...tThymeleafNarrativeGeneratorDstu2Test.java | 2 +- .../apache/ApacheClientIntegrationTest.java | 57 +- .../uhn/fhir/rest/server/BinaryDstu2Test.java | 70 +- .../rest/server/BundleTypeInResponseTest.java | 49 +- .../rest/server/CompartmentDstu2Test.java | 63 +- .../rest/server/CreateConditionalTest.java | 66 +- .../uhn/fhir/rest/server/DeleteDstu2Test.java | 52 +- .../uhn/fhir/rest/server/ETagServerTest.java | 64 +- .../IncludeAndRevincludeParameterTest.java | 53 +- .../fhir/rest/server/IncludeDstu2Test.java | 70 +- .../OperationDuplicateServerDstu2Test.java | 56 +- .../rest/server/OperationServerDstu2Test.java | 114 +-- ...onServerWithSearchParamTypesDstu2Test.java | 68 +- .../rest/server/PatientResourceProvider.java | 2 +- .../uhn/fhir/rest/server/ReadDstu2Test.java | 66 +- ...archBundleProviderWithNoSizeDstu2Test.java | 4 +- .../server/SearchCountParamDstu2Test.java | 62 +- .../uhn/fhir/rest/server/SearchDstu2Test.java | 111 +-- ...rchReturningProfiledResourceDstu2Test.java | 75 +- .../server/SearchWithDstu2BundleTest.java | 51 +- .../SearchWithGenericListDstu2Test.java | 57 +- .../ServerConformanceProviderDstu2Test.java | 18 +- .../rest/server/ServerFeaturesDstu2Test.java | 99 +- .../rest/server/ServerSearchDstu2Test.java | 66 +- .../rest/server/SummaryParamDstu2Test.java | 71 +- ...ransactionWithBundleResourceParamTest.java | 4 +- ...ithVersionlessBundleResourceParamTest.java | 4 +- .../uhn/fhir/rest/server/UpdateDstu2Test.java | 57 +- .../fhir/rest/server/ValidateDstu2Test.java | 54 +- .../InterceptorUserDataMapDstu2Test.java | 59 +- .../LoggingInterceptorDstu2Test.java | 114 +-- .../ServerActionInterceptorTest.java | 136 ++- hapi-fhir-structures-dstu3/pom.xml | 52 +- .../ServerCapabilityStatementProvider.java | 4 +- .../context/ContextScanningDstu3Test.java | 42 +- ...tThymeleafNarrativeGeneratorDstu3Test.java | 2 +- .../rest/server/CreateBinaryDstu3Test.java | 53 +- .../uhn/fhir/rest/server/CreateDstu3Test.java | 67 +- .../rest/server/CustomTypeServerDstu3.java | 52 +- .../server/DeleteConditionalDstu3Test.java | 67 +- .../rest/server/FormatParameterDstu3Test.java | 86 +- .../rest/server/InterceptorDstu3Test.java | 80 +- .../MetadataCapabilityStatementDstu3Test.java | 73 +- .../server/MetadataConformanceDstu3Test.java | 68 +- .../rest/server/OperationServerDstu3Test.java | 96 +- ...onServerWithSearchParamTypesDstu3Test.java | 70 +- .../rest/server/PatchServerDstu3Test.java | 63 +- ...archBundleProviderWithNoSizeDstu3Test.java | 4 +- .../server/SearchCountParamDstu3Test.java | 62 +- .../server/SearchDefaultMethodDstu3Test.java | 58 +- .../uhn/fhir/rest/server/SearchDstu3Test.java | 71 +- .../rest/server/SearchHasParamDstu3Test.java | 48 +- .../fhir/rest/server/SearchPostDstu3Test.java | 68 +- .../fhir/rest/server/SearchSortDstu3Test.java | 48 +- .../SearchWithGenericListDstu3Test.java | 58 +- .../server/SearchWithIncludesDstu3Test.java | 50 +- ...rchWithServerAddressStrategyDstu3Test.java | 85 +- .../rest/server/ServerExceptionDstu3Test.java | 66 +- .../rest/server/ServerMimetypeDstu3Test.java | 77 +- .../server/ServerUsingOldTypesDstu3Test.java | 2 +- .../UnclassifiedServerExceptionDstu3Test.java | 49 +- .../fhir/rest/server/ValidateDstu3Test.java | 61 +- ...pprtedHttpMethodsInterceptorDstu3Test.java | 61 +- .../interceptor/CorsInterceptorDstu3Test.java | 4 +- .../AuthorizationInterceptorDstu3Test.java | 67 +- .../rest/server/PatientResourceProvider.java | 2 +- ...rCapabilityStatementProviderDstu3Test.java | 18 +- hapi-fhir-structures-hl7org-dstu2/pom.xml | 69 +- .../server/ServerConformanceProvider.java | 4 +- .../rest/server/BinaryHl7OrgDstu2Test.java | 59 +- .../BundleTypeInResponseHl7OrgTest.java | 52 +- .../server/CreateConditionalHl7OrgTest.java | 66 +- .../server/DeleteConditionalHl7OrgTest.java | 60 +- ...cludeAndRevincludeParameterHl7OrgTest.java | 56 +- .../rest/server/IncludeHl7OrgDstu2Test.java | 77 +- ...erationDuplicateServerHl7OrgDstu2Test.java | 58 +- .../server/OperationServerHl7OrgTest.java | 80 +- .../rest/server/PreferHl7OrgDstu2Test.java | 62 +- .../fhir/rest/server/ReadHl7OrgDstu2Test.java | 63 +- .../rest/server/SearchHl7OrgDstu2Test.java | 59 +- .../SearchWithGenericListHl7OrgDstu2Test.java | 57 +- .../SearchWithHl7OrgDstu2BundleTest.java | 63 +- ...verConformanceProviderHl7OrgDstu2Test.java | 8 +- ...ithBundleResourceParamHl7OrgDstu2Test.java | 4 +- .../UpdateConditionalHl7OrgDstu2Test.java | 66 +- .../rest/server/ValidateHl7OrgDstu2Test.java | 59 +- hapi-fhir-structures-r4/pom.xml | 69 +- ...stomThymeleafNarrativeGeneratorR4Test.java | 5 +- ...aultThymeleafNarrativeGeneratorR4Test.java | 2 +- .../ca/uhn/fhir/parser/RDFParserTest.java | 3 + .../fhir/rest/client/ClientHeadersR4Test.java | 10 +- .../rest/client/ClientIntegrationTest.java | 53 +- ...ompressOutgoingContentInterceptorTest.java | 54 +- .../uhn/fhir/rest/client/HttpProxyTest.java | 10 +- .../rest/client/LoggingInterceptorTest.java | 43 +- .../fhir/rest/param/DateRangeParamR4Test.java | 80 +- .../fhir/rest/server/BaseR4ServerTest.java | 51 +- .../fhir/rest/server/BinaryServerR4Test.java | 73 +- .../CapabilityStatementCacheR4Test.java | 2 +- .../ca/uhn/fhir/rest/server/CreateR4Test.java | 92 +- .../rest/server/DeleteConditionalR4Test.java | 52 +- .../fhir/rest/server/ETagServerR4Test.java | 70 +- .../fhir/rest/server/ElementsParamR4Test.java | 91 +- .../uhn/fhir/rest/server/HistoryR4Test.java | 71 +- .../ca/uhn/fhir/rest/server/IncludeTest.java | 70 +- .../fhir/rest/server/LastNProviderTest.java | 5 +- .../fhir/rest/server/MultitenancyR4Test.java | 73 +- .../server/OperationGenericServer2R4Test.java | 90 +- .../server/OperationGenericServerR4Test.java | 59 +- .../rest/server/OperationServerR4Test.java | 4 +- .../ca/uhn/fhir/rest/server/PagingTest.java | 2 +- .../server/PagingUsingNamedPagesR4Test.java | 78 +- .../rest/server/PatientResourceProvider.java | 2 +- .../fhir/rest/server/PlainProviderR4Test.java | 74 +- .../ca/uhn/fhir/rest/server/PreferTest.java | 69 +- ...onseCodeModifyingResourceProviderTest.java | 2 +- .../fhir/rest/server/RestfulServerTest.java | 4 +- .../SearchBundleProviderWithNoSizeR4Test.java | 48 +- .../rest/server/SearchHasParamR4Test.java | 49 +- .../ca/uhn/fhir/rest/server/SearchR4Test.java | 6 + .../rest/server/SearchSearchServerR4Test.java | 113 +-- .../fhir/rest/server/SearchSortR4Test.java | 52 +- .../rest/server/ServerConcurrencyTest.java | 8 +- .../server/ServerInvalidDefinitionR4Test.java | 21 +- .../server/ServerMethodSelectionR4Test.java | 18 +- .../rest/server/ServerMimetypeR4Test.java | 96 +- .../fhir/rest/server/SummaryParamR4Test.java | 69 +- .../interceptor/ConsentInterceptorTest.java | 9 +- .../ExceptionHandlingInterceptorTest.java | 4 +- .../ExceptionInterceptorMethodTest.java | 61 +- .../interceptor/InjectionAttackTest.java | 69 +- .../InterceptorThrowingExceptionR4Test.java | 68 +- ...> ResponseHighlighterInterceptorTest.java} | 181 ++-- .../ServeMediaResourceRawInterceptorTest.java | 73 +- ...eHighlightingInterceptorExceptionTest.java | 53 +- .../test/resources/junit-platform.properties | 2 + hapi-fhir-structures-r4b/pom.xml | 63 +- .../rest/server/PatientResourceProvider.java | 2 +- .../uhn/fhir/rest/server/SearchR4BTest.java | 48 +- ...verCapabilityStatementProviderR4BTest.java | 6 +- hapi-fhir-structures-r5/pom.xml | 63 +- .../rest/server/PatientResourceProvider.java | 2 +- .../ca/uhn/fhir/rest/server/SearchR5Test.java | 48 +- ...rverCapabilityStatementProviderR5Test.java | 6 +- hapi-fhir-test-utilities/pom.xml | 49 +- .../test/utilities/BaseRestServerHelper.java | 6 +- .../test/utilities/HttpClientExtension.java | 25 +- .../test/utilities/RestServerDstu3Helper.java | 2 +- .../test/utilities/RestServerR4Helper.java | 17 +- .../docker/DockerRequiredCondition.java | 30 +- .../jpa/JpaModelScannerAndVerifier.java | 53 +- .../server/BaseJettyServerExtension.java | 62 +- .../server/HttpServletExtension.java | 2 +- .../utilities/server/MockServletUtil.java | 2 +- .../server/RequestCaptureServlet.java | 113 +++ .../server/RestfulServerExtension.java | 17 +- hapi-fhir-testpage-overlay/pom.xml | 33 +- .../java/ca/uhn/fhir/to/BaseController.java | 4 +- .../main/java/ca/uhn/fhir/to/Controller.java | 4 +- .../ca/uhn/fhir/to/FhirTesterMvcConfig.java | 6 +- .../java/ca/uhn/fhir/to/TesterConfig.java | 4 +- .../to/client/BearerTokenClientFactory.java | 3 +- .../ca/uhn/fhir/to/model/HomeRequest.java | 11 +- .../uhn/fhir/to/mvc/ToBindingInitializer.java | 6 - .../uhn/fhir/jpa/test/FhirServerConfig.java | 2 +- .../ca/uhn/fhir/jpa/test/OverlayTestApp.java | 17 +- .../java/ca/uhn/fhir/jpa/test/WebTest.java | 33 +- .../pom.xml | 2 +- hapi-fhir-validation-resources-dstu2/pom.xml | 2 +- hapi-fhir-validation-resources-dstu3/pom.xml | 2 +- hapi-fhir-validation-resources-r4/pom.xml | 2 +- hapi-fhir-validation-resources-r4b/pom.xml | 2 +- hapi-fhir-validation-resources-r5/pom.xml | 2 +- hapi-fhir-validation/pom.xml | 59 +- .../rest/server/PatientResourceProvider.java | 2 +- ...RequestValidatingInterceptorDstu3Test.java | 84 +- ...esponseValidatingInterceptorDstu3Test.java | 86 +- ...rverCapabilityStatementProviderR4Test.java | 4 +- .../auth/AuthorizationInterceptorR4Test.java | 797 ++++++++------- ...rminologyServiceValidationSupportTest.java | 2 +- ...logyServiceValidationSupportDstu3Test.java | 2 +- hapi-tinder-plugin/pom.xml | 26 +- .../tinder/ddl/DdlGeneratorHibernate61.java | 214 ++++ .../uhn/fhir/tinder/ddl/GenerateDdlMojo.java | 128 +++ .../resources/vm/jpa_resource_provider.vm | 4 +- hapi-tinder-test/pom.xml | 2 +- .../src/test/java/test/TestAntTask.java | 7 +- .../FhirInstanceValidatorTest.java | 2 - .../ResourceValidatorDstu3FeatureTest.java | 7 +- .../karaf/r4/R4JsonParserTest.java | 1 - pom.xml | 278 +++--- .../pom.xml | 13 +- .../example/ExtendedOrganizationResource.kt | 8 +- .../ExtendedOrganizationResourceTest.kt | 2 +- .../pom.xml | 4 +- .../pom.xml | 17 +- .../ca/uhn/fhir/testmindeps/ReadTest.java | 50 +- 876 files changed, 9407 insertions(+), 17801 deletions(-) rename hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/{BulkImportCommandIT.java => BulkImportCommandTest.java} (94%) rename {hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect => hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/util}/ISequenceValueMassager.java (87%) delete mode 100644 hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/ObservationLastNIndexPersistSvc.java delete mode 100644 hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexAsyncIT.java delete mode 100644 hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexIT.java delete mode 100644 hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/PersistObservationIndexedSearchParamLastNR4IT.java delete mode 100644 hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNElasticsearchSvcMultipleObservationsIT.java delete mode 100644 hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNElasticsearchSvcSingleObservationIT.java delete mode 100644 hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNTestDataGenerator.java create mode 100644 hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirCockroachDialect.java create mode 100644 hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirDerbyDialect.java create mode 100644 hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirMariaDBDialect.java create mode 100644 hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirMySQLDialect.java create mode 100644 hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirOracleDialect.java create mode 100644 hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirPostgresDialect.java create mode 100644 hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirSQLServerDialect.java rename hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/sched/{SchedulerServiceImplIT.java => SchedulerServiceImplTest.java} (97%) delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CreateBinaryDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CreateDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/FormatParameterDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/MetadataConformanceDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/PatchDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ReadDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchPostDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchSortDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithIncludesDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithServerAddressStrategyDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerExceptionDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/UnclassifiedServerExceptionDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/UpdateDstu2_1Test.java delete mode 100644 hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu2_1Test.java rename hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/{ResponseHighlightingInterceptorTest.java => ResponseHighlighterInterceptorTest.java} (89%) create mode 100644 hapi-fhir-structures-r4/src/test/resources/junit-platform.properties create mode 100644 hapi-fhir-test-utilities/src/main/java/ca/uhn/fhir/test/utilities/server/RequestCaptureServlet.java create mode 100644 hapi-tinder-plugin/src/main/java/ca/uhn/fhir/tinder/ddl/DdlGeneratorHibernate61.java create mode 100644 hapi-tinder-plugin/src/main/java/ca/uhn/fhir/tinder/ddl/GenerateDdlMojo.java diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java index b901097f2db..7881deef30b 100644 --- a/.mvn/wrapper/MavenWrapperDownloader.java +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -13,9 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.Authenticator; +import java.net.PasswordAuthentication; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; import java.util.Properties; public class MavenWrapperDownloader { diff --git a/hapi-deployable-pom/pom.xml b/hapi-deployable-pom/pom.xml index 7828ab2b979..09f8ce921e9 100644 --- a/hapi-deployable-pom/pom.xml +++ b/hapi-deployable-pom/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../pom.xml @@ -45,7 +45,6 @@ false false false - false true true 2 @@ -103,14 +102,6 @@ net.bytebuddy byte-buddy - - javax.xml.bind - jaxb-api - - - com.sun.xml.bind - jaxb-impl - .*\.txt$ diff --git a/hapi-fhir-android/pom.xml b/hapi-fhir-android/pom.xml index c80236908a1..32004a48b33 100644 --- a/hapi-fhir-android/pom.xml +++ b/hapi-fhir-android/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -131,12 +131,6 @@ org.jacoco jacoco-maven-plugin - - ${basedir}/target/classes - - - ${basedir}/src/main/java - true diff --git a/hapi-fhir-base/pom.xml b/hapi-fhir-base/pom.xml index ddb95cf5e41..7b126077940 100644 --- a/hapi-fhir-base/pom.xml +++ b/hapi-fhir-base/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -52,19 +52,13 @@ - com.helger - ph-schematron + com.helger.schematron + ph-schematron-api true - - - org.glassfish.jaxb - jaxb-core - - - com.helger - ph-commons + com.helger.schematron + ph-schematron-xslt true @@ -221,7 +215,6 @@ org.apache.maven.plugins maven-checkstyle-plugin - ${maven_checkstyle_version} ${maven.multiModuleProjectDirectory}/hapi-fhir-checkstyle/src/checkstyle/hapi-base-checkstyle.xml diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/support/LookupCodeRequest.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/support/LookupCodeRequest.java index dc7074bba25..8c3bdcaa640 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/support/LookupCodeRequest.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/support/LookupCodeRequest.java @@ -1,3 +1,22 @@ +/*- + * #%L + * HAPI FHIR - Core Library + * %% + * Copyright (C) 2014 - 2023 Smile CDR, Inc. + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ package ca.uhn.fhir.context.support; import java.util.Collection; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/interceptor/api/Pointcut.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/interceptor/api/Pointcut.java index 64b7267f63f..a87023924be 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/interceptor/api/Pointcut.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/interceptor/api/Pointcut.java @@ -158,10 +158,10 @@ public enum Pointcut implements IPointcut { * Hooks may accept the following parameters: *
    *
  • - * javax.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment + * jakarta.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment *
  • *
  • - * javax.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment + * jakarta.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment *
  • *
*

@@ -171,7 +171,7 @@ public enum Pointcut implements IPointcut { * no further processing will occur and no further interceptors will be called. */ SERVER_INCOMING_REQUEST_PRE_PROCESSED( - boolean.class, "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse"), + boolean.class, "jakarta.servlet.http.HttpServletRequest", "jakarta.servlet.http.HttpServletResponse"), /** * Server Hook: @@ -198,10 +198,10 @@ public enum Pointcut implements IPointcut { * only be populated when operating in a RestfulServer implementation. It is provided as a convenience. * *
  • - * javax.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment + * jakarta.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment *
  • *
  • - * javax.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment + * jakarta.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment *
  • *
  • * ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException - The exception that was thrown @@ -220,8 +220,8 @@ public enum Pointcut implements IPointcut { boolean.class, "ca.uhn.fhir.rest.api.server.RequestDetails", "ca.uhn.fhir.rest.server.servlet.ServletRequestDetails", - "javax.servlet.http.HttpServletRequest", - "javax.servlet.http.HttpServletResponse", + "jakarta.servlet.http.HttpServletRequest", + "jakarta.servlet.http.HttpServletResponse", "ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException"), /** @@ -244,10 +244,10 @@ public enum Pointcut implements IPointcut { * only be populated when operating in a RestfulServer implementation. It is provided as a convenience. *
  • *
  • - * javax.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment + * jakarta.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment *
  • *
  • - * javax.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment + * jakarta.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment *
  • * *

    @@ -268,8 +268,8 @@ public enum Pointcut implements IPointcut { boolean.class, "ca.uhn.fhir.rest.api.server.RequestDetails", "ca.uhn.fhir.rest.server.servlet.ServletRequestDetails", - "javax.servlet.http.HttpServletRequest", - "javax.servlet.http.HttpServletResponse"), + "jakarta.servlet.http.HttpServletRequest", + "jakarta.servlet.http.HttpServletResponse"), /** * Server Hook: @@ -291,10 +291,10 @@ public enum Pointcut implements IPointcut { * only be populated when operating in a RestfulServer implementation. It is provided as a convenience. * *

  • - * javax.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment + * jakarta.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment *
  • *
  • - * javax.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment + * jakarta.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment *
  • * *

    @@ -313,8 +313,8 @@ public enum Pointcut implements IPointcut { boolean.class, "ca.uhn.fhir.rest.api.server.RequestDetails", "ca.uhn.fhir.rest.server.servlet.ServletRequestDetails", - "javax.servlet.http.HttpServletRequest", - "javax.servlet.http.HttpServletResponse"), + "jakarta.servlet.http.HttpServletRequest", + "jakarta.servlet.http.HttpServletResponse"), /** * Server Hook: @@ -416,10 +416,10 @@ public enum Pointcut implements IPointcut { * {@link NullPointerException} in the case of a bug being triggered. * *

  • - * javax.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment + * jakarta.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment *
  • *
  • - * javax.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment + * jakarta.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment *
  • * *

    @@ -434,8 +434,8 @@ public enum Pointcut implements IPointcut { "ca.uhn.fhir.rest.api.server.RequestDetails", "ca.uhn.fhir.rest.server.servlet.ServletRequestDetails", "java.lang.Throwable", - "javax.servlet.http.HttpServletRequest", - "javax.servlet.http.HttpServletResponse"), + "jakarta.servlet.http.HttpServletRequest", + "jakarta.servlet.http.HttpServletResponse"), /** * Server Hook: @@ -463,10 +463,10 @@ public enum Pointcut implements IPointcut { * ca.uhn.fhir.rest.api.server.ResponseDetails - This object contains details about the response, including the contents. Hook methods may modify this object to change or replace the response. * *

  • - * javax.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment + * jakarta.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment *
  • *
  • - * javax.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment + * jakarta.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment *
  • * *

    @@ -487,8 +487,8 @@ public enum Pointcut implements IPointcut { "ca.uhn.fhir.rest.server.servlet.ServletRequestDetails", "org.hl7.fhir.instance.model.api.IBaseResource", "ca.uhn.fhir.rest.api.server.ResponseDetails", - "javax.servlet.http.HttpServletRequest", - "javax.servlet.http.HttpServletResponse"), + "jakarta.servlet.http.HttpServletRequest", + "jakarta.servlet.http.HttpServletResponse"), /** * Server Hook: @@ -554,10 +554,10 @@ public enum Pointcut implements IPointcut { * java.lang.String - The GraphQL response * *
  • - * javax.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment + * jakarta.servlet.http.HttpServletRequest - The servlet request, when running in a servlet environment *
  • *
  • - * javax.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment + * jakarta.servlet.http.HttpServletResponse - The servlet response, when running in a servlet environment *
  • * *

    @@ -578,8 +578,8 @@ public enum Pointcut implements IPointcut { "ca.uhn.fhir.rest.server.servlet.ServletRequestDetails", "java.lang.String", "java.lang.String", - "javax.servlet.http.HttpServletRequest", - "javax.servlet.http.HttpServletResponse"), + "jakarta.servlet.http.HttpServletRequest", + "jakarta.servlet.http.HttpServletResponse"), /** * Server Hook: diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseElement.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseElement.java index 0b877f2c434..6e675c3350f 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseElement.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseElement.java @@ -24,7 +24,11 @@ import ca.uhn.fhir.model.api.annotation.Description; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBaseDatatype; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public abstract class BaseElement implements /*IElement, */ ISupportsUndeclaredExtensions { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/IFhirVersion.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/IFhirVersion.java index f506a1f57aa..0532423b8ec 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/IFhirVersion.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/IFhirVersion.java @@ -19,10 +19,15 @@ */ package ca.uhn.fhir.model.api; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.context.FhirVersionEnum; +import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.fhirpath.IFhirPath; import ca.uhn.fhir.rest.api.IVersionSpecificBundleFactory; -import org.hl7.fhir.instance.model.api.*; +import org.hl7.fhir.instance.model.api.IBase; +import org.hl7.fhir.instance.model.api.IBaseResource; +import org.hl7.fhir.instance.model.api.IIdType; +import org.hl7.fhir.instance.model.api.IPrimitiveType; import java.io.InputStream; import java.util.Date; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/narrative2/NarrativeTemplateManifest.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/narrative2/NarrativeTemplateManifest.java index 8152d66f19c..b8cb84adc4b 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/narrative2/NarrativeTemplateManifest.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/narrative2/NarrativeTemplateManifest.java @@ -41,9 +41,18 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; import java.util.function.Consumer; import java.util.stream.Collectors; -import java.util.*; import javax.annotation.Nonnull; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Operation.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Operation.java index 83907544fc5..69a521a77ec 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Operation.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Operation.java @@ -118,7 +118,7 @@ public @interface Operation { * always the right choice), the framework will not attempt to generate a response to * this method. *

    - * This is useful if you want to include an {@link javax.servlet.http.HttpServletResponse} + * This is useful if you want to include an {@link jakarta.servlet.http.HttpServletResponse} * in your method parameters and create a response yourself directly from your * @Operation method. *

    @@ -134,7 +134,7 @@ public @interface Operation { * always the right choice), the framework will not attempt to parse the request body, * but will instead delegate it to the @Operation method. *

    - * This is useful if you want to include an {@link javax.servlet.http.HttpServletRequest} + * This is useful if you want to include an {@link jakarta.servlet.http.HttpServletRequest} * in your method parameters and parse the request yourself. *

    */ diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Read.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Read.java index 4276229f630..aedd0656b36 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Read.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Read.java @@ -23,7 +23,10 @@ import ca.uhn.fhir.rest.client.api.IBasicClient; import ca.uhn.fhir.rest.client.api.IRestfulClient; import org.hl7.fhir.instance.model.api.IBaseResource; -import java.lang.annotation.*; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; /** * RESTful method annotation to be used for the FHIR read and transaction method. diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/TransactionParam.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/TransactionParam.java index 8e50b13c9bb..51539b5d384 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/TransactionParam.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/TransactionParam.java @@ -19,7 +19,10 @@ */ package ca.uhn.fhir.rest.annotation; -import java.lang.annotation.*; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import java.util.List; /** diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Validate.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Validate.java index 7826df8daee..2ece6309e97 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Validate.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Validate.java @@ -22,7 +22,10 @@ package ca.uhn.fhir.rest.annotation; import ca.uhn.fhir.rest.api.ValidationModeEnum; import org.hl7.fhir.instance.model.api.IBaseResource; -import java.lang.annotation.*; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; /** * RESTful method annotation to be used for the FHIR diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenClientParam.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenClientParam.java index 2f8a91f22f4..d51b427f271 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenClientParam.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/TokenClientParam.java @@ -23,7 +23,9 @@ import ca.uhn.fhir.model.base.composite.BaseIdentifierDt; import org.apache.commons.lang3.ObjectUtils; import org.hl7.fhir.instance.model.api.IBaseCoding; -import java.util.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; import static org.apache.commons.lang3.StringUtils.defaultString; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParamPrefixEnum.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParamPrefixEnum.java index 3763c5292ae..56910ea563b 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParamPrefixEnum.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParamPrefixEnum.java @@ -19,7 +19,9 @@ */ package ca.uhn.fhir.rest.param; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; /** * Comparator/qualifier for values used in REST params, such as {@link DateParam}, {@link NumberParam}, and diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/AttachmentUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/AttachmentUtil.java index 9e7d82dd51d..cbb1adceb58 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/AttachmentUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/AttachmentUtil.java @@ -19,7 +19,11 @@ */ package ca.uhn.fhir.util; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.BaseRuntimeChildDefinition; +import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition; +import ca.uhn.fhir.context.BaseRuntimeElementDefinition; +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.context.FhirVersionEnum; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.ICompositeType; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/rdf/RDFUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/rdf/RDFUtil.java index c1678236b7d..3f4cdc49df6 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/rdf/RDFUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/rdf/RDFUtil.java @@ -24,7 +24,8 @@ import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.riot.Lang; import org.apache.jena.riot.RDFDataMgr; -import java.io.*; +import java.io.Reader; +import java.io.Writer; public class RDFUtil { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronBaseValidator.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronBaseValidator.java index 9355952873b..bd90fb8ca6a 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronBaseValidator.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronBaseValidator.java @@ -37,8 +37,8 @@ import com.helger.commons.io.resource.ClassPathResource; import com.helger.commons.io.resource.IReadableResource; import com.helger.schematron.ISchematronResource; import com.helger.schematron.SchematronHelper; +import com.helger.schematron.sch.SchematronResourceSCH; import com.helger.schematron.svrl.jaxb.SchematronOutputType; -import com.helger.schematron.xslt.SchematronResourceSCH; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.instance.model.api.IBaseResource; import org.slf4j.Logger; @@ -90,7 +90,12 @@ public class SchematronBaseValidator implements IValidatorModule { } StreamSource source = new StreamSource(new StringReader(resourceAsString)); - SchematronOutputType results = SchematronHelper.applySchematron(sch, source); + SchematronOutputType results; + try { + results = sch.applySchematronValidationToSVRL(source); + } catch (Exception e) { + throw new InternalErrorException(Msg.code(2433) + e.getMessage(), e); + } if (results == null) { return; } diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/i18n/HapiLocalizerTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/i18n/HapiLocalizerTest.java index 29857f00522..654d40aa675 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/i18n/HapiLocalizerTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/i18n/HapiLocalizerTest.java @@ -1,12 +1,14 @@ package ca.uhn.fhir.i18n; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; +import org.junit.jupiter.api.Test; import java.util.Set; -import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; public class HapiLocalizerTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/model/api/ResourceMetadataKeyEnumTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/model/api/ResourceMetadataKeyEnumTest.java index b0ec6d38352..70f56111cf9 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/model/api/ResourceMetadataKeyEnumTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/model/api/ResourceMetadataKeyEnumTest.java @@ -2,7 +2,8 @@ package ca.uhn.fhir.model.api; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; public class ResourceMetadataKeyEnumTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/model/api/TagTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/model/api/TagTest.java index ab747cf2923..2bfe43c07eb 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/model/api/TagTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/model/api/TagTest.java @@ -5,7 +5,10 @@ import org.junit.jupiter.api.Test; import java.net.URI; import java.net.URISyntaxException; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TagTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/CacheControlDirectiveTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/CacheControlDirectiveTest.java index 744e03b17bd..0d7991d85d8 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/CacheControlDirectiveTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/CacheControlDirectiveTest.java @@ -5,7 +5,9 @@ import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CacheControlDirectiveTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/EncodingEnumTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/EncodingEnumTest.java index b510b658f69..2e2a27e7cbe 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/EncodingEnumTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/EncodingEnumTest.java @@ -2,7 +2,7 @@ package ca.uhn.fhir.rest.api; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; public class EncodingEnumTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/MethodOutcomeTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/MethodOutcomeTest.java index 89a29b045da..5049c53ebc0 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/MethodOutcomeTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/api/MethodOutcomeTest.java @@ -7,7 +7,8 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Optional; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; class MethodOutcomeTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/DateParamTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/DateParamTest.java index e1b13e4f6c2..1e89acc623c 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/DateParamTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/DateParamTest.java @@ -17,7 +17,9 @@ import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.startsWith; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; public class DateParamTest { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(DateParamTest.class); diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/QualifierDetailsTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/QualifierDetailsTest.java index 33eb930e129..f844bdb9dca 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/QualifierDetailsTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/QualifierDetailsTest.java @@ -3,7 +3,8 @@ package ca.uhn.fhir.rest.param; import com.google.common.collect.Sets; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class QualifierDetailsTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/StringParamTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/StringParamTest.java index 064443fcf5e..3b6f7609537 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/StringParamTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/param/StringParamTest.java @@ -1,14 +1,11 @@ package ca.uhn.fhir.rest.param; -import static ca.uhn.fhir.rest.api.Constants.PARAMQUALIFIER_STRING_TEXT; -import static org.junit.jupiter.api.Assertions.*; - import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.api.IQueryParameterType; import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; -import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; @@ -18,12 +15,17 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import ch.qos.logback.classic.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.stream.Collectors; +import static ca.uhn.fhir.rest.api.Constants.PARAMQUALIFIER_STRING_TEXT; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + @ExtendWith(MockitoExtension.class) public class StringParamTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/server/exceptions/BaseServerResponseExceptionTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/server/exceptions/BaseServerResponseExceptionTest.java index 78d38818858..ee0167d79ab 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/server/exceptions/BaseServerResponseExceptionTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/rest/server/exceptions/BaseServerResponseExceptionTest.java @@ -2,7 +2,7 @@ package ca.uhn.fhir.rest.server.exceptions; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertTrue; public class BaseServerResponseExceptionTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/DateRangeUtilTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/DateRangeUtilTest.java index cce99a49e8b..fc75a7dff89 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/DateRangeUtilTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/DateRangeUtilTest.java @@ -5,7 +5,6 @@ import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.param.ParamPrefixEnum; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -19,7 +18,9 @@ import static ca.uhn.fhir.rest.param.ParamPrefixEnum.GREATERTHAN_OR_EQUALS; import static ca.uhn.fhir.rest.param.ParamPrefixEnum.LESSTHAN; import static ca.uhn.fhir.rest.param.ParamPrefixEnum.LESSTHAN_OR_EQUALS; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; class DateRangeUtilTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/LogUtilTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/LogUtilTest.java index 1f8fa0c6578..a1f566f436c 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/LogUtilTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/LogUtilTest.java @@ -5,7 +5,11 @@ import org.slf4j.Logger; import org.slf4j.event.Level; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; public class LogUtilTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/ReflectionUtilTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/ReflectionUtilTest.java index 776f24109c8..9f5dbd46357 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/ReflectionUtilTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/ReflectionUtilTest.java @@ -1,15 +1,17 @@ package ca.uhn.fhir.util; -import static org.junit.jupiter.api.Assertions.*; +import ca.uhn.fhir.context.ConfigurationException; +import ca.uhn.fhir.i18n.Msg; +import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; -import ca.uhn.fhir.i18n.Msg; -import org.junit.jupiter.api.Test; - -import ca.uhn.fhir.context.ConfigurationException; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class ReflectionUtilTest { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/validation/ResultSeverityEnumTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/validation/ResultSeverityEnumTest.java index 860c6367a6a..bc689c55259 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/validation/ResultSeverityEnumTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/validation/ResultSeverityEnumTest.java @@ -1,9 +1,9 @@ package ca.uhn.fhir.validation; -import static org.junit.jupiter.api.Assertions.*; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class ResultSeverityEnumTest { @Test diff --git a/hapi-fhir-bom/pom.xml b/hapi-fhir-bom/pom.xml index 80805431db2..e70d734aa84 100644 --- a/hapi-fhir-bom/pom.xml +++ b/hapi-fhir-bom/pom.xml @@ -4,7 +4,7 @@ 4.0.0 ca.uhn.hapi.fhir hapi-fhir-bom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT pom HAPI FHIR BOM @@ -12,7 +12,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-checkstyle/pom.xml b/hapi-fhir-checkstyle/pom.xml index 75efb8b7607..a1e8d7553cd 100644 --- a/hapi-fhir-checkstyle/pom.xml +++ b/hapi-fhir-checkstyle/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../pom.xml @@ -42,7 +42,6 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.2.0 com.puppycrawl.tools @@ -109,7 +108,6 @@ org.apache.maven.plugins maven-checkstyle-plugin - ${maven_checkstyle_version} **/osgi/**/*, **/.mvn/**/*, **/.mvn_/**/* diff --git a/hapi-fhir-checkstyle/src/checkstyle/hapi-base-checkstyle.xml b/hapi-fhir-checkstyle/src/checkstyle/hapi-base-checkstyle.xml index 5ff02a4549d..620676e3c80 100644 --- a/hapi-fhir-checkstyle/src/checkstyle/hapi-base-checkstyle.xml +++ b/hapi-fhir-checkstyle/src/checkstyle/hapi-base-checkstyle.xml @@ -18,6 +18,13 @@ + + + diff --git a/hapi-fhir-cli/hapi-fhir-cli-api/pom.xml b/hapi-fhir-cli/hapi-fhir-cli-api/pom.xml index 953d36a6f18..3126cd0baf1 100644 --- a/hapi-fhir-cli/hapi-fhir-cli-api/pom.xml +++ b/hapi-fhir-cli/hapi-fhir-cli-api/pom.xml @@ -4,7 +4,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../../hapi-deployable-pom/pom.xml @@ -152,38 +152,25 @@ spring-web + - org.eclipse.jetty - jetty-servlets + org.eclipse.jetty.ee10.websocket + jetty-ee10-websocket-jakarta-client - org.eclipse.jetty - jetty-servlet + jakarta.websocket + jakarta.websocket-client-api org.eclipse.jetty jetty-server - org.eclipse.jetty - jetty-util - - - org.eclipse.jetty - jetty-webapp - - - org.eclipse.jetty.websocket - websocket-jetty-api - - - org.eclipse.jetty.websocket - websocket-core-client - - - org.eclipse.jetty.websocket - websocket-jetty-client + org.eclipse.jetty.ee10 + jetty-ee10-servlet + + org.slf4j jcl-over-slf4j @@ -195,39 +182,17 @@ org.thymeleaf - thymeleaf-spring5 + thymeleaf-spring6 - com.helger - ph-schematron - - - org.glassfish.jaxb - jaxb-runtime - - - org.glassfish.jaxb - jaxb-core - - - com.sun.istack - istack-commons-runtime - - + com.helger.schematron + ph-schematron-api - com.helger - ph-commons - - - javax.xml.bind - jaxb-api - - - org.glassfish.jaxb - jaxb-runtime + com.helger.schematron + ph-schematron-xslt @@ -272,6 +237,15 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + none + false + 1 + + diff --git a/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/BulkImportCommand.java b/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/BulkImportCommand.java index 8794891e7f3..3b8868eeaa9 100644 --- a/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/BulkImportCommand.java +++ b/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/BulkImportCommand.java @@ -40,11 +40,12 @@ import org.apache.commons.io.file.PathUtils; import org.apache.commons.io.filefilter.FileFileFilter; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; +import org.apache.commons.lang3.time.DateUtils; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseParameters; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -234,7 +235,12 @@ public class BulkImportCommand extends BaseCommand { private List startServer(int thePort, List files) { List indexes = new ArrayList<>(); - myServer = new Server(thePort); + + myServer = new Server(); + ServerConnector connector = new ServerConnector(myServer); + connector.setIdleTimeout(DateUtils.MILLIS_PER_MINUTE); + connector.setPort(myPort); + myServer.setConnectors(new Connector[] {connector}); myServlet = new BulkImportFileServlet(); for (File t : files) { diff --git a/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/ReindexTerminologyCommand.java b/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/ReindexTerminologyCommand.java index 36524c393da..f5ea9c1f8dd 100644 --- a/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/ReindexTerminologyCommand.java +++ b/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/ReindexTerminologyCommand.java @@ -24,7 +24,6 @@ import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.util.ParametersUtil; -import joptsimple.internal.Strings; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.ParseException; import org.hl7.fhir.instance.model.api.IBaseParameters; @@ -111,7 +110,7 @@ public class ReindexTerminologyCommand extends BaseRequestGeneratingCommand { @Nonnull private String getResponseMessage(IBaseParameters response) { List message = ParametersUtil.getNamedParameterValuesAsString(myFhirCtx, response, "message"); - return Strings.join(message, NL); + return String.join(NL, message); } public static final String NL = System.getProperty("line.separator"); diff --git a/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/WebsocketSubscribeCommand.java b/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/WebsocketSubscribeCommand.java index 8ec137c69b7..1a13173f9f3 100644 --- a/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/WebsocketSubscribeCommand.java +++ b/hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/WebsocketSubscribeCommand.java @@ -21,19 +21,17 @@ package ca.uhn.fhir.cli; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.model.primitive.IdDt; +import jakarta.websocket.ClientEndpoint; +import jakarta.websocket.ContainerProvider; +import jakarta.websocket.OnClose; +import jakarta.websocket.OnError; +import jakarta.websocket.OnMessage; +import jakarta.websocket.OnOpen; +import jakarta.websocket.Session; +import jakarta.websocket.WebSocketContainer; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; -import org.eclipse.jetty.websocket.api.Frame; -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketFrame; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; -import org.eclipse.jetty.websocket.api.annotations.WebSocket; -import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; -import org.eclipse.jetty.websocket.client.WebSocketClient; import java.net.URI; @@ -46,6 +44,7 @@ public class WebsocketSubscribeCommand extends BaseCommand { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(WebsocketSubscribeCommand.class); private boolean myQuit; + private Session mySession; @Override public String getCommandDescription() { @@ -75,14 +74,13 @@ public class WebsocketSubscribeCommand extends BaseCommand { IdDt subsId = new IdDt(theCommandLine.getOptionValue("i")); - WebSocketClient client = new WebSocketClient(); SimpleEchoSocket socket = new SimpleEchoSocket(subsId.getIdPart()); try { - client.start(); URI echoUri = new URI(target); - ClientUpgradeRequest request = new ClientUpgradeRequest(); ourLog.info("Connecting to : {}", echoUri); - client.connect(socket, echoUri, request); + + WebSocketContainer container = ContainerProvider.getWebSocketContainer(); + mySession = container.connectToServer(socket, echoUri); while (!myQuit) { Thread.sleep(500L); @@ -93,7 +91,9 @@ public class WebsocketSubscribeCommand extends BaseCommand { throw new CommandFailureException(Msg.code(1537) + e); } finally { try { - client.stop(); + if (mySession != null) { + mySession.close(); + } } catch (Exception e) { ourLog.error("Failure", e); } @@ -103,7 +103,7 @@ public class WebsocketSubscribeCommand extends BaseCommand { /** * Basic Echo Client Socket */ - @WebSocket(maxTextMessageSize = 64 * 1024) + @ClientEndpoint public class SimpleEchoSocket { private String mySubsId; @@ -115,37 +115,32 @@ public class WebsocketSubscribeCommand extends BaseCommand { mySubsId = theSubsId; } - @OnWebSocketClose + @OnClose public void onClose(int statusCode, String reason) { ourLog.info("Received CLOSE status={} reason={}", statusCode, reason); } - @OnWebSocketConnect + @OnOpen public void onConnect(Session theSession) { ourLog.info("Successfully connected"); this.session = theSession; try { String sending = "bind " + mySubsId; LOG_SEND.info("{}", sending); - theSession.getRemote().sendString(sending); + theSession.getBasicRemote().sendText(sending); } catch (Throwable t) { ourLog.error("Failure", t); myQuit = true; } } - @OnWebSocketError + @OnError public void onError(Throwable theError) { ourLog.error("Websocket error: ", theError); myQuit = true; } - @OnWebSocketFrame - public void onFrame(Frame theFrame) { - ourLog.debug("Websocket frame: {}", theFrame); - } - - @OnWebSocketMessage + @OnMessage public void onMessage(String theMsg) { LOG_RECV.info("{}", theMsg); } diff --git a/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/BulkImportCommandIT.java b/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/BulkImportCommandTest.java similarity index 94% rename from hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/BulkImportCommandIT.java rename to hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/BulkImportCommandTest.java index c7f4369faef..db1ea7036ab 100644 --- a/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/BulkImportCommandIT.java +++ b/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/BulkImportCommandTest.java @@ -54,9 +54,9 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -public class BulkImportCommandIT { +public class BulkImportCommandTest { - private static final Logger ourLog = LoggerFactory.getLogger(BulkImportCommandIT.class); + private static final Logger ourLog = LoggerFactory.getLogger(BulkImportCommandTest.class); static { HapiSystemProperties.enableTestMode(); @@ -64,7 +64,7 @@ public class BulkImportCommandIT { @RegisterExtension public HttpClientExtension myHttpClientExtension = new HttpClientExtension(); - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) private IJobCoordinator myJobCoordinator; private final BulkDataImportProvider myProvider = new BulkDataImportProvider(); private final FhirContext myCtx = FhirContext.forR4Cached(); @@ -101,19 +101,12 @@ public class BulkImportCommandIT { @Test public void testBulkImport() throws IOException { - JobInstance jobInfo = new JobInstance() - .setStatus(StatusEnum.COMPLETED) - .setCreateTime(parseDate("2022-01-01T12:00:00-04:00")) - .setStartTime(parseDate("2022-01-01T12:10:00-04:00")); - - when(myJobCoordinator.getInstance(eq("THE-JOB-ID"))).thenReturn(jobInfo); - String fileContents1 = "{\"resourceType\":\"Observation\"}\n{\"resourceType\":\"Observation\"}"; String fileContents2 = "{\"resourceType\":\"Patient\"}\n{\"resourceType\":\"Patient\"}"; writeNdJsonFileToTempDirectory(fileContents1, "file1.json"); writeNdJsonFileToTempDirectory(fileContents2, "file2.json"); - when(myJobCoordinator.startInstance(any())).thenReturn(createJobStartResponse("THE-JOB-ID")); + when(myJobCoordinator.startInstance(any(), any())).thenReturn(createJobStartResponse("THE-JOB-ID")); // Start the command in a separate thread new Thread(() -> App.main(new String[]{ @@ -154,7 +147,7 @@ public class BulkImportCommandIT { writeNdJsonFileToTempDirectory(fileContents1, "file1.json.gz"); writeNdJsonFileToTempDirectory(fileContents2, "file2.json.gz"); - when(myJobCoordinator.startInstance(any())) + when(myJobCoordinator.startInstance(any(), any())) .thenReturn(createJobStartResponse("THE-JOB-ID")); // Start the command in a separate thread @@ -196,7 +189,7 @@ public class BulkImportCommandIT { writeNdJsonFileToTempDirectory(fileContents1, "file1.json"); writeNdJsonFileToTempDirectory(fileContents2, "file2.json"); - when(myJobCoordinator.startInstance(any())).thenReturn(createJobStartResponse("THE-JOB-ID")); + when(myJobCoordinator.startInstance(any(), any())).thenReturn(createJobStartResponse("THE-JOB-ID")); // Start the command in a separate thread new Thread(() -> App.main(new String[]{ diff --git a/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HapiClearMigrationLockCommandTest.java b/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HapiClearMigrationLockCommandTest.java index 635ce997c65..d6cd7dc01dd 100644 --- a/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HapiClearMigrationLockCommandTest.java +++ b/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HapiClearMigrationLockCommandTest.java @@ -21,14 +21,19 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.UUID; import static ca.uhn.fhir.jpa.migrate.HapiMigrationLock.LOCK_PID; import static ca.uhn.fhir.jpa.migrate.HapiMigrationStorageSvc.LOCK_TYPE; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import static org.slf4j.LoggerFactory.getLogger; public class HapiClearMigrationLockCommandTest extends ConsoleOutputCapturingBaseTest { diff --git a/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HapiFlywayMigrateDatabaseCommandTest.java b/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HapiFlywayMigrateDatabaseCommandTest.java index 31b74d0b5ab..7c9601db73f 100644 --- a/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HapiFlywayMigrateDatabaseCommandTest.java +++ b/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HapiFlywayMigrateDatabaseCommandTest.java @@ -258,8 +258,9 @@ public class HapiFlywayMigrateDatabaseCommandTest { private File getLocation(String theDatabaseName) throws IOException { File directory = new File(myDbDirectory); if (directory.exists()) { - FileUtils.deleteDirectory(directory); + FileUtils.forceDelete(directory); } + assertFalse(directory.exists()); return new File(myDbDirectory + "/" + theDatabaseName); } diff --git a/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HeaderPassthroughOptionTest.java b/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HeaderPassthroughOptionTest.java index 38cbd22c317..cc79a07c4a0 100644 --- a/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HeaderPassthroughOptionTest.java +++ b/hapi-fhir-cli/hapi-fhir-cli-api/src/test/java/ca/uhn/fhir/cli/HeaderPassthroughOptionTest.java @@ -8,16 +8,19 @@ import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.interceptor.CapturingInterceptor; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.HttpServletExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.ParseException; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.IdType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; @@ -46,33 +49,29 @@ public class HeaderPassthroughOptionTest { private static final Logger ourLog = LoggerFactory.getLogger(HeaderPassthroughOptionTest.class); final String FHIR_VERSION = "r4"; - private FhirContext myCtx = FhirContext.forR4(); - private Server myServer; - private int myPort; + private final FhirContext myCtx = FhirContext.forR4Cached(); private final String headerKey1 = "test-header-key-1"; private final String headerValue1 = "test header value-1"; private static final String ourConceptsFileName = "target/concepts.csv"; private static final String ourHierarchyFileName = "target/hierarchy.csv"; + private static final AtomicInteger ourFilenameCounter = new AtomicInteger(); private final CapturingInterceptor myCapturingInterceptor = new CapturingInterceptor(); private final UploadTerminologyCommand testedCommand = new RequestCapturingUploadTerminologyCommand(myCapturingInterceptor); + private final TerminologyUploaderProvider myProvider = new TerminologyUploaderProvider(); @Mock protected ITermLoaderSvc myTermLoaderSvc; - private static final AtomicInteger ourFilenameCounter = new AtomicInteger(); + + @RegisterExtension + public RestfulServerExtension myServer = new RestfulServerExtension(myCtx) + .registerProvider(myProvider); @BeforeEach - public void beforeEach() throws Exception { - myServer = new Server(0); - TerminologyUploaderProvider provider = new TerminologyUploaderProvider(myCtx, myTermLoaderSvc); - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(myCtx); - servlet.registerProvider(provider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - myServer.setHandler(proxyHandler); - JettyUtil.startServer(myServer); - myPort = JettyUtil.getPortForStartedServer(myServer); + public void beforeEach() { + myProvider.setContext(myCtx); + myProvider.setTerminologyLoaderSvc(myTermLoaderSvc); + when(myTermLoaderSvc.loadCustom(eq("http://foo"), anyList(), any())) .thenReturn(new UploadStatistics(100, new IdType("CodeSystem/101"))); } @@ -85,7 +84,7 @@ public class HeaderPassthroughOptionTest { String[] args = new String[]{ "-v", FHIR_VERSION, "-m", "SNAPSHOT", - "-t", "http://localhost:" + myPort, + "-t", myServer.getBaseUrl(), "-u", "http://foo", "-d", getConceptFilename(filenameCounter), "-d", getHierarchyFilename(filenameCounter), @@ -115,7 +114,7 @@ public class HeaderPassthroughOptionTest { String[] args = new String[]{ "-v", FHIR_VERSION, "-m", "SNAPSHOT", - "-t", "http://localhost:" + myPort, + "-t", myServer.getBaseUrl(), "-u", "http://foo", "-d", getConceptFilename(filenameCounter), "-d", getHierarchyFilename(filenameCounter), @@ -149,7 +148,7 @@ public class HeaderPassthroughOptionTest { String[] args = new String[]{ "-v", FHIR_VERSION, "-m", "SNAPSHOT", - "-t", "http://localhost:" + myPort, + "-t", myServer.getBaseUrl(), "-u", "http://foo", "-d", getConceptFilename(filenameCounter), "-d", getHierarchyFilename(filenameCounter), diff --git a/hapi-fhir-cli/hapi-fhir-cli-app/pom.xml b/hapi-fhir-cli/hapi-fhir-cli-app/pom.xml index dd37903542f..ec740677b09 100644 --- a/hapi-fhir-cli/hapi-fhir-cli-app/pom.xml +++ b/hapi-fhir-cli/hapi-fhir-cli-app/pom.xml @@ -6,7 +6,7 @@ ca.uhn.hapi.fhir hapi-fhir-cli - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../pom.xml diff --git a/hapi-fhir-cli/pom.xml b/hapi-fhir-cli/pom.xml index b2fe5bc90b3..19562217626 100644 --- a/hapi-fhir-cli/pom.xml +++ b/hapi-fhir-cli/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../pom.xml diff --git a/hapi-fhir-client-okhttp/pom.xml b/hapi-fhir-client-okhttp/pom.xml index 70061eae755..70ac8a73a06 100644 --- a/hapi-fhir-client-okhttp/pom.xml +++ b/hapi-fhir-client-okhttp/pom.xml @@ -4,7 +4,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -81,11 +81,6 @@ jetty-server test - - org.eclipse.jetty - jetty-servlet - test - org.jboss.resteasy resteasy-client diff --git a/hapi-fhir-client-okhttp/src/test/java/ca/uhn/fhir/okhttp/GenericOkHttpClientDstu2Test.java b/hapi-fhir-client-okhttp/src/test/java/ca/uhn/fhir/okhttp/GenericOkHttpClientDstu2Test.java index 1969b94293d..0c38e94d735 100644 --- a/hapi-fhir-client-okhttp/src/test/java/ca/uhn/fhir/okhttp/GenericOkHttpClientDstu2Test.java +++ b/hapi-fhir-client-okhttp/src/test/java/ca/uhn/fhir/okhttp/GenericOkHttpClientDstu2Test.java @@ -28,39 +28,27 @@ import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.PreferReturnEnum; import ca.uhn.fhir.rest.api.SearchStyleEnum; import ca.uhn.fhir.rest.api.SummaryEnum; -import ca.uhn.fhir.rest.client.api.Header; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; import ca.uhn.fhir.rest.client.exceptions.InvalidResponseException; import ca.uhn.fhir.rest.client.impl.RestfulClientFactory; import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; import ca.uhn.fhir.rest.param.DateRangeParam; -import ca.uhn.fhir.test.utilities.JettyUtil; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import org.apache.commons.io.Charsets; +import ca.uhn.fhir.test.utilities.server.HttpServletExtension; +import ca.uhn.fhir.test.utilities.server.RequestCaptureServlet; import org.apache.commons.io.IOUtils; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.instance.model.api.IBaseOperationOutcome; import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.extension.RegisterExtension; + import java.io.IOException; import java.util.Date; -import java.util.Enumeration; import java.util.List; -import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -76,23 +64,14 @@ import static org.junit.jupiter.api.Assertions.fail; public class GenericOkHttpClientDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(GenericOkHttpClientDstu2Test.class); - private static FhirContext ourCtx; - private static int ourPort; - private static Server ourServer; - private static int ourResponseCount = 0; - private static String[] ourResponseBodies; - private static String ourResponseBody; - private static String ourResponseContentType; - private static int ourResponseStatus; - private static String ourRequestUri; - private static List ourRequestUriAll; - private static String ourRequestMethod; - private static String ourRequestContentType; - private static byte[] ourRequestBodyBytes; - private static String ourRequestBodyString; - private static ArrayListMultimap ourRequestHeaders; - private static List> ourRequestHeadersAll; - private static Map ourRequestFirstHeaders; + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); + + private static final RequestCaptureServlet MY_SERVLET = new RequestCaptureServlet(); + + @RegisterExtension + public static final HttpServletExtension ourServer = new HttpServletExtension() + .withServlet(MY_SERVLET) + .keepAliveBetweenTests(); /** * This suite of tests can be reconfigured to test a different RestfulClientFactory implementation by @@ -115,9 +94,10 @@ public class GenericOkHttpClientDstu2Test { clientFactory.setServerValidationMode(ServerValidationModeEnum.NEVER); ourCtx.setRestfulClientFactory(clientFactory); - ourResponseCount = 0; + MY_SERVLET.reset(); } + @Test public void testProviderWhereWeForgotToSetTheContext() throws Exception { RestfulClientFactory clientFactory = createNewClientFactoryForTesting(null); @@ -126,7 +106,7 @@ public class GenericOkHttpClientDstu2Test { ourCtx.setRestfulClientFactory(clientFactory); try { - ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); fail(); } catch (IllegalStateException e) { String factoryClassName = clientFactory.getClass().getSimpleName(); @@ -163,25 +143,25 @@ public class GenericOkHttpClientDstu2Test { conf.setCopyright("COPY"); final String respString = p.encodeResourceToString(conf); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.fetchConformance().ofType(Conformance.class).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata", ourRequestUri); - assertEquals(1, ourRequestHeaders.get("Accept").size()); - assertThat(ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata", MY_SERVLET.ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); client.fetchConformance().ofType(Conformance.class).encodedJson().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata?_format=json", ourRequestUri); - assertEquals(1, ourRequestHeaders.get("Accept").size()); - assertThat(ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata?_format=json", MY_SERVLET.ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); client.fetchConformance().ofType(Conformance.class).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata?_format=xml", ourRequestUri); - assertEquals(1, ourRequestHeaders.get("Accept").size()); - assertThat(ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata?_format=xml", MY_SERVLET.ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); } @Test @@ -194,24 +174,24 @@ public class GenericOkHttpClientDstu2Test { final Patient patient = new Patient(); patient.addName().addFamily("FAMILY"); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient resp = client.read(Patient.class, new IdDt("123")); assertEquals("FAMILY", resp.getName().get(0).getFamily().get(0).getValue()); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata", ourRequestUriAll.get(0)); - assertEquals(1, ourRequestHeadersAll.get(0).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUriAll.get(1)); - assertEquals(1, ourRequestHeadersAll.get(1).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata", MY_SERVLET.ourRequestUriAll.get(0)); + assertEquals(1, MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", MY_SERVLET.ourRequestUriAll.get(1)); + assertEquals(1, MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); } @Test @@ -224,23 +204,23 @@ public class GenericOkHttpClientDstu2Test { final Patient patient = new Patient(); patient.addName().addFamily("FAMILY"); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.setEncoding(EncodingEnum.JSON); Patient resp = client.read(Patient.class, new IdDt("123")); assertEquals("FAMILY", resp.getName().get(0).getFamily().get(0).getValue()); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata?_format=json", ourRequestUriAll.get(0)); - assertEquals(1, ourRequestHeadersAll.get(0).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_format=json", ourRequestUriAll.get(1)); - assertEquals(1, ourRequestHeadersAll.get(1).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata?_format=json", MY_SERVLET.ourRequestUriAll.get(0)); + assertEquals(1, MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_format=json", MY_SERVLET.ourRequestUriAll.get(1)); + assertEquals(1, MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); } @Test @@ -253,78 +233,78 @@ public class GenericOkHttpClientDstu2Test { final String respString = p.encodeResourceToString(conf); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Conformance resp = (Conformance) client.capabilities().ofType(Conformance.class).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata", MY_SERVLET.ourRequestUri); assertEquals("COPY", resp.getCopyright()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); } @Test public void testCreate() throws Exception { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().addFamily("FOOFAMILY"); client.create().resource(p).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("POST", ourRequestMethod); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); p.setId("123"); client.create().resource(p).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - String body = ourRequestBodyString; + String body = MY_SERVLET.ourRequestBodyString; assertThat(body, containsString("")); assertThat(body, not(containsString("123"))); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("POST", ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); } @Test public void testCreateConditional() throws Exception { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().addFamily("FOOFAMILY"); client.create().resource(p).conditionalByUrl("Patient?name=foo").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); String expectedContentTypeHeader = EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8; assertContentTypeEquals(expectedContentTypeHeader); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", ourRequestMethod); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", MY_SERVLET.ourRequestMethod); client.create().resource(p).conditionalByUrl("Patient?name=http://foo|bar").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(expectedContentTypeHeader); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar", ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", ourRequestMethod); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar", MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", MY_SERVLET.ourRequestMethod); client.create().resource(p).conditional().where(Patient.NAME.matches().value("foo")).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(expectedContentTypeHeader); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", ourRequestMethod); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", MY_SERVLET.ourRequestMethod); } private void assertContentTypeEquals(String expectedContentTypeHeader) { @@ -335,20 +315,20 @@ public class GenericOkHttpClientDstu2Test { @Test public void testCreatePrefer() throws Exception { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().addFamily("FOOFAMILY"); client.create().resource(p).prefer(PreferReturnEnum.MINIMAL).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); client.create().resource(p).prefer(PreferReturnEnum.REPRESENTATION).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); } @Test @@ -357,11 +337,11 @@ public class GenericOkHttpClientDstu2Test { p.setId("123"); final String formatted = ourCtx.newXmlParser().encodeResourceToString(p); - ourResponseStatus = Constants.STATUS_HTTP_200_OK; - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = formatted; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_200_OK; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = formatted; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); p = new Patient(); p.setId(new IdDt("1")); @@ -374,33 +354,33 @@ public class GenericOkHttpClientDstu2Test { @Test public void testDeleteConditional() throws Exception { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.delete().resourceById(new IdDt("Patient/123")).execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUri); + assertEquals("DELETE", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", MY_SERVLET.ourRequestUri); client.delete().resourceConditionalByUrl("Patient?name=foo").execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertEquals("DELETE", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestUri); client.delete().resourceConditionalByType("Patient").where(Patient.NAME.matches().value("foo")).execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertEquals("DELETE", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestUri); } @SuppressWarnings("deprecation") @Test public void testDeleteNonFluent() throws Exception { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.delete().resourceById(new IdDt("Patient/123")).execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUri); + assertEquals("DELETE", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", MY_SERVLET.ourRequestUri); } @@ -408,10 +388,10 @@ public class GenericOkHttpClientDstu2Test { public void testHistory() throws Exception { final String msg = getPatientFeedWithOneResult(); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle response; @@ -421,7 +401,7 @@ public class GenericOkHttpClientDstu2Test { .andReturnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/_history", MY_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); response = client @@ -432,7 +412,7 @@ public class GenericOkHttpClientDstu2Test { .count(null) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/_history", MY_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); response = client @@ -442,7 +422,7 @@ public class GenericOkHttpClientDstu2Test { .since(new InstantDt()) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/_history", MY_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); response = client @@ -451,7 +431,7 @@ public class GenericOkHttpClientDstu2Test { .andReturnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/_history", MY_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); response = client @@ -460,7 +440,7 @@ public class GenericOkHttpClientDstu2Test { .andReturnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/_history", MY_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); response = client @@ -471,8 +451,8 @@ public class GenericOkHttpClientDstu2Test { .since(new InstantDt("2001-01-02T11:22:33Z")) .execute(); - assertThat(ourRequestUri, either(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123/_history?_since=2001-01-02T11:22:33Z&_count=123")) - .or(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123/_history?_count=123&_since=2001-01-02T11:22:33Z"))); + assertThat(MY_SERVLET.ourRequestUri, either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123/_history?_since=2001-01-02T11:22:33Z&_count=123")) + .or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123/_history?_count=123&_since=2001-01-02T11:22:33Z"))); assertEquals(1, response.getEntry().size()); response = client @@ -482,7 +462,7 @@ public class GenericOkHttpClientDstu2Test { .since(new InstantDt("2001-01-02T11:22:33Z").getValue()) .execute(); - assertThat(ourRequestUri, containsString("_since=2001-01")); + assertThat(MY_SERVLET.ourRequestUri, containsString("_since=2001-01")); assertEquals(1, response.getEntry().size()); } @@ -496,10 +476,10 @@ public class GenericOkHttpClientDstu2Test { outParams.addParameter().setName("meta").setValue(new MetaDt().addProfile("urn:profile:out")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); MetaDt resp = client .meta() @@ -509,11 +489,11 @@ public class GenericOkHttpClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$meta-add", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$meta-add", MY_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("POST", ourRequestMethod); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals("", - ourRequestBodyString); + MY_SERVLET.ourRequestBodyString); } @Test @@ -527,10 +507,10 @@ public class GenericOkHttpClientDstu2Test { outParams.addParameter().setName("meta").setValue(new MetaDt().addProfile("urn:profile:out")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); MetaDt resp = client .meta() @@ -538,9 +518,9 @@ public class GenericOkHttpClientDstu2Test { .fromServer() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$meta", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$meta", MY_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); resp = client .meta() @@ -548,9 +528,9 @@ public class GenericOkHttpClientDstu2Test { .fromType("Patient") .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$meta", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$meta", MY_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); resp = client .meta() @@ -558,9 +538,9 @@ public class GenericOkHttpClientDstu2Test { .fromResource(new IdDt("Patient/123")) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$meta", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$meta", MY_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); } @Test @@ -577,10 +557,10 @@ public class GenericOkHttpClientDstu2Test { outParams.addParameter().setValue(new StringDt("STRINGVALOUT2")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client .operation() @@ -590,9 +570,9 @@ public class GenericOkHttpClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -602,9 +582,9 @@ public class GenericOkHttpClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -614,9 +594,9 @@ public class GenericOkHttpClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -625,7 +605,7 @@ public class GenericOkHttpClientDstu2Test { .withParameters(inParams) .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", MY_SERVLET.ourRequestUri); } @Test @@ -637,10 +617,10 @@ public class GenericOkHttpClientDstu2Test { outParams.addParameter().setValue(new StringDt("STRINGVALOUT2")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client .operation() @@ -650,9 +630,9 @@ public class GenericOkHttpClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -662,9 +642,9 @@ public class GenericOkHttpClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -674,9 +654,9 @@ public class GenericOkHttpClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -685,17 +665,17 @@ public class GenericOkHttpClientDstu2Test { .withNoParameters(Parameters.class) .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); } @Test public void testOperationWithBundleResponseJson() throws Exception { - ourResponseContentType = Constants.CT_FHIR_JSON; - final String respString = "{\n" + " \"resourceType\":\"Bundle\",\n" + " \"id\":\"8cef5f2a-0ba9-43a5-be26-c8dde9ff0e19\",\n" + " \"base\":\"http://localhost:" + ourPort + "/fhir\"\n" + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON; + final String respString = "{\n" + " \"resourceType\":\"Bundle\",\n" + " \"id\":\"8cef5f2a-0ba9-43a5-be26-c8dde9ff0e19\",\n" + " \"base\":\"" + ourServer.getBaseUrl() + "/fhir\"\n" + "}"; - ourResponseBody = respString; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.registerInterceptor(new LoggingInterceptor(true)); @@ -731,10 +711,10 @@ public class GenericOkHttpClientDstu2Test { outParams.setTotal(123); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client .operation() @@ -742,11 +722,11 @@ public class GenericOkHttpClientDstu2Test { .named("$SOMEOPERATION") .withParameters(inParams).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals(1, resp.getParameter().size()); assertEquals(ca.uhn.fhir.model.dstu2.resource.Bundle.class, resp.getParameter().get(0).getResource().getClass()); } @@ -760,10 +740,10 @@ public class GenericOkHttpClientDstu2Test { outParams.addParameter().setValue(new StringDt("STRINGVALOUT2")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client .operation() @@ -774,14 +754,14 @@ public class GenericOkHttpClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertEquals("POST", ourRequestMethod); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals( "", - (ourRequestBodyString)); + (MY_SERVLET.ourRequestBodyString)); /* * Composite type @@ -796,14 +776,14 @@ public class GenericOkHttpClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertEquals("POST", ourRequestMethod); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals( "", - (ourRequestBodyString)); + (MY_SERVLET.ourRequestBodyString)); /* * Resource @@ -818,19 +798,19 @@ public class GenericOkHttpClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertEquals("POST", ourRequestMethod); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals( "", - (ourRequestBodyString)); + (MY_SERVLET.ourRequestBodyString)); } @Test public void testOperationWithInvalidParam() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); // Who knows what the heck this is! IBase weirdBase = new IBase() { @@ -887,10 +867,10 @@ public class GenericOkHttpClientDstu2Test { outParams.addParameter().setValue(new StringDt("STRINGVALOUT2")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client .operation() @@ -901,7 +881,7 @@ public class GenericOkHttpClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/1/$validate-code?code=8495-4&system=http%3A%2F%2Floinc.org", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/1/$validate-code?code=8495-4&system=http%3A%2F%2Floinc.org", MY_SERVLET.ourRequestUri); client .operation() @@ -912,11 +892,11 @@ public class GenericOkHttpClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/1/$validate-code", ourRequestUri); - ourLog.info(ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/1/$validate-code", MY_SERVLET.ourRequestUri); + ourLog.info(MY_SERVLET.ourRequestBodyString); assertEquals( "", - ourRequestBodyString); + MY_SERVLET.ourRequestBodyString); } @Test @@ -933,10 +913,10 @@ public class GenericOkHttpClientDstu2Test { outParams.addParameter().setValue(new StringDt("STRINGVALOUT2")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client .operation() @@ -944,12 +924,12 @@ public class GenericOkHttpClientDstu2Test { .named("$SOMEOPERATION") .withParameters(inParams).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -957,12 +937,12 @@ public class GenericOkHttpClientDstu2Test { .named("$SOMEOPERATION") .withParameters(inParams).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -970,16 +950,16 @@ public class GenericOkHttpClientDstu2Test { .named("$SOMEOPERATION") .withParameters(inParams).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); resp = client.operation().onInstance(new IdDt("http://foo.com/bar/baz/Patient/123/_history/22")).named("$SOMEOPERATION").withParameters(inParams).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); } @Test @@ -994,10 +974,10 @@ public class GenericOkHttpClientDstu2Test { outParams.addParameter().setValue(new StringDt("STRINGVALOUT2")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client .operation() @@ -1005,12 +985,12 @@ public class GenericOkHttpClientDstu2Test { .named("$SOMEOPERATION") .withNoParameters(Parameters.class).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -1018,12 +998,12 @@ public class GenericOkHttpClientDstu2Test { .named("$SOMEOPERATION") .withNoParameters(Parameters.class).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -1031,12 +1011,12 @@ public class GenericOkHttpClientDstu2Test { .named("$SOMEOPERATION") .withNoParameters(Parameters.class).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); resp = client .operation() @@ -1045,19 +1025,19 @@ public class GenericOkHttpClientDstu2Test { .withNoParameters(Parameters.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); } @Test public void testPageNext() throws Exception { - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = getPatientFeedWithOneResult(); + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = getPatientFeedWithOneResult(); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle(); - sourceBundle.getLinkOrCreate(IBaseBundle.LINK_PREV).setUrl("http://localhost:" + ourPort + "/fhir/prev"); - sourceBundle.getLinkOrCreate(IBaseBundle.LINK_NEXT).setUrl("http://localhost:" + ourPort + "/fhir/next"); + sourceBundle.getLinkOrCreate(IBaseBundle.LINK_PREV).setUrl(ourServer.getBaseUrl() + "/fhir/prev"); + sourceBundle.getLinkOrCreate(IBaseBundle.LINK_NEXT).setUrl(ourServer.getBaseUrl() + "/fhir/next"); ca.uhn.fhir.model.dstu2.resource.Bundle resp = client .loadPage() @@ -1065,12 +1045,12 @@ public class GenericOkHttpClientDstu2Test { .execute(); assertEquals(1, resp.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/fhir/next", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/next", MY_SERVLET.ourRequestUri); } @Test public void testPageNextNoLink() throws Exception { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle(); try { @@ -1082,13 +1062,13 @@ public class GenericOkHttpClientDstu2Test { @Test public void testPagePrev() throws Exception { - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = getPatientFeedWithOneResult(); + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = getPatientFeedWithOneResult(); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle(); - sourceBundle.getLinkOrCreate("previous").setUrl("http://localhost:" + ourPort + "/fhir/prev"); + sourceBundle.getLinkOrCreate("previous").setUrl(ourServer.getBaseUrl() + "/fhir/prev"); ca.uhn.fhir.model.dstu2.resource.Bundle resp = client .loadPage() @@ -1096,14 +1076,14 @@ public class GenericOkHttpClientDstu2Test { .execute(); assertEquals(1, resp.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/fhir/prev", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/prev", MY_SERVLET.ourRequestUri); /* * Try with "prev" instead of "previous" */ sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle(); - sourceBundle.getLinkOrCreate("prev").setUrl("http://localhost:" + ourPort + "/fhir/prev"); + sourceBundle.getLinkOrCreate("prev").setUrl(ourServer.getBaseUrl() + "/fhir/prev"); resp = client .loadPage() @@ -1111,7 +1091,7 @@ public class GenericOkHttpClientDstu2Test { .execute(); assertEquals(1, resp.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/fhir/prev", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/prev", MY_SERVLET.ourRequestUri); } @Test @@ -1120,15 +1100,15 @@ public class GenericOkHttpClientDstu2Test { patient.addName().addFamily("FAM"); final String respString = ourCtx.newXmlParser().encodeResourceToString(patient); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient response; - response = (Patient) client.read(new UriDt("http://localhost:" + ourPort + "/fhir/Patient/123")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUri); + response = (Patient) client.read(new UriDt(ourServer.getBaseUrl() + "/fhir/Patient/123")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", MY_SERVLET.ourRequestUri); assertEquals("FAM", response.getName().get(0).getFamily().get(0).getValue()); } @@ -1138,15 +1118,15 @@ public class GenericOkHttpClientDstu2Test { patient.addName().addFamily("FAM"); final String respString = ourCtx.newXmlParser().encodeResourceToString(patient); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient response; - response = (Patient) client.read().resource(Patient.class).withUrl(new IdDt("http://localhost:" + ourPort + "/AAA/Patient/123")).execute(); - assertEquals("http://localhost:" + ourPort + "/AAA/Patient/123", ourRequestUri); + response = (Patient) client.read().resource(Patient.class).withUrl(new IdDt(ourServer.getBaseUrl() + "/AAA/Patient/123")).execute(); + assertEquals(ourServer.getBaseUrl() + "/AAA/Patient/123", MY_SERVLET.ourRequestUri); assertEquals("FAM", response.getName().get(0).getFamily().get(0).getValue()); } @@ -1167,10 +1147,10 @@ public class GenericOkHttpClientDstu2Test { " \n" + ""; - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = input; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = input; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle response; @@ -1187,10 +1167,10 @@ public class GenericOkHttpClientDstu2Test { public void testReadWithElementsParam() throws Exception { String msg = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); IBaseResource response = client.read() .resource("Patient") @@ -1198,8 +1178,8 @@ public class GenericOkHttpClientDstu2Test { .elementsSubset("name", "identifier") .execute(); - assertThat(ourRequestUri, either(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123?_elements=name%2Cidentifier")) - .or(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123?_elements=identifier%2Cname"))); + assertThat(MY_SERVLET.ourRequestUri, either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123?_elements=name%2Cidentifier")) + .or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123?_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getClass()); } @@ -1207,10 +1187,10 @@ public class GenericOkHttpClientDstu2Test { public void testReadWithSummaryInvalid() throws Exception { String msg = "<>>>><<<<>"; - ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); try { client.read() @@ -1229,10 +1209,10 @@ public class GenericOkHttpClientDstu2Test { public void testReadWithSummaryParamHtml() throws Exception { String msg = "
    HELP IM A DIV
    "; - ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient response = client.read() .resource(Patient.class) @@ -1240,7 +1220,7 @@ public class GenericOkHttpClientDstu2Test { .summaryMode(SummaryEnum.TEXT) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_summary=text", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_summary=text", MY_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getClass()); assertEquals("
    HELP IM A DIV
    ", response.getText().getDiv().getValueAsString()); } @@ -1249,10 +1229,10 @@ public class GenericOkHttpClientDstu2Test { public void testSearchByString() throws Exception { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() .forResource("Patient") @@ -1260,7 +1240,7 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=james", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=james", MY_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1268,18 +1248,18 @@ public class GenericOkHttpClientDstu2Test { public void testSearchByUrl() throws Exception { final String msg = getPatientFeedWithOneResult(); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle response = client.search() - .byUrl("http://localhost:" + ourPort + "/AAA?name=http://foo|bar") + .byUrl(ourServer.getBaseUrl() + "/AAA?name=http://foo|bar") .encodedJson() .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/AAA?name=http%3A//foo%7Cbar&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/AAA?name=http%3A//foo%7Cbar&_format=json", MY_SERVLET.ourRequestUri); assertNotNull(response); response = client.search() @@ -1288,7 +1268,7 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", MY_SERVLET.ourRequestUri); assertNotNull(response); response = client.search() @@ -1297,7 +1277,7 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", MY_SERVLET.ourRequestUri); assertNotNull(response); response = client.search() @@ -1305,7 +1285,7 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); assertNotNull(response); response = client.search() @@ -1313,7 +1293,7 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); assertNotNull(response); try { @@ -1330,10 +1310,10 @@ public class GenericOkHttpClientDstu2Test { public void testSearchReturningDstu2Bundle() throws Exception { String msg = IOUtils.toString(GenericOkHttpClientDstu2Test.class.getResourceAsStream("/bundle_orion.xml")); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle response = client.search() .forResource("Observation") @@ -1355,10 +1335,10 @@ public class GenericOkHttpClientDstu2Test { public void testSearchWithElementsParam() throws Exception { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() .forResource("Patient") @@ -1367,8 +1347,8 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(Bundle.class) .execute(); - assertThat(ourRequestUri, either(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=name%2Cidentifier")) - .or(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); + assertThat(MY_SERVLET.ourRequestUri, either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=name%2Cidentifier")) + .or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1376,10 +1356,10 @@ public class GenericOkHttpClientDstu2Test { public void testSearchByPost() throws Exception { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() .forResource("Patient") @@ -1389,29 +1369,29 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/_search?_elements=identifier%2Cname", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/_search?_elements=identifier%2Cname", MY_SERVLET.ourRequestUri); - // assertThat(ourRequestUri, - // either(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://localhost:" + ourPort + + // assertThat(MY_SERVLET.ourRequestUri, + // either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo(ourServer.getBaseUrl() + // "/fhir/Patient?name=james&_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); - assertEquals("name=james", ourRequestBodyString); + assertEquals("name=james", MY_SERVLET.ourRequestBodyString); - assertEquals("application/x-www-form-urlencoded", ourRequestContentType.replace(";char", "; char").toLowerCase()); - assertEquals(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY, ourRequestFirstHeaders.get("Accept").getValue()); - assertThat(ourRequestFirstHeaders.get("User-Agent").getValue(), not(emptyString())); + assertEquals("application/x-www-form-urlencoded", MY_SERVLET.ourRequestContentType.replace(";char", "; char").toLowerCase()); + assertEquals(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY, MY_SERVLET.ourRequestFirstHeaders.get("Accept").getValue()); + assertThat(MY_SERVLET.ourRequestFirstHeaders.get("User-Agent").getValue(), not(emptyString())); } @Test public void testSearchByPostUseJson() throws Exception { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() .forResource("Patient") @@ -1422,30 +1402,30 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(Bundle.class) .execute(); - assertThat(ourRequestUri, containsString("http://localhost:" + ourPort + "/fhir/Patient/_search?")); - assertThat(ourRequestUri, containsString("_elements=identifier%2Cname")); - assertThat(ourRequestUri, not(containsString("_format=json"))); + assertThat(MY_SERVLET.ourRequestUri, containsString(ourServer.getBaseUrl() + "/fhir/Patient/_search?")); + assertThat(MY_SERVLET.ourRequestUri, containsString("_elements=identifier%2Cname")); + assertThat(MY_SERVLET.ourRequestUri, not(containsString("_format=json"))); - // assertThat(ourRequestUri, - // either(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://localhost:" + ourPort + + // assertThat(MY_SERVLET.ourRequestUri, + // either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo(ourServer.getBaseUrl() + // "/fhir/Patient?name=james&_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); - assertEquals("name=james", ourRequestBodyString); + assertEquals("name=james", MY_SERVLET.ourRequestBodyString); - assertEquals("application/x-www-form-urlencoded", ourRequestContentType); - assertEquals(Constants.CT_FHIR_JSON, ourRequestFirstHeaders.get("Accept").getValue()); + assertEquals("application/x-www-form-urlencoded", MY_SERVLET.ourRequestContentType); + assertEquals(Constants.CT_FHIR_JSON, MY_SERVLET.ourRequestFirstHeaders.get("Accept").getValue()); } @Test - public void testSearchWithLastUpdated() throws Exception { + public void testSearchWithLastUpdated() { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() .forResource("Patient") @@ -1454,18 +1434,18 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=james&_lastUpdated=ge2011-01-01&_lastUpdated=le2012-01-01", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_lastUpdated=ge2011-01-01&_lastUpdated=le2012-01-01", MY_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @Test - public void testSearchWithProfileAndSecurity() throws Exception { + public void testSearchWithProfileAndSecurity() { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() .forResource("Patient") @@ -1476,7 +1456,7 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?_security=system1%7Ccode1&_security=system2%7Ccode2&_profile=http%3A%2F%2Ffoo1&_profile=http%3A%2F%2Ffoo2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?_security=system1%7Ccode1&_security=system2%7Ccode2&_profile=http%3A%2F%2Ffoo1&_profile=http%3A%2F%2Ffoo2", MY_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1485,10 +1465,10 @@ public class GenericOkHttpClientDstu2Test { public void testSearchWithReverseInclude() throws Exception { String msg = getPatientFeedWithOneResult(); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() .forResource(Patient.class) @@ -1497,17 +1477,17 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", MY_SERVLET.ourRequestUri); } @Test public void testSearchWithSummaryParam() throws Exception { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() .forResource("Patient") @@ -1516,7 +1496,7 @@ public class GenericOkHttpClientDstu2Test { .returnBundle(Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=james&_summary=false", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_summary=false", MY_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1535,16 +1515,16 @@ public class GenericOkHttpClientDstu2Test { resp.addEntry().getResponse().setLocation("Patient/1/_history/1"); resp.addEntry().getResponse().setLocation("Patient/2/_history/2"); - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = reqString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = reqString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); String response = client.transaction() .withBundle(reqString) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/", MY_SERVLET.ourRequestUri); assertThat(response, containsString("\"Bundle\"")); assertContentTypeEquals("application/json+fhir; charset=UTF-8"); @@ -1553,7 +1533,7 @@ public class GenericOkHttpClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/", MY_SERVLET.ourRequestUri); assertContentTypeEquals("application/xml+fhir; charset=UTF-8"); } @@ -1564,10 +1544,10 @@ public class GenericOkHttpClientDstu2Test { resp.addEntry().getResponse().setLocation("Patient/2/_history/2"); String respString = ourCtx.newJsonParser().encodeResourceToString(resp); - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle input = new ca.uhn.fhir.model.dstu2.resource.Bundle(); @@ -1585,7 +1565,7 @@ public class GenericOkHttpClientDstu2Test { .encodedJson() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir", MY_SERVLET.ourRequestUri); assertEquals(2, response.getEntry().size()); assertEquals("Patient/1/_history/1", response.getEntry().get(0).getResponse().getLocation()); @@ -1594,97 +1574,97 @@ public class GenericOkHttpClientDstu2Test { @Test public void testUpdateConditional() throws Exception { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().addFamily("FOOFAMILY"); client.update().resource(p).conditionalByUrl("Patient?name=foo").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestUri); client.update().resource(p).conditionalByUrl("Patient?name=http://foo|bar").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar", ourRequestUri); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar", MY_SERVLET.ourRequestUri); client.update().resource(ourCtx.newXmlParser().encodeResourceToString(p)).conditionalByUrl("Patient?name=foo").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestUri); client.update().resource(p).conditional().where(Patient.NAME.matches().value("foo")).and(Patient.ADDRESS.matches().value("AAA|BBB")).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", ourRequestUri); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", MY_SERVLET.ourRequestUri); client.update().resource(ourCtx.newXmlParser().encodeResourceToString(p)).conditional().where(Patient.NAME.matches().value("foo")).and(Patient.ADDRESS.matches().value("AAA|BBB")).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertContentTypeEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", ourRequestUri); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", MY_SERVLET.ourRequestUri); } private String getActualContentTypeHeader() { - return ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char"); + return MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char"); } @Test public void testUpdateNonFluent() throws Exception { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.setEncoding(EncodingEnum.XML); Patient p = new Patient(); p.addName().addFamily("FOOFAMILY"); client.update(new IdDt("Patient/123"), p); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); String expectedContentTypeHeader = EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8; assertThat(getActualContentTypeHeader(), equalToIgnoringCase(expectedContentTypeHeader)); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_format=xml", ourRequestUri); - assertEquals("PUT", ourRequestMethod); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_format=xml", MY_SERVLET.ourRequestUri); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); client.update("123", p); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); assertThat(getActualContentTypeHeader(), equalToIgnoringCase(expectedContentTypeHeader)); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_format=xml", ourRequestUri); - assertEquals("PUT", ourRequestMethod); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_format=xml", MY_SERVLET.ourRequestUri); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); } @Test public void testUpdatePrefer() throws Exception { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.setId(new IdDt("1")); p.addName().addFamily("FOOFAMILY"); client.update().resource(p).prefer(PreferReturnEnum.MINIMAL).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); client.update().resource(p).prefer(PreferReturnEnum.REPRESENTATION).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); } @Test @@ -1693,11 +1673,11 @@ public class GenericOkHttpClientDstu2Test { p.setId("123"); final String formatted = ourCtx.newXmlParser().encodeResourceToString(p); - ourResponseStatus = Constants.STATUS_HTTP_200_OK; - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = formatted; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_200_OK; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = formatted; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); p = new Patient(); p.setId(new IdDt("1")); @@ -1714,10 +1694,10 @@ public class GenericOkHttpClientDstu2Test { oo.addIssue().setDiagnostics("FOOBAR"); final String msg = ourCtx.newXmlParser().encodeResourceToString(oo); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().addGiven("GIVEN"); @@ -1725,34 +1705,34 @@ public class GenericOkHttpClientDstu2Test { MethodOutcome response; response = client.validate().resource(p).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate", ourRequestUri); - assertEquals("POST", ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals( "", - ourRequestBodyString); + MY_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); response = client.validate().resource(ourCtx.newXmlParser().encodeResourceToString(p)).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate", ourRequestUri); - assertEquals("POST", ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals( "", - ourRequestBodyString); + MY_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); response = client.validate().resource(ourCtx.newJsonParser().encodeResourceToString(p)).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertEquals("{\"resourceType\":\"Parameters\",\"parameter\":[{\"name\":\"resource\",\"resource\":{\"resourceType\":\"Patient\",\"name\":[{\"given\":[\"GIVEN\"]}]}}]}", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); + assertEquals("{\"resourceType\":\"Parameters\",\"parameter\":[{\"name\":\"resource\",\"resource\":{\"resourceType\":\"Patient\",\"name\":[{\"given\":[\"GIVEN\"]}]}}]}", MY_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); response = client.validate().resource(ourCtx.newJsonParser().encodeResourceToString(p)).prettyPrint().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate?_pretty=true", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertThat(ourRequestBodyString, containsString("\"resourceType\": \"Parameters\",\n")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate?_pretty=true", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("\"resourceType\": \"Parameters\",\n")); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); } @@ -1763,10 +1743,10 @@ public class GenericOkHttpClientDstu2Test { oo.addIssue().setDiagnostics("FOOBAR"); final String msg = ourCtx.newXmlParser().encodeResourceToString(oo); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.setEncoding(EncodingEnum.XML); Patient p = new Patient(); @@ -1776,11 +1756,11 @@ public class GenericOkHttpClientDstu2Test { response = client.validate(p); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate?_format=xml", ourRequestUri); - assertEquals("POST", ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate?_format=xml", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals( "", - ourRequestBodyString); + MY_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); } @@ -1789,77 +1769,4 @@ public class GenericOkHttpClientDstu2Test { return (OperationOutcome) theOperationOutcome; } - @BeforeEach - public void beforeReset() { - ourRequestUri = null; - ourRequestUriAll = Lists.newArrayList(); - ourResponseStatus = 200; - ourResponseBody = null; - ourResponseBodies = null; - ourResponseCount = 0; - - ourResponseContentType = null; - ourRequestContentType = null; - ourRequestBodyBytes = null; - ourRequestBodyString = null; - ourRequestHeaders = null; - ourRequestFirstHeaders = null; - ourRequestMethod = null; - ourRequestHeadersAll = Lists.newArrayList(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu2(); - - ourServer = new Server(0); - ourServer.setHandler(new AbstractHandler() { - - @Override - public void handle(String theArg0, Request theRequest, HttpServletRequest theServletRequest, HttpServletResponse theResp) throws IOException, ServletException { - theRequest.setHandled(true); - ourRequestUri = theRequest.getHttpURI().toString(); - ourRequestUriAll.add(ourRequestUri); - ourRequestMethod = theRequest.getMethod(); - ourRequestContentType = theServletRequest.getContentType(); - ourRequestBodyBytes = IOUtils.toByteArray(theServletRequest.getInputStream()); - ourRequestBodyString = new String(ourRequestBodyBytes, Charsets.UTF_8); - - ourRequestHeaders = ArrayListMultimap.create(); - ourRequestHeadersAll.add(ourRequestHeaders); - ourRequestFirstHeaders = Maps.newHashMap(); - - for (Enumeration headerNameEnum = theRequest.getHeaderNames(); headerNameEnum.hasMoreElements(); ) { - String nextName = headerNameEnum.nextElement(); - for (Enumeration headerValueEnum = theRequest.getHeaders(nextName); headerValueEnum.hasMoreElements(); ) { - String nextValue = headerValueEnum.nextElement(); - if (ourRequestFirstHeaders.containsKey(nextName) == false) { - ourRequestFirstHeaders.put(nextName, new Header(nextName, nextValue)); - } - ourRequestHeaders.put(nextName, new Header(nextName, nextValue)); - } - } - - theResp.setStatus(ourResponseStatus); - - if (ourResponseBody != null) { - theResp.setContentType(ourResponseContentType); - theResp.getWriter().write(ourResponseBody); - } else if (ourResponseBodies != null) { - theResp.setContentType(ourResponseContentType); - theResp.getWriter().write(ourResponseBodies[ourResponseCount]); - } - - ourResponseCount++; - } - }); - - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - } - - @AfterAll - public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } } diff --git a/hapi-fhir-client/pom.xml b/hapi-fhir-client/pom.xml index 1f8a6b2d2f6..bed73ac4cbf 100644 --- a/hapi-fhir-client/pom.xml +++ b/hapi-fhir-client/pom.xml @@ -4,7 +4,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpClient.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpClient.java index 4235ef0de4a..4269b074d22 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpClient.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpClient.java @@ -22,19 +22,29 @@ package ca.uhn.fhir.rest.client.apache; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.RequestTypeEnum; -import ca.uhn.fhir.rest.client.api.*; +import ca.uhn.fhir.rest.client.api.Header; +import ca.uhn.fhir.rest.client.api.IHttpClient; +import ca.uhn.fhir.rest.client.api.IHttpRequest; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.*; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpOptions; +import org.apache.http.client.methods.HttpPatch; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.message.BasicNameValuePair; import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; -import java.util.*; /** * A Http Client based on Apache. This is an adapter around the class diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpResponse.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpResponse.java index 33c573d7054..2fb0546f33e 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpResponse.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpResponse.java @@ -26,14 +26,24 @@ import ca.uhn.fhir.rest.client.impl.BaseHttpResponse; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.util.StopWatch; import org.apache.commons.io.IOUtils; +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.entity.ContentType; -import org.apache.http.*; -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * A Http Response based on Apache. This is an adapter around the class diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/BaseHttpClient.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/BaseHttpClient.java index 79fc6d71461..e6c0cdea08c 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/BaseHttpClient.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/BaseHttpClient.java @@ -20,7 +20,9 @@ package ca.uhn.fhir.rest.client.apache; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.api.*; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.rest.api.RequestTypeEnum; import ca.uhn.fhir.rest.client.api.Header; import ca.uhn.fhir.rest.client.api.HttpClientUtil; import ca.uhn.fhir.rest.client.api.IHttpClient; diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/GZipContentInterceptor.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/GZipContentInterceptor.java index ce6869ec4fd..06e974f6c41 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/GZipContentInterceptor.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/apache/GZipContentInterceptor.java @@ -20,7 +20,9 @@ package ca.uhn.fhir.rest.client.apache; import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.client.api.*; +import ca.uhn.fhir.rest.client.api.IClientInterceptor; +import ca.uhn.fhir.rest.client.api.IHttpRequest; +import ca.uhn.fhir.rest.client.api.IHttpResponse; import org.apache.http.Header; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.client.methods.HttpRequestBase; diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/interceptor/BasicAuthInterceptor.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/interceptor/BasicAuthInterceptor.java index 6cb8d3c1dfa..2e86a893fdb 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/interceptor/BasicAuthInterceptor.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/interceptor/BasicAuthInterceptor.java @@ -20,7 +20,9 @@ package ca.uhn.fhir.rest.client.interceptor; import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.client.api.*; +import ca.uhn.fhir.rest.client.api.IClientInterceptor; +import ca.uhn.fhir.rest.client.api.IHttpRequest; +import ca.uhn.fhir.rest.client.api.IHttpResponse; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/interceptor/CookieInterceptor.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/interceptor/CookieInterceptor.java index 923680eaabc..4f22f76470d 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/interceptor/CookieInterceptor.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/interceptor/CookieInterceptor.java @@ -20,7 +20,9 @@ package ca.uhn.fhir.rest.client.interceptor; import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.client.api.*; +import ca.uhn.fhir.rest.client.api.IClientInterceptor; +import ca.uhn.fhir.rest.client.api.IHttpRequest; +import ca.uhn.fhir.rest.client.api.IHttpResponse; /** * HTTP interceptor to be used for adding Cookie to requests. diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseMethodBinding.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseMethodBinding.java index 0e8e1c33a6b..11c50a18655 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseMethodBinding.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseMethodBinding.java @@ -19,16 +19,41 @@ */ package ca.uhn.fhir.rest.client.method; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.ConfigurationException; +import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.i18n.Msg; -import ca.uhn.fhir.model.api.*; +import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.base.resource.BaseOperationOutcome; import ca.uhn.fhir.parser.IParser; -import ca.uhn.fhir.rest.annotation.*; -import ca.uhn.fhir.rest.api.*; +import ca.uhn.fhir.rest.annotation.AddTags; +import ca.uhn.fhir.rest.annotation.Create; +import ca.uhn.fhir.rest.annotation.Delete; +import ca.uhn.fhir.rest.annotation.DeleteTags; +import ca.uhn.fhir.rest.annotation.GetPage; +import ca.uhn.fhir.rest.annotation.History; +import ca.uhn.fhir.rest.annotation.Metadata; +import ca.uhn.fhir.rest.annotation.Operation; +import ca.uhn.fhir.rest.annotation.Patch; +import ca.uhn.fhir.rest.annotation.Read; +import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.annotation.Transaction; +import ca.uhn.fhir.rest.annotation.Update; +import ca.uhn.fhir.rest.annotation.Validate; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.client.exceptions.NonFhirResponseException; import ca.uhn.fhir.rest.client.impl.BaseHttpClientInvocation; -import ca.uhn.fhir.rest.server.exceptions.*; +import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; +import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; +import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; +import ca.uhn.fhir.rest.server.exceptions.MethodNotAllowedException; +import ca.uhn.fhir.rest.server.exceptions.PreconditionFailedException; +import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; +import ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException; +import ca.uhn.fhir.rest.server.exceptions.UnclassifiedServerFailureException; +import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import ca.uhn.fhir.util.ReflectionUtil; import org.apache.commons.io.IOUtils; import org.hl7.fhir.instance.model.api.IAnyResource; @@ -37,7 +62,10 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; -import java.util.*; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; public abstract class BaseMethodBinding implements IClientResponseHandler { diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseOutcomeReturningMethodBinding.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseOutcomeReturningMethodBinding.java index 91db00c0dbd..c2043d7e9dd 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseOutcomeReturningMethodBinding.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseOutcomeReturningMethodBinding.java @@ -32,7 +32,9 @@ import org.hl7.fhir.instance.model.api.IIdType; import java.io.InputStream; import java.lang.reflect.Method; -import java.util.*; +import java.util.List; +import java.util.Map; +import java.util.Set; abstract class BaseOutcomeReturningMethodBinding extends BaseMethodBinding { static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseOutcomeReturningMethodBinding.class); diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseOutcomeReturningMethodBindingWithResourceIdButNoResourceBody.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseOutcomeReturningMethodBindingWithResourceIdButNoResourceBody.java index a31703842ab..af1b00f22b9 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseOutcomeReturningMethodBindingWithResourceIdButNoResourceBody.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/BaseOutcomeReturningMethodBindingWithResourceIdButNoResourceBody.java @@ -19,9 +19,12 @@ */ package ca.uhn.fhir.rest.client.method; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.ConfigurationException; +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.i18n.Msg; -import ca.uhn.fhir.rest.annotation.*; +import ca.uhn.fhir.rest.annotation.Delete; +import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.param.ParameterUtil; import org.hl7.fhir.instance.model.api.IBaseResource; diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/ConditionalParamBinder.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/ConditionalParamBinder.java index 37ce4bdf3eb..12a479b9e72 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/ConditionalParamBinder.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/ConditionalParamBinder.java @@ -29,7 +29,9 @@ import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBaseResource; import java.lang.reflect.Method; -import java.util.*; +import java.util.Collection; +import java.util.List; +import java.util.Map; class ConditionalParamBinder implements IParameter { diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/DeleteMethodBinding.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/DeleteMethodBinding.java index a69d57f5c62..6e63d2a368e 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/DeleteMethodBinding.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/DeleteMethodBinding.java @@ -31,7 +31,10 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import java.lang.reflect.Method; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; public class DeleteMethodBinding extends BaseOutcomeReturningMethodBindingWithResourceIdButNoResourceBody { diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/HistoryMethodBinding.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/HistoryMethodBinding.java index 86997ad19e1..38580994c73 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/HistoryMethodBinding.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/HistoryMethodBinding.java @@ -31,7 +31,9 @@ import ca.uhn.fhir.rest.param.DateParam; import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.param.ParameterUtil; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; -import org.hl7.fhir.instance.model.api.*; +import org.hl7.fhir.instance.model.api.IBaseResource; +import org.hl7.fhir.instance.model.api.IIdType; +import org.hl7.fhir.instance.model.api.IPrimitiveType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/NullParameter.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/NullParameter.java index d80cc262a19..2fff425f0ac 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/NullParameter.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/NullParameter.java @@ -24,7 +24,9 @@ import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import org.hl7.fhir.instance.model.api.IBaseResource; import java.lang.reflect.Method; -import java.util.*; +import java.util.Collection; +import java.util.List; +import java.util.Map; class NullParameter implements IParameter { diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/OperationMethodBinding.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/OperationMethodBinding.java index b852238c9bc..fb723b1849d 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/OperationMethodBinding.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/OperationMethodBinding.java @@ -31,7 +31,13 @@ import ca.uhn.fhir.rest.param.ParameterUtil; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.util.FhirTerser; import ca.uhn.fhir.util.ParametersUtil; -import org.hl7.fhir.instance.model.api.*; +import org.hl7.fhir.instance.model.api.IBase; +import org.hl7.fhir.instance.model.api.IBaseBundle; +import org.hl7.fhir.instance.model.api.IBaseDatatype; +import org.hl7.fhir.instance.model.api.IBaseParameters; +import org.hl7.fhir.instance.model.api.IBaseResource; +import org.hl7.fhir.instance.model.api.IIdType; +import org.hl7.fhir.instance.model.api.IPrimitiveType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/PatchMethodBinding.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/PatchMethodBinding.java index fd53b07ae4f..cee15f46595 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/PatchMethodBinding.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/PatchMethodBinding.java @@ -24,7 +24,9 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.rest.annotation.Patch; import ca.uhn.fhir.rest.annotation.ResourceParam; -import ca.uhn.fhir.rest.api.*; +import ca.uhn.fhir.rest.api.PatchTypeEnum; +import ca.uhn.fhir.rest.api.RequestTypeEnum; +import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.client.impl.BaseHttpClientInvocation; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; @@ -33,7 +35,12 @@ import org.hl7.fhir.instance.model.api.IIdType; import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Set; /** * Base class for an operation that has a resource type but not a resource body in the diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/RawParamsParmeter.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/RawParamsParmeter.java index eb147489828..8b919104632 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/RawParamsParmeter.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/RawParamsParmeter.java @@ -26,7 +26,9 @@ import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBaseResource; import java.lang.reflect.Method; -import java.util.*; +import java.util.Collection; +import java.util.List; +import java.util.Map; public class RawParamsParmeter implements IParameter { diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/ReadMethodBinding.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/ReadMethodBinding.java index d2710f86fe4..014cce3e569 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/ReadMethodBinding.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/ReadMethodBinding.java @@ -24,18 +24,25 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.model.valueset.BundleTypeEnum; -import ca.uhn.fhir.rest.annotation.*; +import ca.uhn.fhir.rest.annotation.Elements; +import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.param.ParameterUtil; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.Validate; -import org.hl7.fhir.instance.model.api.*; +import org.hl7.fhir.instance.model.api.IBaseBinary; +import org.hl7.fhir.instance.model.api.IBaseResource; +import org.hl7.fhir.instance.model.api.IIdType; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; public class ReadMethodBinding extends BaseResourceReturningMethodBinding implements IClientResponseHandlerHandlesBinary { diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/SearchParameter.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/SearchParameter.java index 058eda8f287..4fcecab24d8 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/SearchParameter.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/SearchParameter.java @@ -19,16 +19,56 @@ */ package ca.uhn.fhir.rest.client.method; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.ConfigurationException; +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.context.RuntimePrimitiveDatatypeDefinition; import ca.uhn.fhir.i18n.Msg; -import ca.uhn.fhir.model.api.*; +import ca.uhn.fhir.model.api.IQueryParameterAnd; +import ca.uhn.fhir.model.api.IQueryParameterOr; +import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.model.base.composite.BaseIdentifierDt; import ca.uhn.fhir.model.base.composite.BaseQuantityDt; import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.rest.annotation.OptionalParam; -import ca.uhn.fhir.rest.api.*; -import ca.uhn.fhir.rest.param.*; -import ca.uhn.fhir.rest.param.binder.*; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.QualifiedParamList; +import ca.uhn.fhir.rest.api.RestSearchParameterTypeEnum; +import ca.uhn.fhir.rest.param.CompositeAndListParam; +import ca.uhn.fhir.rest.param.CompositeOrListParam; +import ca.uhn.fhir.rest.param.CompositeParam; +import ca.uhn.fhir.rest.param.DateAndListParam; +import ca.uhn.fhir.rest.param.DateOrListParam; +import ca.uhn.fhir.rest.param.DateParam; +import ca.uhn.fhir.rest.param.DateRangeParam; +import ca.uhn.fhir.rest.param.HasAndListParam; +import ca.uhn.fhir.rest.param.HasOrListParam; +import ca.uhn.fhir.rest.param.HasParam; +import ca.uhn.fhir.rest.param.NumberAndListParam; +import ca.uhn.fhir.rest.param.NumberOrListParam; +import ca.uhn.fhir.rest.param.NumberParam; +import ca.uhn.fhir.rest.param.QuantityAndListParam; +import ca.uhn.fhir.rest.param.QuantityOrListParam; +import ca.uhn.fhir.rest.param.QuantityParam; +import ca.uhn.fhir.rest.param.ReferenceAndListParam; +import ca.uhn.fhir.rest.param.ReferenceOrListParam; +import ca.uhn.fhir.rest.param.ReferenceParam; +import ca.uhn.fhir.rest.param.StringAndListParam; +import ca.uhn.fhir.rest.param.StringOrListParam; +import ca.uhn.fhir.rest.param.StringParam; +import ca.uhn.fhir.rest.param.TokenAndListParam; +import ca.uhn.fhir.rest.param.TokenOrListParam; +import ca.uhn.fhir.rest.param.TokenParam; +import ca.uhn.fhir.rest.param.UriAndListParam; +import ca.uhn.fhir.rest.param.UriOrListParam; +import ca.uhn.fhir.rest.param.UriParam; +import ca.uhn.fhir.rest.param.binder.CalendarBinder; +import ca.uhn.fhir.rest.param.binder.DateBinder; +import ca.uhn.fhir.rest.param.binder.FhirPrimitiveBinder; +import ca.uhn.fhir.rest.param.binder.IParamBinder; +import ca.uhn.fhir.rest.param.binder.QueryParameterAndBinder; +import ca.uhn.fhir.rest.param.binder.QueryParameterOrBinder; +import ca.uhn.fhir.rest.param.binder.QueryParameterTypeBinder; +import ca.uhn.fhir.rest.param.binder.StringBinder; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.util.CollectionUtil; import ca.uhn.fhir.util.ReflectionUtil; @@ -36,7 +76,16 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IPrimitiveType; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; public class SearchParameter extends BaseQueryParameter { diff --git a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/TransactionParameter.java b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/TransactionParameter.java index 546fa2bdff2..e793c0361a6 100644 --- a/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/TransactionParameter.java +++ b/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/method/TransactionParameter.java @@ -19,7 +19,9 @@ */ package ca.uhn.fhir.rest.client.method; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.ConfigurationException; +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.rest.annotation.TransactionParam; @@ -28,7 +30,9 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.*; +import java.util.Collection; +import java.util.List; +import java.util.Map; public class TransactionParameter implements IParameter { diff --git a/hapi-fhir-converter/pom.xml b/hapi-fhir-converter/pom.xml index bcaa65bb8cb..0accae54174 100644 --- a/hapi-fhir-converter/pom.xml +++ b/hapi-fhir-converter/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -33,8 +33,8 @@ true - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided @@ -126,36 +126,6 @@ xmlunit-core test - - org.eclipse.jetty - jetty-servlets - test - - - org.eclipse.jetty - jetty-servlet - test - - - org.eclipse.jetty - jetty-server - test - - - org.eclipse.jetty - jetty-util - test - - - org.eclipse.jetty - jetty-webapp - test - - - org.eclipse.jetty - jetty-http - test - ca.uhn.hapi.fhir hapi-fhir-test-utilities @@ -183,7 +153,7 @@ ca.uhn.fhir.rest.server*;resolution:=optional, - javax.servlet.http;resolution:=optional, + jakarta.servlet.http;resolution:=optional, * diff --git a/hapi-fhir-converter/src/main/java/ca/uhn/hapi/converters/server/VersionedApiConverterInterceptor.java b/hapi-fhir-converter/src/main/java/ca/uhn/hapi/converters/server/VersionedApiConverterInterceptor.java index c009350abc5..6de828b406f 100644 --- a/hapi-fhir-converter/src/main/java/ca/uhn/hapi/converters/server/VersionedApiConverterInterceptor.java +++ b/hapi-fhir-converter/src/main/java/ca/uhn/hapi/converters/server/VersionedApiConverterInterceptor.java @@ -31,6 +31,8 @@ import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter; import ca.uhn.fhir.rest.server.interceptor.auth.AuthorizationConstants; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.hl7.fhir.converter.NullVersionConverterAdvisor10_30; import org.hl7.fhir.converter.NullVersionConverterAdvisor10_40; import org.hl7.fhir.convertors.factory.VersionConvertorFactory_10_30; @@ -41,8 +43,6 @@ import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.instance.model.api.IBaseResource; import java.util.StringTokenizer; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-converter/src/test/java/ca/uhn/hapi/converters/server/VersionedApiConverterInterceptorR4Test.java b/hapi-fhir-converter/src/test/java/ca/uhn/hapi/converters/server/VersionedApiConverterInterceptorR4Test.java index 08e6f17231c..7d83cabfe68 100644 --- a/hapi-fhir-converter/src/test/java/ca/uhn/hapi/converters/server/VersionedApiConverterInterceptorR4Test.java +++ b/hapi-fhir-converter/src/test/java/ca/uhn/hapi/converters/server/VersionedApiConverterInterceptorR4Test.java @@ -5,7 +5,9 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; import org.apache.commons.io.IOUtils; @@ -15,14 +17,15 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.HumanName; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -35,16 +38,21 @@ import static org.hamcrest.MatcherAssert.assertThat; public class VersionedApiConverterInterceptorR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(VersionedApiConverterInterceptorR4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); - private static int ourPort; + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); - private static Server ourServer; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .registerInterceptor(new VersionedApiConverterInterceptor()) + .setDefaultResponseEncoding(EncodingEnum.JSON); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testSearchNormal() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(responseContent); @@ -54,7 +62,7 @@ public class VersionedApiConverterInterceptorR4Test { @Test public void testSearchConvertToR2() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); httpGet.addHeader("Accept", "application/fhir+json; fhirVersion=1.0"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -65,7 +73,7 @@ public class VersionedApiConverterInterceptorR4Test { @Test public void testSearchConvertToR2ByFormatParam() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + UrlUtil.escapeUrlParam("application/fhir+json; fhirVersion=1.0")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=" + UrlUtil.escapeUrlParam("application/fhir+json; fhirVersion=1.0")); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(responseContent); @@ -75,36 +83,9 @@ public class VersionedApiConverterInterceptorR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.JSON); - servlet.setDefaultPrettyPrint(true); - servlet.registerInterceptor(new VersionedApiConverterInterceptor()); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-dist/pom.xml b/hapi-fhir-dist/pom.xml index bd14759edc9..298abf36b56 100644 --- a/hapi-fhir-dist/pom.xml +++ b/hapi-fhir-dist/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../pom.xml @@ -249,18 +249,12 @@ thymeleaf - com.helger - ph-schematron - - - Saxon-HE - net.sf.saxon - - + com.helger.schematron + ph-schematron-api - com.helger - ph-commons + com.helger.schematron + ph-schematron-xslt org.springframework diff --git a/hapi-fhir-docs/pom.xml b/hapi-fhir-docs/pom.xml index ce9d6c844ce..0de0b3b0a0a 100644 --- a/hapi-fhir-docs/pom.xml +++ b/hapi-fhir-docs/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -72,10 +72,6 @@ jackson-dataformat-yaml - - javax.ejb - ejb-api - javax.ws.rs jsr311-api @@ -104,8 +100,8 @@ - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/AuthorizationInterceptors.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/AuthorizationInterceptors.java index 94a2becaeac..ae017dc82d4 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/AuthorizationInterceptors.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/AuthorizationInterceptors.java @@ -35,7 +35,14 @@ import ca.uhn.fhir.rest.api.server.storage.TransactionDetails; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; -import ca.uhn.fhir.rest.server.interceptor.auth.*; +import ca.uhn.fhir.rest.server.interceptor.auth.AdditionalCompartmentSearchParameters; +import ca.uhn.fhir.rest.server.interceptor.auth.AuthorizationInterceptor; +import ca.uhn.fhir.rest.server.interceptor.auth.AuthorizedList; +import ca.uhn.fhir.rest.server.interceptor.auth.IAuthRule; +import ca.uhn.fhir.rest.server.interceptor.auth.PolicyEnum; +import ca.uhn.fhir.rest.server.interceptor.auth.RuleBuilder; +import ca.uhn.fhir.rest.server.interceptor.auth.SearchNarrowingConsentService; +import ca.uhn.fhir.rest.server.interceptor.auth.SearchNarrowingInterceptor; import ca.uhn.fhir.rest.server.interceptor.consent.ConsentInterceptor; import ca.uhn.fhir.rest.server.interceptor.consent.RuleFilteringConsentService; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/AuthorizingTesterUiClientFactory.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/AuthorizingTesterUiClientFactory.java index f40e1a0ef6e..4a284f8f03e 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/AuthorizingTesterUiClientFactory.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/AuthorizingTesterUiClientFactory.java @@ -23,8 +23,7 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.interceptor.BasicAuthInterceptor; import ca.uhn.fhir.rest.server.util.ITestingUiClientFactory; - -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; public class AuthorizingTesterUiClientFactory implements ITestingUiClientFactory { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/BalpExample.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/BalpExample.java index f04b586d38f..94e987a1c0c 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/BalpExample.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/BalpExample.java @@ -26,11 +26,11 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.storage.interceptor.balp.AsyncMemoryQueueBackedFhirClientBalpSink; import ca.uhn.fhir.storage.interceptor.balp.IBalpAuditContextServices; import ca.uhn.fhir.storage.interceptor.balp.IBalpAuditEventSink; +import jakarta.servlet.ServletException; import org.hl7.fhir.r4.model.Reference; import java.util.List; import javax.annotation.Nonnull; -import javax.servlet.ServletException; public class BalpExample { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ClientTransactionExamples.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ClientTransactionExamples.java index cbd954ce231..de96c72ec61 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ClientTransactionExamples.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ClientTransactionExamples.java @@ -21,7 +21,13 @@ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.client.api.IGenericClient; -import org.hl7.fhir.r4.model.*; +import org.hl7.fhir.r4.model.Bundle; +import org.hl7.fhir.r4.model.Enumerations; +import org.hl7.fhir.r4.model.IdType; +import org.hl7.fhir.r4.model.Observation; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Quantity; +import org.hl7.fhir.r4.model.Reference; public class ClientTransactionExamples { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Copier.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Copier.java index 35594752f37..c16556aedb4 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Copier.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Copier.java @@ -29,7 +29,11 @@ import org.hl7.fhir.instance.model.api.IIdType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Dstu2Examples.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Dstu2Examples.java index 3ec9e5275b6..7de0d0ff5f1 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Dstu2Examples.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/Dstu2Examples.java @@ -24,9 +24,9 @@ import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; +import jakarta.servlet.ServletException; import java.util.Collection; -import javax.servlet.ServletException; @SuppressWarnings("serial") public class Dstu2Examples { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExampleRestfulClient.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExampleRestfulClient.java index d2dcb9a74f8..703dabe9c65 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExampleRestfulClient.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExampleRestfulClient.java @@ -20,7 +20,8 @@ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.context.FhirContext; -import org.hl7.fhir.r4.model.*; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.StringType; import java.util.List; diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExampleRestfulServlet.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExampleRestfulServlet.java index 601a94cb353..9d7fa02fea7 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExampleRestfulServlet.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExampleRestfulServlet.java @@ -21,11 +21,11 @@ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; import java.util.ArrayList; import java.util.List; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; // START SNIPPET: servlet diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExtensionsDstu3.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExtensionsDstu3.java index a433b2f27d6..267ea3c7249 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExtensionsDstu3.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ExtensionsDstu3.java @@ -22,7 +22,14 @@ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.parser.DataFormatException; import ca.uhn.fhir.rest.client.api.IGenericClient; -import org.hl7.fhir.r4.model.*; +import org.hl7.fhir.r4.model.Bundle; +import org.hl7.fhir.r4.model.DateTimeType; +import org.hl7.fhir.r4.model.Extension; +import org.hl7.fhir.r4.model.HumanName; +import org.hl7.fhir.r4.model.IdType; +import org.hl7.fhir.r4.model.Identifier; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.StringType; import java.io.IOException; import java.util.List; diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/FhirContextIntro.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/FhirContextIntro.java index 786e1ffed14..58daa9517e3 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/FhirContextIntro.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/FhirContextIntro.java @@ -22,7 +22,11 @@ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.parser.DataFormatException; import ca.uhn.fhir.parser.IParser; -import org.hl7.fhir.r4.model.*; +import org.hl7.fhir.r4.model.Enumerations; +import org.hl7.fhir.r4.model.HumanName; +import org.hl7.fhir.r4.model.Identifier; +import org.hl7.fhir.r4.model.Observation; +import org.hl7.fhir.r4.model.Patient; public class FhirContextIntro { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/FhirDataModel.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/FhirDataModel.java index 4a365cd0597..37ebe099e66 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/FhirDataModel.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/FhirDataModel.java @@ -22,7 +22,17 @@ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.api.TemporalPrecisionEnum; import ca.uhn.fhir.rest.client.api.IGenericClient; -import org.hl7.fhir.r4.model.*; +import org.hl7.fhir.r4.model.CodeableConcept; +import org.hl7.fhir.r4.model.Coding; +import org.hl7.fhir.r4.model.Enumerations; +import org.hl7.fhir.r4.model.HumanName; +import org.hl7.fhir.r4.model.Identifier; +import org.hl7.fhir.r4.model.InstantType; +import org.hl7.fhir.r4.model.Observation; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.Quantity; +import org.hl7.fhir.r4.model.SimpleQuantity; +import org.hl7.fhir.r4.model.StringType; import java.util.Date; import java.util.List; diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/JaxRsConformanceProvider.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/JaxRsConformanceProvider.java index 8827962da1e..3312ba27702 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/JaxRsConformanceProvider.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/JaxRsConformanceProvider.java @@ -22,13 +22,13 @@ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.jaxrs.server.AbstractJaxRsConformanceProvider; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.server.IResourceProvider; +import jakarta.ejb.EJB; +import jakarta.ejb.Stateless; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; import java.util.concurrent.ConcurrentHashMap; -import javax.ejb.EJB; -import javax.ejb.Stateless; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; /** * Conformance Rest Service diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/JaxRsPatientRestProvider.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/JaxRsPatientRestProvider.java index 90981c02318..3130b526342 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/JaxRsPatientRestProvider.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/JaxRsPatientRestProvider.java @@ -21,22 +21,30 @@ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.jaxrs.server.AbstractJaxRsResourceProvider; import ca.uhn.fhir.model.primitive.StringDt; -import ca.uhn.fhir.rest.annotation.*; +import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; +import ca.uhn.fhir.rest.annotation.Create; +import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.annotation.Operation; +import ca.uhn.fhir.rest.annotation.OperationParam; +import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.RequestTypeEnum; import ca.uhn.fhir.rest.api.RestOperationTypeEnum; +import jakarta.ejb.Local; +import jakarta.ejb.Stateless; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Parameters; import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.StringType; -import javax.ejb.Local; -import javax.ejb.Stateless; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.*; - /** * A demo JaxRs Patient Rest Provider */ diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/PartitionExamples.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/PartitionExamples.java index dbe13655830..d17a23f2afd 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/PartitionExamples.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/PartitionExamples.java @@ -28,13 +28,13 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.rest.server.tenant.UrlBaseTenantIdentificationStrategy; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Observation; import org.hl7.fhir.r4.model.Patient; import org.springframework.beans.factory.annotation.Autowired; import java.util.Set; -import javax.servlet.http.HttpServletRequest; @SuppressWarnings("InnerClassMayBeStatic") public class PartitionExamples { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RequestCounterInterceptor.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RequestCounterInterceptor.java index be64bc050ba..ca352849127 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RequestCounterInterceptor.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RequestCounterInterceptor.java @@ -22,9 +22,8 @@ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.interceptor.api.Hook; import ca.uhn.fhir.interceptor.api.Interceptor; import ca.uhn.fhir.interceptor.api.Pointcut; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; // START SNIPPET: interceptor @Interceptor diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RequestExceptionInterceptor.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RequestExceptionInterceptor.java index 4e89f7eb9b9..c9cffa52427 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RequestExceptionInterceptor.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RequestExceptionInterceptor.java @@ -23,10 +23,10 @@ import ca.uhn.fhir.interceptor.api.Hook; import ca.uhn.fhir.interceptor.api.Pointcut; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; // START SNIPPET: interceptor public class RequestExceptionInterceptor { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RestfulPatientResourceProviderMore.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RestfulPatientResourceProviderMore.java index a1c27f0d831..2d30a3ec2d4 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RestfulPatientResourceProviderMore.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/RestfulPatientResourceProviderMore.java @@ -27,19 +27,70 @@ import ca.uhn.fhir.model.api.TemporalPrecisionEnum; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.valueset.BundleEntryTransactionMethodEnum; import ca.uhn.fhir.parser.DataFormatException; +import ca.uhn.fhir.rest.annotation.At; +import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; import ca.uhn.fhir.rest.annotation.Count; -import ca.uhn.fhir.rest.annotation.*; -import ca.uhn.fhir.rest.api.*; +import ca.uhn.fhir.rest.annotation.Create; +import ca.uhn.fhir.rest.annotation.Delete; +import ca.uhn.fhir.rest.annotation.Elements; +import ca.uhn.fhir.rest.annotation.History; +import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.annotation.IncludeParam; +import ca.uhn.fhir.rest.annotation.Metadata; +import ca.uhn.fhir.rest.annotation.Offset; +import ca.uhn.fhir.rest.annotation.OptionalParam; +import ca.uhn.fhir.rest.annotation.Read; +import ca.uhn.fhir.rest.annotation.RequiredParam; +import ca.uhn.fhir.rest.annotation.ResourceParam; +import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.annotation.Since; +import ca.uhn.fhir.rest.annotation.Sort; +import ca.uhn.fhir.rest.annotation.Transaction; +import ca.uhn.fhir.rest.annotation.TransactionParam; +import ca.uhn.fhir.rest.annotation.Update; +import ca.uhn.fhir.rest.annotation.Validate; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.rest.api.SortOrderEnum; +import ca.uhn.fhir.rest.api.SortSpec; +import ca.uhn.fhir.rest.api.SummaryEnum; +import ca.uhn.fhir.rest.api.ValidationModeEnum; import ca.uhn.fhir.rest.client.api.IBasicClient; -import ca.uhn.fhir.rest.param.*; +import ca.uhn.fhir.rest.param.CompositeParam; +import ca.uhn.fhir.rest.param.DateParam; +import ca.uhn.fhir.rest.param.DateRangeParam; +import ca.uhn.fhir.rest.param.ParamPrefixEnum; +import ca.uhn.fhir.rest.param.QuantityParam; +import ca.uhn.fhir.rest.param.ReferenceParam; +import ca.uhn.fhir.rest.param.StringAndListParam; +import ca.uhn.fhir.rest.param.StringOrListParam; +import ca.uhn.fhir.rest.param.StringParam; +import ca.uhn.fhir.rest.param.TokenOrListParam; +import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.rest.server.IResourceProvider; -import ca.uhn.fhir.rest.server.exceptions.*; +import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; +import ca.uhn.fhir.rest.server.exceptions.PreconditionFailedException; +import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; +import ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException; +import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; +import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; +import org.hl7.fhir.r4.model.CapabilityStatement; +import org.hl7.fhir.r4.model.Coding; +import org.hl7.fhir.r4.model.DateTimeType; +import org.hl7.fhir.r4.model.DiagnosticReport; +import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Identifier.IdentifierUse; +import org.hl7.fhir.r4.model.InstantType; +import org.hl7.fhir.r4.model.Observation; +import org.hl7.fhir.r4.model.OperationOutcome; import org.hl7.fhir.r4.model.OperationOutcome.IssueSeverity; -import org.hl7.fhir.r4.model.*; +import org.hl7.fhir.r4.model.Organization; +import org.hl7.fhir.r4.model.Patient; import java.io.IOException; import java.math.BigDecimal; @@ -47,8 +98,6 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; @SuppressWarnings("unused") public abstract class RestfulPatientResourceProviderMore implements IResourceProvider { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/SecurityInterceptors.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/SecurityInterceptors.java index f44f6004ecf..ac81b7322af 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/SecurityInterceptors.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/SecurityInterceptors.java @@ -25,11 +25,10 @@ import ca.uhn.fhir.interceptor.api.Interceptor; import ca.uhn.fhir.interceptor.api.Pointcut; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - public class SecurityInterceptors { public void basicAuthInterceptorRealm() { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServerETagExamples.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServerETagExamples.java index 6c78c25e8f9..0e8977d4346 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServerETagExamples.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServerETagExamples.java @@ -21,9 +21,8 @@ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.rest.server.ETagSupportEnum; import ca.uhn.fhir.rest.server.RestfulServer; - -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; @SuppressWarnings("serial") public class ServerETagExamples { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServerOperations.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServerOperations.java index 1365d2d61ec..173887ef082 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServerOperations.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServerOperations.java @@ -24,7 +24,13 @@ import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; -import ca.uhn.fhir.rest.param.*; +import ca.uhn.fhir.rest.param.DateParam; +import ca.uhn.fhir.rest.param.DateRangeParam; +import ca.uhn.fhir.rest.param.StringParam; +import ca.uhn.fhir.rest.param.TokenAndListParam; +import ca.uhn.fhir.rest.param.TokenParam; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.hl7.fhir.dstu3.model.Parameters; import org.hl7.fhir.r4.model.Bundle; @@ -36,8 +42,6 @@ import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; public class ServerOperations { private static final Logger ourLog = LoggerFactory.getLogger(ServerOperations.class); diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServletExamples.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServletExamples.java index a6b336f3cfa..7eb61d0711b 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServletExamples.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ServletExamples.java @@ -37,14 +37,14 @@ import ca.uhn.fhir.rest.server.interceptor.ResponseValidatingInterceptor; import ca.uhn.fhir.rest.server.interceptor.SearchPreferHandlingInterceptor; import ca.uhn.fhir.rest.server.interceptor.StaticCapabilityStatementInterceptor; import ca.uhn.fhir.validation.ResultSeverityEnum; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; import org.hl7.fhir.common.hapi.validation.validator.FhirInstanceValidator; import org.hl7.fhir.r4.model.CapabilityStatement; import org.hl7.fhir.r4.model.Enumerations; import org.springframework.web.cors.CorsConfiguration; import java.util.Arrays; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; @SuppressWarnings({"serial", "RedundantThrows", "InnerClassMayBeStatic"}) public class ServletExamples { diff --git a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ValidatorExamples.java b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ValidatorExamples.java index d75bd9d5064..7fa54099747 100644 --- a/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ValidatorExamples.java +++ b/hapi-fhir-docs/src/main/java/ca/uhn/hapi/fhir/docs/ValidatorExamples.java @@ -36,6 +36,7 @@ import ca.uhn.fhir.validation.SchemaBaseValidator; import ca.uhn.fhir.validation.SingleValidationMessage; import ca.uhn.fhir.validation.ValidationResult; import ca.uhn.fhir.validation.schematron.SchematronBaseValidator; +import jakarta.servlet.ServletException; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.hl7.fhir.common.hapi.validation.support.CachingValidationSupport; @@ -60,7 +61,6 @@ import java.io.File; import java.io.FileReader; import java.util.List; import javax.annotation.Nonnull; -import javax.servlet.ServletException; @SuppressWarnings({"serial", "unused"}) public class ValidatorExamples { diff --git a/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/changelog/7_0_0/changes.yaml b/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/changelog/7_0_0/changes.yaml index e69de29bb2d..891e4962f07 100644 --- a/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/changelog/7_0_0/changes.yaml +++ b/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/changelog/7_0_0/changes.yaml @@ -0,0 +1,25 @@ +--- +- item: + type: "add" + title: "The version of a few dependencies have been bumped to the latest versions + (dependent HAPI modules listed in brackets): +
      +
    • Spring Framework (JPA): 5.3.27 -> 6.0.12
    • +
    • Spring Data BOM (JPA): 2021.2.2 -> 2023.0.0
    • +
    • Hibernate (JPA): 5.6.15.Final -> 6.2.8.Final
    • +
    • Hibernate Validator (JPA): 6.1.5.Final -> 8.0.0.Final
    • +
    • Hibernate Search (JPA): 6.1.6.Final -> 6.2.1.Final
    • +
    • Spring Boot (Boot+Starter): 2.7.12 -> 3.1.4
    • +
    • Jetty (CLI): 10.0.14 -> 12.0.2
    • +
    • Phloc Schematron (Schematron Validator): 5.6.5 -> 7.1.2
    • +
    • RestEasy (JAX-RS Server): 5.0.2.Final -> 6.2.5.Final
    • +
    " +- item: + type: "change" + title: "HAPI FHIR JPA now requires PostgreSQL 10+. Previously Postgres 9.4 + was supported but this version has been dropped." +- item: + type: "remove" + title: "The legacy `$lastn` support has been removed, and only the redesigned 'advanced' version is now + supported. The advanced version requires Elasticsearch." + diff --git a/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/database_support.md b/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/database_support.md index 5b5a473f744..763682c55ff 100644 --- a/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/database_support.md +++ b/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/database_support.md @@ -1,19 +1,20 @@ # Database Support -HAPI FHIR JPA Server maintains active support for several databases: +HAPI FHIR JPA Server maintains active support for several databases. -- [MS SQL Server](https://www.microsoft.com/en-us/sql-server/sql-server-2019) -- [PostgreSQL](https://www.postgresql.org/) -- [Oracle](https://www.oracle.com/ca-en/database/12c-database/) +The supported databases are regularly tested for ongoing compliance and performance, and HAPI FHIR has specific performance optimizations for each platform. Make sure to use the HAPI FHIR dialect class as opposed to the default hibernate dialect class. -Use of any of the above databases is fully supported by HAPI-FHIR, and code is actively written to work with them. +| Database | Status | Hibernate Dialect Class | Notes | +|-----------------------------------------------------------------------------|---------------|----------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------| +| [MS SQL Server](https://www.microsoft.com/en-us/sql-server/sql-server-2019) | **Supported** | `ca.uhn.fhir.jpa.model.dialect.HapiFhirH2Dialect` | | +| [PostgreSQL](https://www.postgresql.org/) | **Supported** | `ca.uhn.fhir.jpa.model.dialect.HapiFhirPostgresDialect` | | +| [Oracle](https://www.oracle.com/ca-en/database/12c-database/) | **Supported** | `ca.uhn.fhir.jpa.model.dialect.HapiFhirOracleDialect` | | +| [Cockroach DB](https://www.cockroachlabs.com/) | Experimental | `ca.uhn.fhir.jpa.model.dialect.HapiFhirCockroachDialect` | A CockroachDB dialect was contributed by a HAPI FHIR community member. This dialect is not regularly tested, use with caution. | +| MySQL | Deprecated | `ca.uhn.fhir.jpa.model.dialect.HapiFhirMySQLDialect` | MySQL and MariaDB exhibit poor performance with HAPI FHIR and have therefore been deprecated. These databases should not be used. | +| MariaDB | Deprecated | `ca.uhn.fhir.jpa.model.dialect.HapiFhirMariaDBDialect` | MySQL and MariaDB exhibit poor performance with HAPI FHIR and have therefore been deprecated. These databases should not be used. | # Experimental Support -HAPI FHIR currently provides experimental for the following databases, but does not actively support them, or write code specifically to work with them: - -- [Cockroach DB](https://www.cockroachlabs.com/) - HAPI FHIR uses the Hibernate ORM to provide database abstraction. This means that HAPI FHIR could theoretically also work on other databases supported by Hibernate. For example, although we do not regularly test or validate on other platforms, community members have reported successfully running HAPI FHIR on: @@ -21,9 +22,3 @@ For example, although we do not regularly test or validate on other platforms, c - Cache - Firebird -# Deprecated Support - -These databases were previously supported by HAPI FHIR JPA Server, but have since been deprecated, and should not be used. - -- [MySQL](https://www.mysql.com/) - diff --git a/hapi-fhir-jacoco/pom.xml b/hapi-fhir-jacoco/pom.xml index 47c0a8dc304..a1ae5cb4b1e 100644 --- a/hapi-fhir-jacoco/pom.xml +++ b/hapi-fhir-jacoco/pom.xml @@ -11,7 +11,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-jaxrsserver-base/pom.xml b/hapi-fhir-jaxrsserver-base/pom.xml index e4b20f53161..8b55c6e27ac 100644 --- a/hapi-fhir-jaxrsserver-base/pom.xml +++ b/hapi-fhir-jaxrsserver-base/pom.xml @@ -4,7 +4,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -74,20 +74,22 @@
    - javax.ejb - ejb-api - provided + jakarta.ejb + jakarta.ejb-api - javax.servlet - javax.servlet-api - provided + jakarta.servlet + jakarta.servlet-api - org.jboss.spec.javax.ws.rs - jboss-jaxrs-api_2.1_spec - provided + jakarta.ws.rs + jakarta.ws.rs-api + + jakarta.interceptor + jakarta.interceptor-api + + org.springframework spring-context @@ -109,11 +111,6 @@ jetty-server test - - org.eclipse.jetty - jetty-servlet - test - ca.uhn.hapi.fhir hapi-fhir-test-utilities diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpClient.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpClient.java index 8ea09b92709..5e1e2569665 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpClient.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpClient.java @@ -29,20 +29,20 @@ import ca.uhn.fhir.rest.client.api.IHttpClient; import ca.uhn.fhir.rest.client.api.IHttpRequest; import ca.uhn.fhir.rest.client.impl.BaseHttpClientInvocation; import ca.uhn.fhir.rest.client.method.MethodUtil; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation.Builder; +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; import org.hl7.fhir.instance.model.api.IBaseBinary; import java.util.List; import java.util.Map; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation.Builder; -import javax.ws.rs.core.Form; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; /** * A Http Request based on JaxRs. This is an adapter around the class - * {@link javax.ws.rs.client.Client Client} + * {@link jakarta.ws.rs.client.Client Client} * * @author Peter Van Houte | peter.vanhoute@agfa.com | Agfa Healthcare */ diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpRequest.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpRequest.java index 94f03508eed..844e46b81cf 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpRequest.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpRequest.java @@ -25,19 +25,19 @@ import ca.uhn.fhir.rest.client.api.BaseHttpRequest; import ca.uhn.fhir.rest.client.api.IHttpRequest; import ca.uhn.fhir.rest.client.api.IHttpResponse; import ca.uhn.fhir.util.StopWatch; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.Response; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.Response; /** * A Http Request based on JaxRs. This is an adapter around the class - * {@link javax.ws.rs.client.Invocation Invocation} + * {@link jakarta.ws.rs.client.Invocation Invocation} * * @author Peter Van Houte | peter.vanhoute@agfa.com | Agfa Healthcare */ diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpResponse.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpResponse.java index 1522d5007d3..4599ee9e1b3 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpResponse.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsHttpResponse.java @@ -22,17 +22,17 @@ package ca.uhn.fhir.jaxrs.client; import ca.uhn.fhir.rest.client.api.IHttpResponse; import ca.uhn.fhir.rest.client.impl.BaseHttpResponse; import ca.uhn.fhir.util.StopWatch; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import java.io.*; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; /** - * A Http Response based on JaxRs. This is an adapter around the class {@link javax.ws.rs.core.Response Response} + * A Http Response based on JaxRs. This is an adapter around the class {@link jakarta.ws.rs.core.Response Response} * @author Peter Van Houte | peter.vanhoute@agfa.com | Agfa Healthcare */ public class JaxRsHttpResponse extends BaseHttpResponse implements IHttpResponse { diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsRestfulClientFactory.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsRestfulClientFactory.java index 68084615474..fc5788fa903 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsRestfulClientFactory.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/client/JaxRsRestfulClientFactory.java @@ -25,11 +25,11 @@ import ca.uhn.fhir.rest.api.RequestTypeEnum; import ca.uhn.fhir.rest.client.api.Header; import ca.uhn.fhir.rest.client.api.IHttpClient; import ca.uhn.fhir.rest.client.impl.RestfulClientFactory; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; import java.util.List; import java.util.Map; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; /** * A Restful Client Factory, based on Jax Rs @@ -97,7 +97,7 @@ public class JaxRsRestfulClientFactory extends RestfulClientFactory { } /** - * Only accept clients of type javax.ws.rs.client.Client + * Only accept clients of type jakarta.ws.rs.client.Client * Can be used to set a specific Client implementation * @param theHttpClient */ diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsBundleProvider.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsBundleProvider.java index fc00b175fd6..27fc15d6f9f 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsBundleProvider.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsBundleProvider.java @@ -25,21 +25,25 @@ import ca.uhn.fhir.jaxrs.server.interceptor.JaxRsExceptionInterceptor; import ca.uhn.fhir.jaxrs.server.util.JaxRsMethodBindings; import ca.uhn.fhir.jaxrs.server.util.JaxRsRequest; import ca.uhn.fhir.jaxrs.server.util.JaxRsRequest.Builder; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.RequestTypeEnum; +import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.api.server.IRestfulServer; -import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.server.IPagingProvider; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor; import ca.uhn.fhir.rest.server.method.BaseMethodBinding; +import jakarta.interceptor.Interceptors; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import java.io.IOException; import java.util.Collections; import java.util.List; -import javax.interceptor.Interceptors; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.*; /** * This server is the abstract superclass for all bundle providers. It exposes diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProvider.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProvider.java index 5208fe2e03f..926794f41cf 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProvider.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProvider.java @@ -40,6 +40,12 @@ import ca.uhn.fhir.rest.server.RestfulServerUtils; import ca.uhn.fhir.rest.server.method.BaseMethodBinding; import ca.uhn.fhir.rest.server.provider.ServerCapabilityStatementProvider; import ca.uhn.fhir.util.ReflectionUtil; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.OPTIONS; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.dstu2.hapi.rest.server.ServerConformanceProvider; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -59,12 +65,6 @@ import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import javax.ws.rs.GET; -import javax.ws.rs.OPTIONS; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; /** * This is the conformance provider for the jax rs servers. It requires all providers to be registered during startup because the conformance profile is generated during the postconstruct phase. diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsPageProvider.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsPageProvider.java index 86626914d35..133791e8c63 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsPageProvider.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsPageProvider.java @@ -30,14 +30,14 @@ import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.server.IPagingProvider; import ca.uhn.fhir.rest.server.PageProvider; import ca.uhn.fhir.rest.server.method.PageMethodBinding; +import jakarta.interceptor.Interceptors; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import java.io.IOException; -import javax.interceptor.Interceptors; -import javax.ws.rs.GET; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; /** * Base class for a provider to provide the [baseUrl]?_getpages=foo request, which is a request to the diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsProvider.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsProvider.java index 6d3e3b17cd2..b297ee90daa 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsProvider.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsProvider.java @@ -29,16 +29,16 @@ import ca.uhn.fhir.jaxrs.server.util.JaxRsRequest.Builder; import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor; import ca.uhn.fhir.rest.server.*; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.util.Map.Entry; import java.util.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; /** * This is the abstract superclass for all jaxrs providers. It contains some defaults implementing @@ -103,7 +103,7 @@ public abstract class AbstractJaxRsProvider implements IRestfulServerDefaults { /** * This method returns the server base, independent of the request or resource. * - * @see javax.ws.rs.core.UriInfo#getBaseUri() + * @see jakarta.ws.rs.core.UriInfo#getBaseUri() * @return the ascii string for the server base */ public String getBaseForServer() { diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProvider.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProvider.java index ebb634294af..5feb325154e 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProvider.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProvider.java @@ -30,14 +30,21 @@ import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.server.IPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.method.BaseMethodBinding; +import jakarta.interceptor.Interceptors; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import org.hl7.fhir.instance.model.api.IBaseResource; import java.io.IOException; import java.net.URL; -import javax.interceptor.Interceptors; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.*; /** * This server is the abstract superclass for all resource providers. It exposes diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsExceptionInterceptor.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsExceptionInterceptor.java index 19b046cf2d9..f58be619bec 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsExceptionInterceptor.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsExceptionInterceptor.java @@ -24,12 +24,12 @@ import ca.uhn.fhir.jaxrs.server.util.JaxRsRequest; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.interceptor.ExceptionHandlingInterceptor; +import jakarta.interceptor.AroundInvoke; +import jakarta.interceptor.InvocationContext; +import jakarta.servlet.ServletException; +import jakarta.ws.rs.core.Response; import java.io.IOException; -import javax.interceptor.AroundInvoke; -import javax.interceptor.InvocationContext; -import javax.servlet.ServletException; -import javax.ws.rs.core.Response; /** * An interceptor that catches the jax-rs exceptions diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsResponseException.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsResponseException.java index 8b14284e530..14100369b86 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsResponseException.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsResponseException.java @@ -20,8 +20,7 @@ package ca.uhn.fhir.jaxrs.server.interceptor; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; - -import javax.ejb.ApplicationException; +import jakarta.ejb.ApplicationException; /** * A JEE wrapper exception that will not force a rollback. diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequest.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequest.java index 3fd75c52e6f..52a9177ffd5 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequest.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequest.java @@ -32,6 +32,8 @@ import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.method.ResourceParameter; import ca.uhn.fhir.util.UrlUtil; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; import org.apache.commons.lang3.StringUtils; import java.io.IOException; @@ -42,8 +44,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; /** * The JaxRsRequest is a jax-rs specific implementation of the RequestDetails. diff --git a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponse.java b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponse.java index 5d08b17f87e..94015f91c42 100644 --- a/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponse.java +++ b/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponse.java @@ -22,6 +22,8 @@ package ca.uhn.fhir.jaxrs.server.util; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.server.BaseRestfulResponse; import ca.uhn.fhir.util.IoUtil; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.ResponseBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; @@ -33,8 +35,6 @@ import java.io.Writer; import java.util.List; import java.util.Map.Entry; import javax.annotation.Nonnull; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/GenericJaxRsClientDstu2Test.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/GenericJaxRsClientDstu2Test.java index 4392426bc20..725c8268525 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/GenericJaxRsClientDstu2Test.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/GenericJaxRsClientDstu2Test.java @@ -27,38 +27,26 @@ import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.PreferReturnEnum; import ca.uhn.fhir.rest.api.SearchStyleEnum; import ca.uhn.fhir.rest.api.SummaryEnum; -import ca.uhn.fhir.rest.client.api.Header; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; import ca.uhn.fhir.rest.client.exceptions.InvalidResponseException; import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; import ca.uhn.fhir.rest.param.DateRangeParam; -import ca.uhn.fhir.test.utilities.JettyUtil; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import org.apache.commons.io.Charsets; +import ca.uhn.fhir.test.utilities.server.HttpServletExtension; +import ca.uhn.fhir.test.utilities.server.RequestCaptureServlet; import org.apache.commons.io.IOUtils; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.instance.model.api.IBaseOperationOutcome; import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; +import org.junit.jupiter.api.extension.RegisterExtension; + import java.util.ArrayList; import java.util.Date; -import java.util.Enumeration; import java.util.List; -import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -73,23 +61,15 @@ import static org.junit.jupiter.api.Assertions.fail; public class GenericJaxRsClientDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(GenericJaxRsClientDstu2Test.class); - private static FhirContext ourCtx; - private static int ourPort; - private static Server ourServer; - private static int ourResponseCount = 0; - private static String[] ourResponseBodies; - private static String ourResponseBody; - private static String ourResponseContentType; - private static int ourResponseStatus; - private static String ourRequestUri; - private static List ourRequestUriAll; - private static String ourRequestMethod; - private static String ourRequestContentType; - private static byte[] ourRequestBodyBytes; - private static String ourRequestBodyString; - private static ArrayListMultimap ourRequestHeaders; - private static List> ourRequestHeadersAll; - private static Map ourRequestFirstHeaders; + + private static final FhirContext ourCtx = FhirContext.forDstu2(); + + private static final RequestCaptureServlet CAPTURE_SERVLET = new RequestCaptureServlet(); + + @RegisterExtension + public static final HttpServletExtension ourServer = new HttpServletExtension() + .withServlet(CAPTURE_SERVLET) + .keepAliveBetweenTests(); @BeforeEach public void before() { @@ -97,7 +77,7 @@ public class GenericJaxRsClientDstu2Test { clientFactory.setServerValidationMode(ServerValidationModeEnum.NEVER); ourCtx.setRestfulClientFactory(clientFactory); - ourResponseCount = 0; + CAPTURE_SERVLET.reset(); } private String getPatientFeedWithOneResult() { @@ -129,28 +109,28 @@ public class GenericJaxRsClientDstu2Test { conf.setCopyright("COPY"); final String respString = p.encodeResourceToString(conf); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.fetchConformance().ofType(Conformance.class).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata", ourRequestUri); - assertEquals(1, ourRequestHeaders.get("Accept").size()); - assertThat(ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata", CAPTURE_SERVLET.ourRequestUri); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get("Accept").size()); + assertThat(CAPTURE_SERVLET.ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); client.fetchConformance().ofType(Conformance.class).encodedJson().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata?_format=json", ourRequestUri); - assertEquals(1, ourRequestHeaders.get("Accept").size()); - assertThat(ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata?_format=json", CAPTURE_SERVLET.ourRequestUri); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get("Accept").size()); + assertThat(CAPTURE_SERVLET.ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); client.fetchConformance().ofType(Conformance.class).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata?_format=xml", ourRequestUri); - assertEquals(1, ourRequestHeaders.get("Accept").size()); - assertThat(ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata?_format=xml", CAPTURE_SERVLET.ourRequestUri); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get("Accept").size()); + assertThat(CAPTURE_SERVLET.ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); } @@ -164,24 +144,24 @@ public class GenericJaxRsClientDstu2Test { final Patient patient = new Patient(); patient.addName().addFamily("FAMILY"); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient resp = client.read(Patient.class, new IdDt("123")); assertEquals("FAMILY", resp.getName().get(0).getFamily().get(0).getValue()); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata", ourRequestUriAll.get(0)); - assertEquals(1, ourRequestHeadersAll.get(0).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUriAll.get(1)); - assertEquals(1, ourRequestHeadersAll.get(1).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata", CAPTURE_SERVLET.ourRequestUriAll.get(0)); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeadersAll.get(0).get("Accept").size()); + assertThat(CAPTURE_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); + assertThat(CAPTURE_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); + assertThat(CAPTURE_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", CAPTURE_SERVLET.ourRequestUriAll.get(1)); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeadersAll.get(1).get("Accept").size()); + assertThat(CAPTURE_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY)); + assertThat(CAPTURE_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); + assertThat(CAPTURE_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); } @Test @@ -194,23 +174,23 @@ public class GenericJaxRsClientDstu2Test { final Patient patient = new Patient(); patient.addName().addFamily("FAMILY"); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.setEncoding(EncodingEnum.JSON); Patient resp = client.read(Patient.class, new IdDt("123")); assertEquals("FAMILY", resp.getName().get(0).getFamily().get(0).getValue()); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata?_format=json", ourRequestUriAll.get(0)); - assertEquals(1, ourRequestHeadersAll.get(0).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_format=json", ourRequestUriAll.get(1)); - assertEquals(1, ourRequestHeadersAll.get(1).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata?_format=json", CAPTURE_SERVLET.ourRequestUriAll.get(0)); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeadersAll.get(0).get("Accept").size()); + assertThat(CAPTURE_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertThat(CAPTURE_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_format=json", CAPTURE_SERVLET.ourRequestUriAll.get(1)); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeadersAll.get(1).get("Accept").size()); + assertThat(CAPTURE_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertThat(CAPTURE_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); } @Test @@ -223,16 +203,16 @@ public class GenericJaxRsClientDstu2Test { final String respString = p.encodeResourceToString(conf); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Conformance resp = client.capabilities().ofType(Conformance.class).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata", CAPTURE_SERVLET.ourRequestUri); assertEquals("COPY", resp.getCopyright()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", CAPTURE_SERVLET.ourRequestMethod); } @@ -245,7 +225,7 @@ public class GenericJaxRsClientDstu2Test { ourCtx.setRestfulClientFactory(clientFactory); try { - ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); fail(); } catch (IllegalStateException e) { assertEquals(Msg.code(1355) + "JaxRsRestfulClientFactory does not have FhirContext defined. This must be set via JaxRsRestfulClientFactory#setFhirContext(FhirContext)", e.getMessage()); @@ -254,7 +234,7 @@ public class GenericJaxRsClientDstu2Test { @Test public void testCreate() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); @@ -262,23 +242,23 @@ public class GenericJaxRsClientDstu2Test { client.create().resource(p).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", CAPTURE_SERVLET.ourRequestUri); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); p.setId("123"); client.create().resource(p).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - String body = ourRequestBodyString; + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + String body = CAPTURE_SERVLET.ourRequestBodyString; assertThat(body, containsString("")); assertThat(body, not(containsString("123"))); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("POST", ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", CAPTURE_SERVLET.ourRequestUri); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); } @@ -287,39 +267,39 @@ public class GenericJaxRsClientDstu2Test { public void testCreateConditional() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + CAPTURE_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().addFamily("FOOFAMILY"); client.create().resource(p).conditionalByUrl("Patient?name=foo").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", CAPTURE_SERVLET.ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); client.create().resource(p).conditionalByUrl("Patient?name=http://foo|bar").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar", ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", CAPTURE_SERVLET.ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar", CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); client.create().resource(p).conditional().where(Patient.NAME.matches().value("foo")).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", CAPTURE_SERVLET.ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); } @@ -328,22 +308,22 @@ public class GenericJaxRsClientDstu2Test { public void testCreatePrefer() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + CAPTURE_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().addFamily("FOOFAMILY"); client.create().resource(p).prefer(PreferReturnEnum.MINIMAL).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); client.create().resource(p).prefer(PreferReturnEnum.REPRESENTATION).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); } @@ -355,11 +335,11 @@ public class GenericJaxRsClientDstu2Test { final String formatted = ourCtx.newXmlParser().encodeResourceToString(p); - ourResponseStatus = Constants.STATUS_HTTP_200_OK; - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = formatted; + CAPTURE_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_200_OK; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = formatted; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); p = new Patient(); p.setId(new IdDt("1")); @@ -372,38 +352,38 @@ public class GenericJaxRsClientDstu2Test { @Test public void testDeleteConditional() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + CAPTURE_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.delete().resourceById(new IdDt("Patient/123")).execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUri); + assertEquals("DELETE", CAPTURE_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", CAPTURE_SERVLET.ourRequestUri); client.delete().resourceConditionalByUrl("Patient?name=foo").execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertEquals("DELETE", CAPTURE_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", CAPTURE_SERVLET.ourRequestUri); client.delete().resourceConditionalByType("Patient").where(Patient.NAME.matches().value("foo")).execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertEquals("DELETE", CAPTURE_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", CAPTURE_SERVLET.ourRequestUri); } @Test public void testDelete() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + CAPTURE_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.delete().resourceById(new IdDt("Patient/123")).execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUri); + assertEquals("DELETE", CAPTURE_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", CAPTURE_SERVLET.ourRequestUri); } @@ -412,10 +392,10 @@ public class GenericJaxRsClientDstu2Test { final String msg = getPatientFeedWithOneResult(); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle response; @@ -427,7 +407,7 @@ public class GenericJaxRsClientDstu2Test { .andReturnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/_history", CAPTURE_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); @@ -439,7 +419,7 @@ public class GenericJaxRsClientDstu2Test { .count(null) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/_history", CAPTURE_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); @@ -450,7 +430,7 @@ public class GenericJaxRsClientDstu2Test { .since(new InstantDt()) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/_history", CAPTURE_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); @@ -460,7 +440,7 @@ public class GenericJaxRsClientDstu2Test { .andReturnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/_history", CAPTURE_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); @@ -470,7 +450,7 @@ public class GenericJaxRsClientDstu2Test { .andReturnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/_history", CAPTURE_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); @@ -482,7 +462,7 @@ public class GenericJaxRsClientDstu2Test { .since(new InstantDt("2001-01-02T11:22:33Z")) .execute(); - assertThat(ourRequestUri, either(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123/_history?_since=2001-01-02T11:22:33Z&_count=123")).or(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123/_history?_count=123&_since=2001-01-02T11:22:33Z"))); + assertThat(CAPTURE_SERVLET.ourRequestUri, either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123/_history?_since=2001-01-02T11:22:33Z&_count=123")).or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123/_history?_count=123&_since=2001-01-02T11:22:33Z"))); assertEquals(1, response.getEntry().size()); @@ -493,7 +473,7 @@ public class GenericJaxRsClientDstu2Test { .since(new InstantDt("2001-01-02T11:22:33Z").getValue()) .execute(); - assertThat(ourRequestUri, containsString("_since=2001-01")); + assertThat(CAPTURE_SERVLET.ourRequestUri, containsString("_since=2001-01")); assertEquals(1, response.getEntry().size()); } @@ -508,10 +488,10 @@ public class GenericJaxRsClientDstu2Test { outParams.addParameter().setName("meta").setValue(new MetaDt().addProfile("urn:profile:out")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); MetaDt resp = client @@ -522,10 +502,10 @@ public class GenericJaxRsClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$meta-add", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$meta-add", CAPTURE_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("POST", ourRequestMethod); - assertEquals("", ourRequestBodyString); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); + assertEquals("", CAPTURE_SERVLET.ourRequestBodyString); } @@ -541,10 +521,10 @@ public class GenericJaxRsClientDstu2Test { outParams.addParameter().setName("meta").setValue(new MetaDt().addProfile("urn:profile:out")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); MetaDt resp = client @@ -553,9 +533,9 @@ public class GenericJaxRsClientDstu2Test { .fromServer() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$meta", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$meta", CAPTURE_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", CAPTURE_SERVLET.ourRequestMethod); resp = client @@ -564,9 +544,9 @@ public class GenericJaxRsClientDstu2Test { .fromType("Patient") .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$meta", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$meta", CAPTURE_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", CAPTURE_SERVLET.ourRequestMethod); resp = client @@ -575,9 +555,9 @@ public class GenericJaxRsClientDstu2Test { .fromResource(new IdDt("Patient/123")) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$meta", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$meta", CAPTURE_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", CAPTURE_SERVLET.ourRequestMethod); } @@ -597,10 +577,10 @@ public class GenericJaxRsClientDstu2Test { final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client @@ -611,9 +591,9 @@ public class GenericJaxRsClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", CAPTURE_SERVLET.ourRequestMethod); resp = client @@ -624,9 +604,9 @@ public class GenericJaxRsClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", CAPTURE_SERVLET.ourRequestMethod); resp = client @@ -637,9 +617,9 @@ public class GenericJaxRsClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", CAPTURE_SERVLET.ourRequestMethod); // @formatter:off @@ -651,7 +631,7 @@ public class GenericJaxRsClientDstu2Test { .useHttpGet() .execute(); // @formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", CAPTURE_SERVLET.ourRequestUri); } @@ -664,10 +644,10 @@ public class GenericJaxRsClientDstu2Test { outParams.addParameter().setValue(new StringDt("STRINGVALOUT2")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client @@ -678,9 +658,9 @@ public class GenericJaxRsClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", CAPTURE_SERVLET.ourRequestMethod); resp = client @@ -691,9 +671,9 @@ public class GenericJaxRsClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", CAPTURE_SERVLET.ourRequestMethod); resp = client @@ -704,9 +684,9 @@ public class GenericJaxRsClientDstu2Test { .useHttpGet() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", CAPTURE_SERVLET.ourRequestMethod); // @formatter:off @@ -718,18 +698,18 @@ public class GenericJaxRsClientDstu2Test { .useHttpGet() .execute(); // @formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); } @Test public void testOperationWithBundleResponseJson() { - ourResponseContentType = Constants.CT_FHIR_JSON; - final String respString = "{\n" + " \"resourceType\":\"Bundle\",\n" + " \"id\":\"8cef5f2a-0ba9-43a5-be26-c8dde9ff0e19\",\n" + " \"base\":\"http://localhost:" + ourPort + "/fhir\"\n" + "}"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON; + final String respString = "{\n" + " \"resourceType\":\"Bundle\",\n" + " \"id\":\"8cef5f2a-0ba9-43a5-be26-c8dde9ff0e19\",\n" + " \"base\":\"" + ourServer.getBaseUrl() + "/fhir\"\n" + "}"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.registerInterceptor(new LoggingInterceptor(true)); @@ -765,10 +745,10 @@ public class GenericJaxRsClientDstu2Test { outParams.setTotal(123); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client @@ -777,11 +757,11 @@ public class GenericJaxRsClientDstu2Test { .named("$SOMEOPERATION") .withParameters(inParams).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(CAPTURE_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); assertEquals(1, resp.getParameter().size()); assertEquals(ca.uhn.fhir.model.dstu2.resource.Bundle.class, resp.getParameter().get(0).getResource().getClass()); @@ -796,10 +776,10 @@ public class GenericJaxRsClientDstu2Test { outParams.addParameter().setValue(new StringDt("STRINGVALOUT2")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client @@ -811,12 +791,12 @@ public class GenericJaxRsClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals("POST", ourRequestMethod); - assertEquals("", (ourRequestBodyString)); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); + assertEquals("", (CAPTURE_SERVLET.ourRequestBodyString)); /* @@ -833,13 +813,13 @@ public class GenericJaxRsClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); assertEquals("", - (ourRequestBodyString)); + (CAPTURE_SERVLET.ourRequestBodyString)); /* @@ -856,21 +836,21 @@ public class GenericJaxRsClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); assertEquals( "", - (ourRequestBodyString)); + (CAPTURE_SERVLET.ourRequestBodyString)); } @Test public void testOperationWithInvalidParam() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); // Who knows what the heck this is! IBase weirdBase = new IBase() { @@ -928,10 +908,10 @@ public class GenericJaxRsClientDstu2Test { final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client @@ -944,7 +924,7 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/1/$validate-code?code=8495-4&system=http%3A%2F%2Floinc.org", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/1/$validate-code?code=8495-4&system=http%3A%2F%2Floinc.org", CAPTURE_SERVLET.ourRequestUri); client @@ -958,9 +938,9 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/1/$validate-code", ourRequestUri); - ourLog.info(ourRequestBodyString); - assertEquals("", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/1/$validate-code", CAPTURE_SERVLET.ourRequestUri); + ourLog.info(CAPTURE_SERVLET.ourRequestBodyString); + assertEquals("", CAPTURE_SERVLET.ourRequestBodyString); } @@ -979,10 +959,10 @@ public class GenericJaxRsClientDstu2Test { final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client @@ -991,12 +971,12 @@ public class GenericJaxRsClientDstu2Test { .named("$SOMEOPERATION") .withParameters(inParams).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(CAPTURE_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); resp = client @@ -1005,12 +985,12 @@ public class GenericJaxRsClientDstu2Test { .named("$SOMEOPERATION") .withParameters(inParams).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(CAPTURE_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); resp = client @@ -1021,17 +1001,17 @@ public class GenericJaxRsClientDstu2Test { .encodedXml() .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(CAPTURE_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); resp = client.operation().onInstance(new IdDt("http://foo.com/bar/baz/Patient/123/_history/22")).named("$SOMEOPERATION").withParameters(inParams).execute(); // @formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); } @@ -1048,10 +1028,10 @@ public class GenericJaxRsClientDstu2Test { final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Parameters resp = client @@ -1060,12 +1040,12 @@ public class GenericJaxRsClientDstu2Test { .named("$SOMEOPERATION") .withNoParameters(Parameters.class).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(CAPTURE_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); resp = client @@ -1074,12 +1054,12 @@ public class GenericJaxRsClientDstu2Test { .named("$SOMEOPERATION") .withNoParameters(Parameters.class).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(CAPTURE_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); resp = client @@ -1088,12 +1068,12 @@ public class GenericJaxRsClientDstu2Test { .named("$SOMEOPERATION") .withNoParameters(Parameters.class).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(CAPTURE_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); // @formatter:off @@ -1104,22 +1084,22 @@ public class GenericJaxRsClientDstu2Test { .withNoParameters(Parameters.class) .execute(); // @formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", CAPTURE_SERVLET.ourRequestUri); } @Test public void testPageNext() { - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = getPatientFeedWithOneResult(); + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = getPatientFeedWithOneResult(); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle(); - sourceBundle.getLinkOrCreate(IBaseBundle.LINK_PREV).setUrl("http://localhost:" + ourPort + "/fhir/prev"); - sourceBundle.getLinkOrCreate(IBaseBundle.LINK_NEXT).setUrl("http://localhost:" + ourPort + "/fhir/next"); + sourceBundle.getLinkOrCreate(IBaseBundle.LINK_PREV).setUrl(ourServer.getBaseUrl() + "/fhir/prev"); + sourceBundle.getLinkOrCreate(IBaseBundle.LINK_NEXT).setUrl(ourServer.getBaseUrl() + "/fhir/next"); ca.uhn.fhir.model.dstu2.resource.Bundle resp = client @@ -1129,14 +1109,14 @@ public class GenericJaxRsClientDstu2Test { assertEquals(1, resp.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/fhir/next", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/next", CAPTURE_SERVLET.ourRequestUri); } @Test public void testPageNextNoLink() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle(); try { @@ -1150,14 +1130,14 @@ public class GenericJaxRsClientDstu2Test { public void testPagePrev() { - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = getPatientFeedWithOneResult(); + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = getPatientFeedWithOneResult(); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle(); - sourceBundle.getLinkOrCreate("previous").setUrl("http://localhost:" + ourPort + "/fhir/prev"); + sourceBundle.getLinkOrCreate("previous").setUrl(ourServer.getBaseUrl() + "/fhir/prev"); ca.uhn.fhir.model.dstu2.resource.Bundle resp = client @@ -1167,7 +1147,7 @@ public class GenericJaxRsClientDstu2Test { assertEquals(1, resp.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/fhir/prev", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/prev", CAPTURE_SERVLET.ourRequestUri); /* @@ -1175,7 +1155,7 @@ public class GenericJaxRsClientDstu2Test { */ sourceBundle = new ca.uhn.fhir.model.dstu2.resource.Bundle(); - sourceBundle.getLinkOrCreate("prev").setUrl("http://localhost:" + ourPort + "/fhir/prev"); + sourceBundle.getLinkOrCreate("prev").setUrl(ourServer.getBaseUrl() + "/fhir/prev"); resp = client @@ -1185,7 +1165,7 @@ public class GenericJaxRsClientDstu2Test { assertEquals(1, resp.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/fhir/prev", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/prev", CAPTURE_SERVLET.ourRequestUri); } @@ -1197,16 +1177,16 @@ public class GenericJaxRsClientDstu2Test { patient.addName().addFamily("FAM"); final String respString = ourCtx.newXmlParser().encodeResourceToString(patient); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient response; - response = (Patient) client.read(new UriDt("http://localhost:" + ourPort + "/fhir/Patient/123")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUri); + response = (Patient) client.read(new UriDt(ourServer.getBaseUrl() + "/fhir/Patient/123")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", CAPTURE_SERVLET.ourRequestUri); assertEquals("FAM", response.getName().get(0).getFamily().get(0).getValue()); } @@ -1217,15 +1197,15 @@ public class GenericJaxRsClientDstu2Test { patient.addName().addFamily("FAM"); final String respString = ourCtx.newXmlParser().encodeResourceToString(patient); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient response; - response = client.read().resource(Patient.class).withUrl(new IdDt("http://localhost:" + ourPort + "/AAA/Patient/123")).execute(); - assertEquals("http://localhost:" + ourPort + "/AAA/Patient/123", ourRequestUri); + response = client.read().resource(Patient.class).withUrl(new IdDt(ourServer.getBaseUrl() + "/AAA/Patient/123")).execute(); + assertEquals(ourServer.getBaseUrl() + "/AAA/Patient/123", CAPTURE_SERVLET.ourRequestUri); assertEquals("FAM", response.getName().get(0).getFamily().get(0).getValue()); } @@ -1248,10 +1228,10 @@ public class GenericJaxRsClientDstu2Test { ""; - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = input; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = input; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle response; @@ -1269,10 +1249,10 @@ public class GenericJaxRsClientDstu2Test { String msg = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); IBaseResource response = client.read() .resource("Patient") @@ -1280,7 +1260,7 @@ public class GenericJaxRsClientDstu2Test { .elementsSubset("name", "identifier") .execute(); - assertThat(ourRequestUri, either(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123?_elements=name%2Cidentifier")).or(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123?_elements=identifier%2Cname"))); + assertThat(CAPTURE_SERVLET.ourRequestUri, either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123?_elements=name%2Cidentifier")).or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123?_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getClass()); } @@ -1290,11 +1270,11 @@ public class GenericJaxRsClientDstu2Test { String msg = "<>>>><<<<>"; - ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); try { @@ -1314,11 +1294,11 @@ public class GenericJaxRsClientDstu2Test { String msg = "
    HELP IM A DIV
    "; - ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient response = client.read() .resource(Patient.class) @@ -1326,7 +1306,7 @@ public class GenericJaxRsClientDstu2Test { .summaryMode(SummaryEnum.TEXT) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_summary=text", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_summary=text", CAPTURE_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getClass()); assertEquals("
    HELP IM A DIV
    ", response.getText().getDiv().getValueAsString()); @@ -1337,11 +1317,11 @@ public class GenericJaxRsClientDstu2Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() .forResource("Patient") @@ -1349,7 +1329,7 @@ public class GenericJaxRsClientDstu2Test { .returnBundle(Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=james", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=james", CAPTURE_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1360,19 +1340,19 @@ public class GenericJaxRsClientDstu2Test { final String msg = getPatientFeedWithOneResult(); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle response = client.search() - .byUrl("http://localhost:" + ourPort + "/AAA?name=http://foo|bar") + .byUrl(ourServer.getBaseUrl() + "/AAA?name=http://foo|bar") .encodedJson() .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/AAA?name=http%3A//foo%7Cbar&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/AAA?name=http%3A//foo%7Cbar&_format=json", CAPTURE_SERVLET.ourRequestUri); assertNotNull(response); @@ -1382,7 +1362,7 @@ public class GenericJaxRsClientDstu2Test { .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", CAPTURE_SERVLET.ourRequestUri); assertNotNull(response); @@ -1392,7 +1372,7 @@ public class GenericJaxRsClientDstu2Test { .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", CAPTURE_SERVLET.ourRequestUri); assertNotNull(response); @@ -1401,7 +1381,7 @@ public class GenericJaxRsClientDstu2Test { .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", CAPTURE_SERVLET.ourRequestUri); assertNotNull(response); @@ -1410,7 +1390,7 @@ public class GenericJaxRsClientDstu2Test { .returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class) .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", CAPTURE_SERVLET.ourRequestUri); assertNotNull(response); @@ -1429,11 +1409,11 @@ public class GenericJaxRsClientDstu2Test { String msg = IOUtils.toString(GenericJaxRsClientDstu2Test.class.getResourceAsStream("/bundle_orion.xml")); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle response = client.search() @@ -1458,11 +1438,11 @@ public class GenericJaxRsClientDstu2Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() @@ -1473,7 +1453,7 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertThat(ourRequestUri, either(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); + assertThat(CAPTURE_SERVLET.ourRequestUri, either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1483,11 +1463,11 @@ public class GenericJaxRsClientDstu2Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() @@ -1499,18 +1479,18 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/_search?_elements=identifier%2Cname", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/_search?_elements=identifier%2Cname", CAPTURE_SERVLET.ourRequestUri); - // assertThat(ourRequestUri, - // either(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); + // assertThat(MY_SERVLET.ourRequestUri, + // either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); - assertEquals("name=james", ourRequestBodyString); + assertEquals("name=james", CAPTURE_SERVLET.ourRequestBodyString); - assertEquals("application/x-www-form-urlencoded", ourRequestContentType.replace(";char", "; char").toLowerCase()); - assertEquals(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY, ourRequestFirstHeaders.get("Accept").getValue()); - assertThat(ourRequestFirstHeaders.get("User-Agent").getValue(), not(emptyString())); + assertEquals("application/x-www-form-urlencoded", CAPTURE_SERVLET.ourRequestContentType.replace(";char", "; char").toLowerCase()); + assertEquals(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_LEGACY, CAPTURE_SERVLET.ourRequestFirstHeaders.get("Accept").getValue()); + assertThat(CAPTURE_SERVLET.ourRequestFirstHeaders.get("User-Agent").getValue(), not(emptyString())); } @Test @@ -1518,11 +1498,11 @@ public class GenericJaxRsClientDstu2Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() @@ -1535,18 +1515,18 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertThat(ourRequestUri, containsString("http://localhost:" + ourPort + "/fhir/Patient/_search?")); - assertThat(ourRequestUri, containsString("_elements=identifier%2Cname")); + assertThat(CAPTURE_SERVLET.ourRequestUri, containsString(ourServer.getBaseUrl() + "/fhir/Patient/_search?")); + assertThat(CAPTURE_SERVLET.ourRequestUri, containsString("_elements=identifier%2Cname")); - // assertThat(ourRequestUri, - // either(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); + // assertThat(MY_SERVLET.ourRequestUri, + // either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); - assertEquals("name=james", ourRequestBodyString); + assertEquals("name=james", CAPTURE_SERVLET.ourRequestBodyString); - assertEquals("application/x-www-form-urlencoded", ourRequestContentType); - assertEquals(Constants.CT_FHIR_JSON, ourRequestFirstHeaders.get("Accept").getValue()); + assertEquals("application/x-www-form-urlencoded", CAPTURE_SERVLET.ourRequestContentType); + assertEquals(Constants.CT_FHIR_JSON, CAPTURE_SERVLET.ourRequestFirstHeaders.get("Accept").getValue()); } @Test @@ -1554,11 +1534,11 @@ public class GenericJaxRsClientDstu2Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() @@ -1569,7 +1549,7 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=james&_lastUpdated=ge2011-01-01&_lastUpdated=le2012-01-01", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_lastUpdated=ge2011-01-01&_lastUpdated=le2012-01-01", CAPTURE_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1579,11 +1559,11 @@ public class GenericJaxRsClientDstu2Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() @@ -1596,7 +1576,7 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?_security=system1%7Ccode1&_security=system2%7Ccode2&_profile=http%3A%2F%2Ffoo1&_profile=http%3A%2F%2Ffoo2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?_security=system1%7Ccode1&_security=system2%7Ccode2&_profile=http%3A%2F%2Ffoo1&_profile=http%3A%2F%2Ffoo2", CAPTURE_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1608,11 +1588,11 @@ public class GenericJaxRsClientDstu2Test { String msg = getPatientFeedWithOneResult(); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() @@ -1623,7 +1603,7 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", CAPTURE_SERVLET.ourRequestUri); } @@ -1632,11 +1612,11 @@ public class GenericJaxRsClientDstu2Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Bundle response = client.search() @@ -1647,7 +1627,7 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=james&_summary=false", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_summary=false", CAPTURE_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1661,12 +1641,12 @@ public class GenericJaxRsClientDstu2Test { String respString = ourCtx.newJsonParser().encodeResourceToString(resp); - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); - List input = new ArrayList(); + List input = new ArrayList<>(); Patient p1 = new Patient(); // No ID p1.addName().addFamily("PATIENT1"); @@ -1684,10 +1664,10 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir", CAPTURE_SERVLET.ourRequestUri); assertEquals(2, response.size()); - String requestString = ourRequestBodyString; + String requestString = CAPTURE_SERVLET.ourRequestBodyString; ca.uhn.fhir.model.dstu2.resource.Bundle requestBundle = ourCtx.newJsonParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, requestString); assertEquals(2, requestBundle.getEntry().size()); assertEquals("POST", requestBundle.getEntry().get(0).getRequest().getMethod()); @@ -1720,10 +1700,10 @@ public class GenericJaxRsClientDstu2Test { resp.addEntry().getResponse().setLocation("Patient/2/_history/2"); - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = reqString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = reqString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); String response = client.transaction() @@ -1731,9 +1711,9 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/", CAPTURE_SERVLET.ourRequestUri); assertThat(response, containsString("\"Bundle\"")); - assertEquals("application/json+fhir;charset=UTF-8", ourRequestFirstHeaders.get("Content-Type").getValue()); + assertEquals("application/json+fhir;charset=UTF-8", CAPTURE_SERVLET.ourRequestFirstHeaders.get("Content-Type").getValue()); response = client.transaction() @@ -1742,8 +1722,8 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/", ourRequestUri); - assertEquals("application/xml+fhir;charset=UTF-8", ourRequestFirstHeaders.get("Content-Type").getValue()); + assertEquals(ourServer.getBaseUrl() + "/fhir/", CAPTURE_SERVLET.ourRequestUri); + assertEquals("application/xml+fhir;charset=UTF-8", CAPTURE_SERVLET.ourRequestFirstHeaders.get("Content-Type").getValue()); } @@ -1756,10 +1736,10 @@ public class GenericJaxRsClientDstu2Test { String respString = ourCtx.newJsonParser().encodeResourceToString(resp); - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = respString; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); ca.uhn.fhir.model.dstu2.resource.Bundle input = new ca.uhn.fhir.model.dstu2.resource.Bundle(); @@ -1779,7 +1759,7 @@ public class GenericJaxRsClientDstu2Test { .execute(); - assertEquals("http://localhost:" + ourPort + "/fhir", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir", CAPTURE_SERVLET.ourRequestUri); assertEquals(2, response.getEntry().size()); assertEquals("Patient/1/_history/1", response.getEntry().get(0).getResponse().getLocation()); @@ -1790,52 +1770,52 @@ public class GenericJaxRsClientDstu2Test { public void testUpdateConditional() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + CAPTURE_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().addFamily("FOOFAMILY"); client.update().resource(p).conditionalByUrl("Patient?name=foo").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", CAPTURE_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", CAPTURE_SERVLET.ourRequestUri); client.update().resource(p).conditionalByUrl("Patient?name=http://foo|bar").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar", ourRequestUri); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", CAPTURE_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar", CAPTURE_SERVLET.ourRequestUri); client.update().resource(ourCtx.newXmlParser().encodeResourceToString(p)).conditionalByUrl("Patient?name=foo").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", CAPTURE_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", CAPTURE_SERVLET.ourRequestUri); client.update().resource(p).conditional().where(Patient.NAME.matches().value("foo")).and(Patient.ADDRESS.matches().value("AAA|BBB")).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", ourRequestUri); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", CAPTURE_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", CAPTURE_SERVLET.ourRequestUri); client.update().resource(ourCtx.newXmlParser().encodeResourceToString(p)).conditional().where(Patient.NAME.matches().value("foo")).and(Patient.ADDRESS.matches().value("AAA|BBB")).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", ourRequestUri); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", CAPTURE_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", CAPTURE_SERVLET.ourRequestUri); } @@ -1844,9 +1824,9 @@ public class GenericJaxRsClientDstu2Test { public void testUpdateNonFluent() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + CAPTURE_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.setEncoding(EncodingEnum.XML); @@ -1854,19 +1834,19 @@ public class GenericJaxRsClientDstu2Test { p.addName().addFamily("FOOFAMILY"); client.update(new IdDt("Patient/123"), p); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_format=xml", ourRequestUri); - assertEquals("PUT", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_format=xml", CAPTURE_SERVLET.ourRequestUri); + assertEquals("PUT", CAPTURE_SERVLET.ourRequestMethod); client.update("123", p); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_format=xml", ourRequestUri); - assertEquals("PUT", ourRequestMethod); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentType() + Constants.HEADER_SUFFIX_CT_UTF_8, CAPTURE_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_format=xml", CAPTURE_SERVLET.ourRequestUri); + assertEquals("PUT", CAPTURE_SERVLET.ourRequestMethod); } @@ -1874,9 +1854,9 @@ public class GenericJaxRsClientDstu2Test { public void testUpdatePrefer() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + CAPTURE_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); @@ -1884,13 +1864,13 @@ public class GenericJaxRsClientDstu2Test { p.addName().addFamily("FOOFAMILY"); client.update().resource(p).prefer(PreferReturnEnum.MINIMAL).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); client.update().resource(p).prefer(PreferReturnEnum.REPRESENTATION).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, CAPTURE_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); } @@ -1902,11 +1882,11 @@ public class GenericJaxRsClientDstu2Test { final String formatted = ourCtx.newXmlParser().encodeResourceToString(p); - ourResponseStatus = Constants.STATUS_HTTP_200_OK; - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = formatted; + CAPTURE_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_200_OK; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = formatted; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); p = new Patient(); p.setId(new IdDt("1")); @@ -1925,10 +1905,10 @@ public class GenericJaxRsClientDstu2Test { final String msg = ourCtx.newXmlParser().encodeResourceToString(oo); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().addGiven("GIVEN"); @@ -1937,33 +1917,33 @@ public class GenericJaxRsClientDstu2Test { MethodOutcome response; response = client.validate().resource(p).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertEquals("", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate", CAPTURE_SERVLET.ourRequestUri); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); + assertEquals("", CAPTURE_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); response = client.validate().resource(ourCtx.newXmlParser().encodeResourceToString(p)).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertEquals("", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate", CAPTURE_SERVLET.ourRequestUri); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); + assertEquals("", CAPTURE_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); response = client.validate().resource(ourCtx.newJsonParser().encodeResourceToString(p)).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertEquals("{\"resourceType\":\"Parameters\",\"parameter\":[{\"name\":\"resource\",\"resource\":{\"resourceType\":\"Patient\",\"name\":[{\"given\":[\"GIVEN\"]}]}}]}", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate", CAPTURE_SERVLET.ourRequestUri); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); + assertEquals("{\"resourceType\":\"Parameters\",\"parameter\":[{\"name\":\"resource\",\"resource\":{\"resourceType\":\"Patient\",\"name\":[{\"given\":[\"GIVEN\"]}]}}]}", CAPTURE_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); response = client.validate().resource(ourCtx.newJsonParser().encodeResourceToString(p)).prettyPrint().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate?_pretty=true", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertThat(ourRequestBodyString, containsString("\"resourceType\": \"Parameters\",\n")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate?_pretty=true", CAPTURE_SERVLET.ourRequestUri); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); + assertThat(CAPTURE_SERVLET.ourRequestBodyString, containsString("\"resourceType\": \"Parameters\",\n")); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); @@ -1975,10 +1955,10 @@ public class GenericJaxRsClientDstu2Test { oo.addIssue().setDiagnostics("FOOBAR"); final String msg = ourCtx.newXmlParser().encodeResourceToString(oo); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + CAPTURE_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + CAPTURE_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.setEncoding(EncodingEnum.XML); Patient p = new Patient(); @@ -1991,9 +1971,9 @@ public class GenericJaxRsClientDstu2Test { response = client.validate(p); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate?_format=xml", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertEquals("", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate?_format=xml", CAPTURE_SERVLET.ourRequestUri); + assertEquals("POST", CAPTURE_SERVLET.ourRequestMethod); + assertEquals("", CAPTURE_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssueFirstRep().getDiagnosticsElement().getValue()); @@ -2003,77 +1983,4 @@ public class GenericJaxRsClientDstu2Test { return (OperationOutcome) theOperationOutcome; } - @BeforeEach - public void beforeReset() { - ourRequestUri = null; - ourRequestUriAll = Lists.newArrayList(); - ourResponseStatus = 200; - ourResponseBody = null; - ourResponseBodies = null; - ourResponseCount = 0; - - ourResponseContentType = null; - ourRequestContentType = null; - ourRequestBodyBytes = null; - ourRequestBodyString = null; - ourRequestHeaders = null; - ourRequestFirstHeaders = null; - ourRequestMethod = null; - ourRequestHeadersAll = Lists.newArrayList(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu2(); - - ourServer = new Server(0); - ourServer.setHandler(new AbstractHandler() { - - @Override - public void handle(String theArg0, Request theRequest, HttpServletRequest theServletRequest, HttpServletResponse theResp) throws IOException { - theRequest.setHandled(true); - ourRequestUri = theRequest.getHttpURI().toString(); - ourRequestUriAll.add(ourRequestUri); - ourRequestMethod = theRequest.getMethod(); - ourRequestContentType = theServletRequest.getContentType(); - ourRequestBodyBytes = IOUtils.toByteArray(theServletRequest.getInputStream()); - ourRequestBodyString = new String(ourRequestBodyBytes, Charsets.UTF_8); - - ourRequestHeaders = ArrayListMultimap.create(); - ourRequestHeadersAll.add(ourRequestHeaders); - ourRequestFirstHeaders = Maps.newHashMap(); - - for (Enumeration headerNameEnum = theRequest.getHeaderNames(); headerNameEnum.hasMoreElements(); ) { - String nextName = headerNameEnum.nextElement(); - for (Enumeration headerValueEnum = theRequest.getHeaders(nextName); headerValueEnum.hasMoreElements(); ) { - String nextValue = headerValueEnum.nextElement(); - if (ourRequestFirstHeaders.containsKey(nextName) == false) { - ourRequestFirstHeaders.put(nextName, new Header(nextName, nextValue)); - } - ourRequestHeaders.put(nextName, new Header(nextName, nextValue)); - } - } - - theResp.setStatus(ourResponseStatus); - - if (ourResponseBody != null) { - theResp.setContentType(ourResponseContentType); - theResp.getWriter().write(ourResponseBody); - } else if (ourResponseBodies != null) { - theResp.setContentType(ourResponseContentType); - theResp.getWriter().write(ourResponseBodies[ourResponseCount]); - } - - ourResponseCount++; - } - }); - - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - } - - @AfterAll - public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } } diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/GenericJaxRsClientDstu3Test.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/GenericJaxRsClientDstu3Test.java index 40d7a62d37b..6826becadcd 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/GenericJaxRsClientDstu3Test.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/GenericJaxRsClientDstu3Test.java @@ -19,6 +19,8 @@ import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.system.HapiSystemProperties; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.HttpServletExtension; +import ca.uhn.fhir.test.utilities.server.RequestCaptureServlet; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -55,8 +57,10 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.extension.RegisterExtension; + import java.io.IOException; import java.util.ArrayList; import java.util.Date; @@ -77,23 +81,14 @@ import static org.junit.jupiter.api.Assertions.fail; public class GenericJaxRsClientDstu3Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(GenericJaxRsClientDstu3Test.class); - private static FhirContext ourCtx; - private static int ourPort; - private static Server ourServer; - private static int ourResponseCount = 0; - private static String[] ourResponseBodies; - private static String ourResponseBody; - private static String ourResponseContentType; - private static int ourResponseStatus; - private static String ourRequestUri; - private static List ourRequestUriAll; - private static String ourRequestMethod; - private static String ourRequestContentType; - private static byte[] ourRequestBodyBytes; - private static String ourRequestBodyString; - private static ArrayListMultimap ourRequestHeaders; - private static List> ourRequestHeadersAll; - private static Map ourRequestFirstHeaders; + private static final FhirContext ourCtx = FhirContext.forDstu3(); + + private static final RequestCaptureServlet MY_SERVLET = new RequestCaptureServlet(); + + @RegisterExtension + public static final HttpServletExtension ourServer = new HttpServletExtension() + .withServlet(MY_SERVLET) + .keepAliveBetweenTests(); @BeforeEach public void before() { @@ -101,7 +96,7 @@ public class GenericJaxRsClientDstu3Test { clientFactory.setServerValidationMode(ServerValidationModeEnum.NEVER); ourCtx.setRestfulClientFactory(clientFactory); - ourResponseCount = 0; + MY_SERVLET.reset(); HapiSystemProperties.enableHapiClientKeepResponses(); } @@ -134,28 +129,28 @@ public class GenericJaxRsClientDstu3Test { conf.setCopyright("COPY"); final String respString = p.encodeResourceToString(conf); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.fetchConformance().ofType(CapabilityStatement.class).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata", ourRequestUri); - assertEquals(1, ourRequestHeaders.get("Accept").size()); - assertThat(ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_NON_LEGACY)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata", MY_SERVLET.ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_NON_LEGACY)); client.fetchConformance().ofType(CapabilityStatement.class).encodedJson().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata?_format=json", ourRequestUri); - assertEquals(1, ourRequestHeaders.get("Accept").size()); - assertThat(ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata?_format=json", MY_SERVLET.ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); client.fetchConformance().ofType(CapabilityStatement.class).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata?_format=xml", ourRequestUri); - assertEquals(1, ourRequestHeaders.get("Accept").size()); - assertThat(ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata?_format=xml", MY_SERVLET.ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeaders.get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); } @@ -169,24 +164,24 @@ public class GenericJaxRsClientDstu3Test { final Patient patient = new Patient(); patient.addName().setFamily("FAMILY"); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient resp = client.read(Patient.class, new IdType("123").getValue()); assertEquals("FAMILY", resp.getName().get(0).getFamily()); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata", ourRequestUriAll.get(0)); - assertEquals(1, ourRequestHeadersAll.get(0).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_NON_LEGACY)); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUriAll.get(1)); - assertEquals(1, ourRequestHeadersAll.get(1).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_NON_LEGACY)); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata", MY_SERVLET.ourRequestUriAll.get(0)); + assertEquals(1, MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_NON_LEGACY)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", MY_SERVLET.ourRequestUriAll.get(1)); + assertEquals(1, MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_NON_LEGACY)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_XML)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); } @Test @@ -199,23 +194,23 @@ public class GenericJaxRsClientDstu3Test { final Patient patient = new Patient(); patient.addName().setFamily("FAMILY"); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBodies = new String[]{p.encodeResourceToString(conf), p.encodeResourceToString(patient)}; ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.setEncoding(EncodingEnum.JSON); Patient resp = client.read(Patient.class, new IdType("123").getValue()); assertEquals("FAMILY", resp.getName().get(0).getFamily()); - assertEquals("http://localhost:" + ourPort + "/fhir/metadata?_format=json", ourRequestUriAll.get(0)); - assertEquals(1, ourRequestHeadersAll.get(0).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); - assertThat(ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_format=json", ourRequestUriAll.get(1)); - assertEquals(1, ourRequestHeadersAll.get(1).get("Accept").size()); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); - assertThat(ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata?_format=json", MY_SERVLET.ourRequestUriAll.get(0)); + assertEquals(1, MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(0).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_format=json", MY_SERVLET.ourRequestUriAll.get(1)); + assertEquals(1, MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").size()); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), containsString(Constants.CT_FHIR_JSON)); + assertThat(MY_SERVLET.ourRequestHeadersAll.get(1).get("Accept").get(0).getValue(), not(containsString(Constants.CT_FHIR_XML))); } @Test @@ -227,19 +222,19 @@ public class GenericJaxRsClientDstu3Test { final String respString = p.encodeResourceToString(conf); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off CapabilityStatement resp = client.fetchConformance().ofType(CapabilityStatement.class).execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/metadata", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/metadata", MY_SERVLET.ourRequestUri); assertEquals("COPY", resp.getCopyright()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); } @@ -252,7 +247,7 @@ public class GenericJaxRsClientDstu3Test { ourCtx.setRestfulClientFactory(clientFactory); try { - ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); fail(); } catch (IllegalStateException e) { assertEquals(Msg.code(1355) + "JaxRsRestfulClientFactory does not have FhirContext defined. This must be set via JaxRsRestfulClientFactory#setFhirContext(FhirContext)", e.getMessage()); @@ -261,7 +256,7 @@ public class GenericJaxRsClientDstu3Test { @Test public void testCreate() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); @@ -269,23 +264,23 @@ public class GenericJaxRsClientDstu3Test { client.create().resource(p).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); p.setId("123"); client.create().resource(p).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - String body = ourRequestBodyString; + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + String body = MY_SERVLET.ourRequestBodyString; assertThat(body, containsString("")); assertThat(body, not(containsString("123"))); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("POST", ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); } @@ -294,48 +289,48 @@ public class GenericJaxRsClientDstu3Test { public void testCreateConditional() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().setFamily("FOOFAMILY"); client.create().resource(p).conditionalByUrl("Patient?name=foo").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", MY_SERVLET.ourRequestMethod); client.create().resource(p).conditionalByUrl("Patient?name=http://foo|bar").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar", ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar", MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", MY_SERVLET.ourRequestMethod); client.create().resource(p).conditional().where(Patient.NAME.matches().value("foo")).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_IF_NONE_EXIST).getValue()); + assertEquals("POST", MY_SERVLET.ourRequestMethod); } @Test public void testCreate2() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); @@ -343,11 +338,11 @@ public class GenericJaxRsClientDstu3Test { client.create().resource(p).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); } @@ -355,22 +350,22 @@ public class GenericJaxRsClientDstu3Test { public void testCreatePrefer() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().setFamily("FOOFAMILY"); client.create().resource(p).prefer(PreferReturnEnum.MINIMAL).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); client.create().resource(p).prefer(PreferReturnEnum.REPRESENTATION).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); } @@ -382,11 +377,11 @@ public class GenericJaxRsClientDstu3Test { final String formatted = ourCtx.newXmlParser().encodeResourceToString(p); - ourResponseStatus = Constants.STATUS_HTTP_200_OK; - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = formatted; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_200_OK; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = formatted; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); p = new Patient(); p.setId(new IdType("1")); @@ -399,24 +394,24 @@ public class GenericJaxRsClientDstu3Test { @Test public void testDeleteConditional() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.delete().resourceById(new IdType("Patient/123")).execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUri); + assertEquals("DELETE", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", MY_SERVLET.ourRequestUri); client.delete().resourceConditionalByUrl("Patient?name=foo").execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertEquals("DELETE", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestUri); client.delete().resourceConditionalByType("Patient").where(Patient.NAME.matches().value("foo")).execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertEquals("DELETE", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestUri); } @@ -424,14 +419,14 @@ public class GenericJaxRsClientDstu3Test { @SuppressWarnings("deprecation") @Test public void testDeleteNonFluent() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.delete().resourceById(new IdType("Patient/123")).execute(); - assertEquals("DELETE", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUri); + assertEquals("DELETE", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", MY_SERVLET.ourRequestUri); } @@ -440,10 +435,10 @@ public class GenericJaxRsClientDstu3Test { final String msg = getPatientFeedWithOneResult(); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); org.hl7.fhir.dstu3.model.Bundle response; @@ -454,7 +449,7 @@ public class GenericJaxRsClientDstu3Test { .andReturnBundle(org.hl7.fhir.dstu3.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/_history", MY_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); @@ -467,7 +462,7 @@ public class GenericJaxRsClientDstu3Test { .count(null) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/_history", MY_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); @@ -479,7 +474,7 @@ public class GenericJaxRsClientDstu3Test { .since(new InstantType()) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/_history", MY_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); @@ -490,7 +485,7 @@ public class GenericJaxRsClientDstu3Test { .andReturnBundle(org.hl7.fhir.dstu3.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/_history", MY_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); @@ -501,7 +496,7 @@ public class GenericJaxRsClientDstu3Test { .andReturnBundle(org.hl7.fhir.dstu3.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/_history", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/_history", MY_SERVLET.ourRequestUri); assertEquals(1, response.getEntry().size()); @@ -514,7 +509,7 @@ public class GenericJaxRsClientDstu3Test { .since(new InstantType("2001-01-02T11:22:33Z")) .execute(); //@formatter:on - assertThat(ourRequestUri, either(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123/_history?_since=2001-01-02T11:22:33Z&_count=123")).or(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123/_history?_count=123&_since=2001-01-02T11:22:33Z"))); + assertThat(MY_SERVLET.ourRequestUri, either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123/_history?_since=2001-01-02T11:22:33Z&_count=123")).or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123/_history?_count=123&_since=2001-01-02T11:22:33Z"))); assertEquals(1, response.getEntry().size()); @@ -526,7 +521,7 @@ public class GenericJaxRsClientDstu3Test { .since(new InstantType("2001-01-02T11:22:33Z").getValue()) .execute(); //@formatter:on - assertThat(ourRequestUri, containsString("_since=2001-01")); + assertThat(MY_SERVLET.ourRequestUri, containsString("_since=2001-01")); assertEquals(1, response.getEntry().size()); } @@ -541,10 +536,10 @@ public class GenericJaxRsClientDstu3Test { outParams.addParameter().setName("meta").setValue(new Meta().addProfile("urn:profile:out")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off @@ -556,10 +551,10 @@ public class GenericJaxRsClientDstu3Test { .encodedXml() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$meta-add", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$meta-add", MY_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("POST", ourRequestMethod); - assertEquals("", ourRequestBodyString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); + assertEquals("", MY_SERVLET.ourRequestBodyString); } @@ -575,10 +570,10 @@ public class GenericJaxRsClientDstu3Test { outParams.addParameter().setName("meta").setValue(new Meta().addProfile("urn:profile:out")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off @@ -588,9 +583,9 @@ public class GenericJaxRsClientDstu3Test { .fromServer() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/$meta", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$meta", MY_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); //@formatter:off @@ -600,9 +595,9 @@ public class GenericJaxRsClientDstu3Test { .fromType("Patient") .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$meta", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$meta", MY_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); //@formatter:off @@ -612,9 +607,9 @@ public class GenericJaxRsClientDstu3Test { .fromResource(new IdType("Patient/123")) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$meta", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$meta", MY_SERVLET.ourRequestUri); assertEquals("urn:profile:out", resp.getProfile().get(0).getValue()); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); } @@ -634,10 +629,10 @@ public class GenericJaxRsClientDstu3Test { final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off @@ -649,9 +644,9 @@ public class GenericJaxRsClientDstu3Test { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); //@formatter:off @@ -663,9 +658,9 @@ public class GenericJaxRsClientDstu3Test { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); //@formatter:off @@ -677,9 +672,9 @@ public class GenericJaxRsClientDstu3Test { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); // @formatter:off @@ -691,7 +686,7 @@ public class GenericJaxRsClientDstu3Test { .useHttpGet() .execute(); // @formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION?param1=STRINGVALIN1¶m1=STRINGVALIN1b¶m2=STRINGVALIN2", MY_SERVLET.ourRequestUri); } @@ -704,10 +699,10 @@ public class GenericJaxRsClientDstu3Test { outParams.addParameter().setValue(new StringType("STRINGVALOUT2")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off @@ -719,9 +714,9 @@ public class GenericJaxRsClientDstu3Test { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); //@formatter:off @@ -733,9 +728,9 @@ public class GenericJaxRsClientDstu3Test { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); //@formatter:off @@ -747,9 +742,9 @@ public class GenericJaxRsClientDstu3Test { .useHttpGet() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals("GET", ourRequestMethod); + assertEquals("GET", MY_SERVLET.ourRequestMethod); // @formatter:off @@ -761,18 +756,18 @@ public class GenericJaxRsClientDstu3Test { .useHttpGet() .execute(); // @formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); } @Test public void testOperationWithBundleResponseJson() { - ourResponseContentType = Constants.CT_FHIR_JSON; - final String respString = "{\n" + " \"resourceType\":\"Bundle\",\n" + " \"id\":\"8cef5f2a-0ba9-43a5-be26-c8dde9ff0e19\",\n" + " \"base\":\"http://localhost:" + ourPort + "/fhir\"\n" + "}"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON; + final String respString = "{\n" + " \"resourceType\":\"Bundle\",\n" + " \"id\":\"8cef5f2a-0ba9-43a5-be26-c8dde9ff0e19\",\n" + " \"base\":\"" + ourServer.getBaseUrl() + "/fhir\"\n" + "}"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.registerInterceptor(new LoggingInterceptor(true)); @@ -808,10 +803,10 @@ public class GenericJaxRsClientDstu3Test { outParams.setTotal(123); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off @@ -823,11 +818,11 @@ public class GenericJaxRsClientDstu3Test { .encodedXml() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals(1, resp.getParameter().size()); assertEquals(org.hl7.fhir.dstu3.model.Bundle.class, resp.getParameter().get(0).getResource().getClass()); @@ -842,10 +837,10 @@ public class GenericJaxRsClientDstu3Test { outParams.addParameter().setValue(new StringType("STRINGVALOUT2")); final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off @@ -858,12 +853,12 @@ public class GenericJaxRsClientDstu3Test { .encodedXml() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals("POST", ourRequestMethod); - assertEquals("", (ourRequestBodyString)); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals("POST", MY_SERVLET.ourRequestMethod); + assertEquals("", (MY_SERVLET.ourRequestBodyString)); /* @@ -880,13 +875,13 @@ public class GenericJaxRsClientDstu3Test { .encodedXml() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals("", - (ourRequestBodyString)); + (MY_SERVLET.ourRequestBodyString)); /* @@ -903,21 +898,21 @@ public class GenericJaxRsClientDstu3Test { .encodedXml() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals("POST", MY_SERVLET.ourRequestMethod); assertEquals( "", - (ourRequestBodyString)); + (MY_SERVLET.ourRequestBodyString)); } @Test public void testOperationWithInvalidParam() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); // Who knows what the heck this is! IBase weirdBase = new IBase() { @@ -974,10 +969,10 @@ public class GenericJaxRsClientDstu3Test { final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off @@ -991,7 +986,7 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:off - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/1/$validate-code?code=8495-4&system=http%3A%2F%2Floinc.org", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/1/$validate-code?code=8495-4&system=http%3A%2F%2Floinc.org", MY_SERVLET.ourRequestUri); //@formatter:off @@ -1005,9 +1000,9 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:off - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/1/$validate-code", ourRequestUri); - ourLog.info(ourRequestBodyString); - assertEquals("", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/1/$validate-code", MY_SERVLET.ourRequestUri); + ourLog.info(MY_SERVLET.ourRequestBodyString); + assertEquals("", MY_SERVLET.ourRequestBodyString); } @@ -1026,10 +1021,10 @@ public class GenericJaxRsClientDstu3Test { final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off @@ -1041,12 +1036,12 @@ public class GenericJaxRsClientDstu3Test { .encodedXml() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); //@formatter:off @@ -1058,12 +1053,12 @@ public class GenericJaxRsClientDstu3Test { .encodedXml() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); //@formatter:off @@ -1075,17 +1070,17 @@ public class GenericJaxRsClientDstu3Test { .encodedXml() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); resp = client.operation().onInstance(new IdType("http://foo.com/bar/baz/Patient/123/_history/22")).named("$SOMEOPERATION").withParameters(inParams).execute(); // @formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); } @@ -1102,10 +1097,10 @@ public class GenericJaxRsClientDstu3Test { final String respString = p.encodeResourceToString(outParams); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off @@ -1115,12 +1110,12 @@ public class GenericJaxRsClientDstu3Test { .named("$SOMEOPERATION") .withNoParameters(Parameters.class).encodedXml().execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); //@formatter:off @@ -1130,12 +1125,12 @@ public class GenericJaxRsClientDstu3Test { .named("$SOMEOPERATION") .withNoParameters(Parameters.class).encodedXml().execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); //@formatter:off @@ -1147,12 +1142,12 @@ public class GenericJaxRsClientDstu3Test { .encodedXml() .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); assertEquals(respString, p.encodeResourceToString(resp)); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertEquals(ourRequestBodyString, reqString); - assertEquals("POST", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertEquals(MY_SERVLET.ourRequestBodyString, reqString); + assertEquals("POST", MY_SERVLET.ourRequestMethod); // @formatter:off @@ -1163,22 +1158,22 @@ public class GenericJaxRsClientDstu3Test { .withNoParameters(Parameters.class) .execute(); // @formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123/$SOMEOPERATION", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123/$SOMEOPERATION", MY_SERVLET.ourRequestUri); } @Test public void testPageNext() { - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = getPatientFeedWithOneResult(); + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = getPatientFeedWithOneResult(); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); org.hl7.fhir.dstu3.model.Bundle sourceBundle = new org.hl7.fhir.dstu3.model.Bundle(); - sourceBundle.getLinkOrCreate(IBaseBundle.LINK_PREV).setUrl("http://localhost:" + ourPort + "/fhir/prev"); - sourceBundle.getLinkOrCreate(IBaseBundle.LINK_NEXT).setUrl("http://localhost:" + ourPort + "/fhir/next"); + sourceBundle.getLinkOrCreate(IBaseBundle.LINK_PREV).setUrl(ourServer.getBaseUrl() + "/fhir/prev"); + sourceBundle.getLinkOrCreate(IBaseBundle.LINK_NEXT).setUrl(ourServer.getBaseUrl() + "/fhir/next"); //@formatter:off org.hl7.fhir.dstu3.model.Bundle resp = client @@ -1188,14 +1183,14 @@ public class GenericJaxRsClientDstu3Test { //@formatter:on assertEquals(1, resp.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/fhir/next", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/next", MY_SERVLET.ourRequestUri); } @Test public void testPageNextNoLink() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); org.hl7.fhir.dstu3.model.Bundle sourceBundle = new org.hl7.fhir.dstu3.model.Bundle(); try { @@ -1209,14 +1204,14 @@ public class GenericJaxRsClientDstu3Test { public void testPagePrev() { - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = getPatientFeedWithOneResult(); + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = getPatientFeedWithOneResult(); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); org.hl7.fhir.dstu3.model.Bundle sourceBundle = new org.hl7.fhir.dstu3.model.Bundle(); - sourceBundle.getLinkOrCreate("previous").setUrl("http://localhost:" + ourPort + "/fhir/prev"); + sourceBundle.getLinkOrCreate("previous").setUrl(ourServer.getBaseUrl() + "/fhir/prev"); //@formatter:off org.hl7.fhir.dstu3.model.Bundle resp = client @@ -1226,7 +1221,7 @@ public class GenericJaxRsClientDstu3Test { //@formatter:on assertEquals(1, resp.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/fhir/prev", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/prev", MY_SERVLET.ourRequestUri); /* @@ -1234,7 +1229,7 @@ public class GenericJaxRsClientDstu3Test { */ sourceBundle = new org.hl7.fhir.dstu3.model.Bundle(); - sourceBundle.getLinkOrCreate("prev").setUrl("http://localhost:" + ourPort + "/fhir/prev"); + sourceBundle.getLinkOrCreate("prev").setUrl(ourServer.getBaseUrl() + "/fhir/prev"); //@formatter:off resp = client @@ -1244,7 +1239,7 @@ public class GenericJaxRsClientDstu3Test { //@formatter:on assertEquals(1, resp.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/fhir/prev", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/prev", MY_SERVLET.ourRequestUri); } @@ -1256,16 +1251,16 @@ public class GenericJaxRsClientDstu3Test { patient.addName().setFamily("FAM"); final String respString = ourCtx.newXmlParser().encodeResourceToString(patient); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient response; - response = (Patient) client.read(new UriDt("http://localhost:" + ourPort + "/fhir/Patient/123")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123", ourRequestUri); + response = (Patient) client.read(new UriDt(ourServer.getBaseUrl() + "/fhir/Patient/123")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123", MY_SERVLET.ourRequestUri); assertEquals("FAM", response.getName().get(0).getFamily()); } @@ -1276,15 +1271,15 @@ public class GenericJaxRsClientDstu3Test { patient.addName().setFamily("FAM"); final String respString = ourCtx.newXmlParser().encodeResourceToString(patient); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient response; - response = client.read().resource(Patient.class).withUrl(new IdType("http://localhost:" + ourPort + "/AAA/Patient/123")).execute(); - assertEquals("http://localhost:" + ourPort + "/AAA/Patient/123", ourRequestUri); + response = client.read().resource(Patient.class).withUrl(new IdType(ourServer.getBaseUrl() + "/AAA/Patient/123")).execute(); + assertEquals(ourServer.getBaseUrl() + "/AAA/Patient/123", MY_SERVLET.ourRequestUri); assertEquals("FAM", response.getName().get(0).getFamily()); } @@ -1308,10 +1303,10 @@ public class GenericJaxRsClientDstu3Test { //@formatter:on - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = input; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = input; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); org.hl7.fhir.dstu3.model.Bundle response; @@ -1331,10 +1326,10 @@ public class GenericJaxRsClientDstu3Test { String msg = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off IBaseResource response = client.read() @@ -1344,7 +1339,7 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertThat(ourRequestUri, either(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123?_elements=name%2Cidentifier")).or(equalTo("http://localhost:" + ourPort + "/fhir/Patient/123?_elements=identifier%2Cname"))); + assertThat(MY_SERVLET.ourRequestUri, either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123?_elements=name%2Cidentifier")).or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient/123?_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getClass()); } @@ -1354,11 +1349,11 @@ public class GenericJaxRsClientDstu3Test { String msg = "<>>>><<<<>"; - ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off try { @@ -1379,11 +1374,11 @@ public class GenericJaxRsClientDstu3Test { String msg = "
    HELP IM A DIV
    "; - ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_HTML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off Patient response = client.read() @@ -1393,7 +1388,7 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_summary=text", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_summary=text", MY_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getClass()); assertEquals("
    HELP IM A DIV
    ", response.getText().getDiv().getValueAsString()); @@ -1404,11 +1399,11 @@ public class GenericJaxRsClientDstu3Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off Bundle response = client.search() @@ -1418,7 +1413,7 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=james", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=james", MY_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1429,20 +1424,20 @@ public class GenericJaxRsClientDstu3Test { final String msg = getPatientFeedWithOneResult(); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off org.hl7.fhir.dstu3.model.Bundle response = client.search() - .byUrl("http://localhost:" + ourPort + "/AAA?name=http://foo|bar") + .byUrl(ourServer.getBaseUrl() + "/AAA?name=http://foo|bar") .encodedJson() .returnBundle(org.hl7.fhir.dstu3.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/AAA?name=http%3A//foo%7Cbar&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/AAA?name=http%3A//foo%7Cbar&_format=json", MY_SERVLET.ourRequestUri); assertNotNull(response); @@ -1453,7 +1448,7 @@ public class GenericJaxRsClientDstu3Test { .returnBundle(org.hl7.fhir.dstu3.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", MY_SERVLET.ourRequestUri); assertNotNull(response); @@ -1464,7 +1459,7 @@ public class GenericJaxRsClientDstu3Test { .returnBundle(org.hl7.fhir.dstu3.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar&_format=json", MY_SERVLET.ourRequestUri); assertNotNull(response); @@ -1474,7 +1469,7 @@ public class GenericJaxRsClientDstu3Test { .returnBundle(org.hl7.fhir.dstu3.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); assertNotNull(response); @@ -1484,7 +1479,7 @@ public class GenericJaxRsClientDstu3Test { .returnBundle(org.hl7.fhir.dstu3.model.Bundle.class) .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient", MY_SERVLET.ourRequestUri); assertNotNull(response); @@ -1503,11 +1498,11 @@ public class GenericJaxRsClientDstu3Test { String msg = IOUtils.toString(GenericJaxRsClientDstu3Test.class.getResourceAsStream("/bundle_orion.xml")); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off org.hl7.fhir.dstu3.model.Bundle response = client.search() @@ -1532,11 +1527,11 @@ public class GenericJaxRsClientDstu3Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off Bundle response = client.search() @@ -1547,7 +1542,7 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertThat(ourRequestUri, either(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); + assertThat(MY_SERVLET.ourRequestUri, either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1557,11 +1552,11 @@ public class GenericJaxRsClientDstu3Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off Bundle response = client.search() @@ -1573,18 +1568,18 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/_search?_elements=identifier%2Cname", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/_search?_elements=identifier%2Cname", MY_SERVLET.ourRequestUri); - // assertThat(ourRequestUri, - // either(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); + // assertThat(MY_SERVLET.ourRequestUri, + // either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); - assertEquals("name=james", ourRequestBodyString); + assertEquals("name=james", MY_SERVLET.ourRequestBodyString); - assertEquals("application/x-www-form-urlencoded", ourRequestContentType.replace(";char", "; char").toLowerCase()); - assertEquals(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_NON_LEGACY, ourRequestFirstHeaders.get("Accept").getValue()); - assertThat(ourRequestFirstHeaders.get("User-Agent").getValue(), not(emptyString())); + assertEquals("application/x-www-form-urlencoded", MY_SERVLET.ourRequestContentType.replace(";char", "; char").toLowerCase()); + assertEquals(Constants.HEADER_ACCEPT_VALUE_XML_OR_JSON_NON_LEGACY, MY_SERVLET.ourRequestFirstHeaders.get("Accept").getValue()); + assertThat(MY_SERVLET.ourRequestFirstHeaders.get("User-Agent").getValue(), not(emptyString())); } @Test @@ -1592,11 +1587,11 @@ public class GenericJaxRsClientDstu3Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off Bundle response = client.search() @@ -1609,18 +1604,18 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertThat(ourRequestUri, containsString("http://localhost:" + ourPort + "/fhir/Patient/_search?")); - assertThat(ourRequestUri, containsString("_elements=identifier%2Cname")); + assertThat(MY_SERVLET.ourRequestUri, containsString(ourServer.getBaseUrl() + "/fhir/Patient/_search?")); + assertThat(MY_SERVLET.ourRequestUri, containsString("_elements=identifier%2Cname")); - // assertThat(ourRequestUri, - // either(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo("http://localhost:" + ourPort + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); + // assertThat(MY_SERVLET.ourRequestUri, + // either(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=name%2Cidentifier")).or(equalTo(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_elements=identifier%2Cname"))); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); - assertEquals("name=james", ourRequestBodyString); + assertEquals("name=james", MY_SERVLET.ourRequestBodyString); - assertEquals("application/x-www-form-urlencoded", ourRequestContentType); - assertEquals(Constants.HEADER_ACCEPT_VALUE_JSON_NON_LEGACY, ourRequestFirstHeaders.get("Accept").getValue()); + assertEquals("application/x-www-form-urlencoded", MY_SERVLET.ourRequestContentType); + assertEquals(Constants.HEADER_ACCEPT_VALUE_JSON_NON_LEGACY, MY_SERVLET.ourRequestFirstHeaders.get("Accept").getValue()); } @Test @@ -1628,11 +1623,11 @@ public class GenericJaxRsClientDstu3Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off Bundle response = client.search() @@ -1643,7 +1638,7 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=james&_lastUpdated=ge2011-01-01&_lastUpdated=le2012-01-01", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_lastUpdated=ge2011-01-01&_lastUpdated=le2012-01-01", MY_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1653,11 +1648,11 @@ public class GenericJaxRsClientDstu3Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off Bundle response = client.search() @@ -1670,7 +1665,7 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?_security=system1%7Ccode1&_security=system2%7Ccode2&_profile=http%3A%2F%2Ffoo1&_profile=http%3A%2F%2Ffoo2", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?_security=system1%7Ccode1&_security=system2%7Ccode2&_profile=http%3A%2F%2Ffoo1&_profile=http%3A%2F%2Ffoo2", MY_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1682,11 +1677,11 @@ public class GenericJaxRsClientDstu3Test { String msg = getPatientFeedWithOneResult(); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off Bundle response = client.search() @@ -1697,7 +1692,7 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?_revinclude=Provenance%3Atarget&_format=json", MY_SERVLET.ourRequestUri); } @@ -1706,11 +1701,11 @@ public class GenericJaxRsClientDstu3Test { String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off Bundle response = client.search() @@ -1721,7 +1716,7 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=james&_summary=false", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=james&_summary=false", MY_SERVLET.ourRequestUri); assertEquals(Patient.class, response.getEntry().get(0).getResource().getClass()); } @@ -1735,10 +1730,10 @@ public class GenericJaxRsClientDstu3Test { String respString = ourCtx.newJsonParser().encodeResourceToString(resp); - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); List input = new ArrayList(); @@ -1758,10 +1753,10 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir", MY_SERVLET.ourRequestUri); assertEquals(2, response.size()); - String requestString = ourRequestBodyString; + String requestString = MY_SERVLET.ourRequestBodyString; org.hl7.fhir.dstu3.model.Bundle requestBundle = ourCtx.newJsonParser().parseResource(org.hl7.fhir.dstu3.model.Bundle.class, requestString); assertEquals(2, requestBundle.getEntry().size()); assertEquals(HTTPVerb.POST, requestBundle.getEntry().get(0).getRequest().getMethod()); @@ -1810,10 +1805,10 @@ public class GenericJaxRsClientDstu3Test { resp.addEntry().getResponse().setLocation("Patient/2/_history/2"); - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = reqString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = reqString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); //@formatter:off String response = client.transaction() @@ -1821,9 +1816,9 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir/", MY_SERVLET.ourRequestUri); assertThat(response, containsString("\"Bundle\"")); - assertEquals("application/fhir+json;charset=UTF-8", ourRequestFirstHeaders.get("Content-Type").getValue()); + assertEquals("application/fhir+json;charset=UTF-8", MY_SERVLET.ourRequestFirstHeaders.get("Content-Type").getValue()); //@formatter:off response = client.transaction() @@ -1832,8 +1827,8 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/", ourRequestUri); - assertEquals("application/fhir+xml;charset=UTF-8", ourRequestFirstHeaders.get("Content-Type").getValue()); + assertEquals(ourServer.getBaseUrl() + "/fhir/", MY_SERVLET.ourRequestUri); + assertEquals("application/fhir+xml;charset=UTF-8", MY_SERVLET.ourRequestFirstHeaders.get("Content-Type").getValue()); } @@ -1846,10 +1841,10 @@ public class GenericJaxRsClientDstu3Test { String respString = ourCtx.newJsonParser().encodeResourceToString(resp); - ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; - ourResponseBody = respString; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_JSON + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = respString; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); org.hl7.fhir.dstu3.model.Bundle input = new org.hl7.fhir.dstu3.model.Bundle(); @@ -1869,7 +1864,7 @@ public class GenericJaxRsClientDstu3Test { .execute(); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir", ourRequestUri); + assertEquals(ourServer.getBaseUrl() + "/fhir", MY_SERVLET.ourRequestUri); assertEquals(2, response.getEntry().size()); assertEquals("Patient/1/_history/1", response.getEntry().get(0).getResponse().getLocation()); @@ -1880,52 +1875,52 @@ public class GenericJaxRsClientDstu3Test { public void testUpdateConditional() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().setFamily("FOOFAMILY"); client.update().resource(p).conditionalByUrl("Patient?name=foo").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestUri); client.update().resource(p).conditionalByUrl("Patient?name=http://foo|bar").encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=http%3A//foo%7Cbar", ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=http%3A//foo%7Cbar", MY_SERVLET.ourRequestUri); client.update().resource(ourCtx.newXmlParser().encodeResourceToString(p)).conditionalByUrl("Patient?name=foo").execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo", ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo", MY_SERVLET.ourRequestUri); client.update().resource(p).conditional().where(Patient.NAME.matches().value("foo")).and(Patient.ADDRESS.matches().value("AAA|BBB")).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", MY_SERVLET.ourRequestUri); client.update().resource(ourCtx.newXmlParser().encodeResourceToString(p)).conditional().where(Patient.NAME.matches().value("foo")).and(Patient.ADDRESS.matches().value("AAA|BBB")).encodedXml().execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("PUT", ourRequestMethod); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", ourRequestUri); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient?name=foo&address=AAA%5C%7CBBB", MY_SERVLET.ourRequestUri); } @@ -1934,9 +1929,9 @@ public class GenericJaxRsClientDstu3Test { public void testUpdateNonFluent() { - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.setEncoding(EncodingEnum.XML); @@ -1944,29 +1939,27 @@ public class GenericJaxRsClientDstu3Test { p.addName().setFamily("FOOFAMILY"); client.update(new IdType("Patient/123").getValue(), p); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_format=xml", ourRequestUri); - assertEquals("PUT", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_format=xml", MY_SERVLET.ourRequestUri); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); client.update("123", p); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); - assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); - assertThat(ourRequestBodyString, containsString("")); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/123?_format=xml", ourRequestUri); - assertEquals("PUT", ourRequestMethod); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_CONTENT_TYPE).size()); + assertEquals(EncodingEnum.XML.getResourceContentTypeNonLegacy() + Constants.HEADER_SUFFIX_CT_UTF_8, MY_SERVLET.ourRequestFirstHeaders.get(Constants.HEADER_CONTENT_TYPE).getValue().replace(";char", "; char")); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/123?_format=xml", MY_SERVLET.ourRequestUri); + assertEquals("PUT", MY_SERVLET.ourRequestMethod); } @Test public void testUpdatePrefer() { + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - - ourResponseStatus = Constants.STATUS_HTTP_204_NO_CONTENT; - - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); @@ -1974,13 +1967,13 @@ public class GenericJaxRsClientDstu3Test { p.addName().setFamily("FOOFAMILY"); client.update().resource(p).prefer(PreferReturnEnum.MINIMAL).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_MINIMAL, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); client.update().resource(p).prefer(PreferReturnEnum.REPRESENTATION).execute(); - assertEquals(1, ourRequestHeaders.get(Constants.HEADER_PREFER).size()); - assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); + assertEquals(1, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).size()); + assertEquals(Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION, MY_SERVLET.ourRequestHeaders.get(Constants.HEADER_PREFER).get(0).getValue()); } @@ -1992,11 +1985,11 @@ public class GenericJaxRsClientDstu3Test { final String formatted = ourCtx.newXmlParser().encodeResourceToString(p); - ourResponseStatus = Constants.STATUS_HTTP_200_OK; - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = formatted; + MY_SERVLET.ourResponseStatus = Constants.STATUS_HTTP_200_OK; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = formatted; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); p = new Patient(); p.setId(new IdType("1")); @@ -2015,10 +2008,10 @@ public class GenericJaxRsClientDstu3Test { final String msg = ourCtx.newXmlParser().encodeResourceToString(oo); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); Patient p = new Patient(); p.addName().addGiven("GIVEN"); @@ -2027,33 +2020,33 @@ public class GenericJaxRsClientDstu3Test { MethodOutcome response; response = client.validate().resource(p).encodedXml().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertEquals("", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); + assertEquals("", MY_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssue().get(0).getDiagnosticsElement().getValue()); response = client.validate().resource(ourCtx.newXmlParser().encodeResourceToString(p)).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertEquals("", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); + assertEquals("", MY_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssue().get(0).getDiagnosticsElement().getValue()); response = client.validate().resource(ourCtx.newJsonParser().encodeResourceToString(p)).execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertEquals("{\"resourceType\":\"Parameters\",\"parameter\":[{\"name\":\"resource\",\"resource\":{\"resourceType\":\"Patient\",\"name\":[{\"given\":[\"GIVEN\"]}]}}]}", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); + assertEquals("{\"resourceType\":\"Parameters\",\"parameter\":[{\"name\":\"resource\",\"resource\":{\"resourceType\":\"Patient\",\"name\":[{\"given\":[\"GIVEN\"]}]}}]}", MY_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssue().get(0).getDiagnosticsElement().getValue()); response = client.validate().resource(ourCtx.newJsonParser().encodeResourceToString(p)).prettyPrint().execute(); - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate?_pretty=true", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertThat(ourRequestBodyString, containsString("\"resourceType\": \"Parameters\",\n")); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate?_pretty=true", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); + assertThat(MY_SERVLET.ourRequestBodyString, containsString("\"resourceType\": \"Parameters\",\n")); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", toOo(response.getOperationOutcome()).getIssue().get(0).getDiagnosticsElement().getValue()); @@ -2065,10 +2058,10 @@ public class GenericJaxRsClientDstu3Test { oo.addIssue().setDiagnostics("FOOBAR"); final String msg = ourCtx.newXmlParser().encodeResourceToString(oo); - ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; - ourResponseBody = msg; + MY_SERVLET.ourResponseContentType = Constants.CT_FHIR_XML + "; charset=UTF-8"; + MY_SERVLET.ourResponseBody = msg; - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/fhir"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/fhir"); client.setEncoding(EncodingEnum.XML); Patient p = new Patient(); @@ -2081,9 +2074,9 @@ public class GenericJaxRsClientDstu3Test { response = client.validate(p); //@formatter:on - assertEquals("http://localhost:" + ourPort + "/fhir/Patient/$validate?_format=xml", ourRequestUri); - assertEquals("POST", ourRequestMethod); - assertEquals("", ourRequestBodyString); + assertEquals(ourServer.getBaseUrl() + "/fhir/Patient/$validate?_format=xml", MY_SERVLET.ourRequestUri); + assertEquals("POST", MY_SERVLET.ourRequestMethod); + assertEquals("", MY_SERVLET.ourRequestBodyString); assertNotNull(response.getOperationOutcome()); assertEquals("FOOBAR", ((OperationOutcome) response.getOperationOutcome()).getIssue().get(0).getDiagnosticsElement().getValue()); @@ -2093,77 +2086,4 @@ public class GenericJaxRsClientDstu3Test { return (OperationOutcome) theOperationOutcome; } - @BeforeEach - public void beforeReset() { - ourRequestUri = null; - ourRequestUriAll = Lists.newArrayList(); - ourResponseStatus = 200; - ourResponseBody = null; - ourResponseBodies = null; - ourResponseCount = 0; - - ourResponseContentType = null; - ourRequestContentType = null; - ourRequestBodyBytes = null; - ourRequestBodyString = null; - ourRequestHeaders = null; - ourRequestFirstHeaders = null; - ourRequestMethod = null; - ourRequestHeadersAll = Lists.newArrayList(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu3(); - - ourServer = new Server(0); - ourServer.setHandler(new AbstractHandler() { - - @Override - public void handle(String theArg0, Request theRequest, HttpServletRequest theServletRequest, HttpServletResponse theResp) throws IOException { - theRequest.setHandled(true); - ourRequestUri = theRequest.getHttpURI().toString(); - ourRequestUriAll.add(ourRequestUri); - ourRequestMethod = theRequest.getMethod(); - ourRequestContentType = theServletRequest.getContentType(); - ourRequestBodyBytes = IOUtils.toByteArray(theServletRequest.getInputStream()); - ourRequestBodyString = new String(ourRequestBodyBytes, Charsets.UTF_8); - - ourRequestHeaders = ArrayListMultimap.create(); - ourRequestHeadersAll.add(ourRequestHeaders); - ourRequestFirstHeaders = Maps.newHashMap(); - - for (Enumeration headerNameEnum = theRequest.getHeaderNames(); headerNameEnum.hasMoreElements(); ) { - String nextName = headerNameEnum.nextElement(); - for (Enumeration headerValueEnum = theRequest.getHeaders(nextName); headerValueEnum.hasMoreElements(); ) { - String nextValue = headerValueEnum.nextElement(); - if (ourRequestFirstHeaders.containsKey(nextName) == false) { - ourRequestFirstHeaders.put(nextName, new Header(nextName, nextValue)); - } - ourRequestHeaders.put(nextName, new Header(nextName, nextValue)); - } - } - - theResp.setStatus(ourResponseStatus); - - if (ourResponseBody != null) { - theResp.setContentType(ourResponseContentType); - theResp.getWriter().write(ourResponseBody); - } else if (ourResponseBodies != null) { - theResp.setContentType(ourResponseContentType); - theResp.getWriter().write(ourResponseBodies[ourResponseCount]); - } - - ourResponseCount++; - } - }); - - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - } - - @AfterAll - public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } } diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/JaxRsRestfulClientFactoryTest.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/JaxRsRestfulClientFactoryTest.java index 7a6a8df614a..6e701a28a24 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/JaxRsRestfulClientFactoryTest.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/JaxRsRestfulClientFactoryTest.java @@ -14,8 +14,8 @@ import org.slf4j.LoggerFactory; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; -import javax.ws.rs.client.Client; -import javax.ws.rs.core.Response; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.core.Response; import java.util.ArrayList; import java.util.Arrays; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/MyFilter.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/MyFilter.java index 99bbe79ec96..afb4ea4b538 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/MyFilter.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/client/MyFilter.java @@ -1,9 +1,9 @@ package ca.uhn.fhir.jaxrs.client; -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientResponseContext; -import javax.ws.rs.client.ClientResponseFilter; -import javax.ws.rs.ext.Provider; +import jakarta.ws.rs.client.ClientRequestContext; +import jakarta.ws.rs.client.ClientResponseContext; +import jakarta.ws.rs.client.ClientResponseFilter; +import jakarta.ws.rs.ext.Provider; import java.io.IOException; /** diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu2Hl7OrgTest.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu2Hl7OrgTest.java index 5354a5664b0..c7296101b31 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu2Hl7OrgTest.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu2Hl7OrgTest.java @@ -9,9 +9,9 @@ import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; import java.net.URI; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu2_1Test.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu2_1Test.java index eaf56d26e28..ec39710d611 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu2_1Test.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu2_1Test.java @@ -9,10 +9,10 @@ import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; import java.net.URI; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu3Test.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu3Test.java index 6c8ebb7190b..4b026a3f51f 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu3Test.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderDstu3Test.java @@ -9,9 +9,9 @@ import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; import java.net.URI; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderR4Test.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderR4Test.java index 78725548b92..5492f0ec91d 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderR4Test.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderR4Test.java @@ -9,9 +9,9 @@ import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; import java.net.URI; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderTest.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderTest.java index f64dbe68f4d..e1f4825f0fe 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderTest.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsConformanceProviderTest.java @@ -8,9 +8,9 @@ import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; import java.net.URI; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsProviderTest.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsProviderTest.java index 6abf8f9b82d..d3ff832da32 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsProviderTest.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsProviderTest.java @@ -14,10 +14,10 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProviderDstu3Test.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProviderDstu3Test.java index 620a8b3dc1c..2b136dd03c0 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProviderDstu3Test.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProviderDstu3Test.java @@ -20,8 +20,8 @@ import ca.uhn.fhir.test.utilities.JettyUtil; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.lang3.StringUtils; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent; import org.hl7.fhir.dstu3.model.CapabilityStatement; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProviderTest.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProviderTest.java index 67b5fff1d67..a0c1c6ecd82 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProviderTest.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsResourceProviderTest.java @@ -32,8 +32,8 @@ import ca.uhn.fhir.test.utilities.JettyUtil; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.lang3.StringUtils; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseOperationOutcome; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsExceptionInterceptorTest.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsExceptionInterceptorTest.java index 044d00b10b7..c0d1de719a2 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsExceptionInterceptorTest.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsExceptionInterceptorTest.java @@ -1,26 +1,35 @@ package ca.uhn.fhir.jaxrs.server.interceptor; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.*; - -import java.net.URI; -import java.util.HashMap; - -import javax.interceptor.InvocationContext; -import javax.servlet.ServletException; -import javax.ws.rs.core.*; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import ca.uhn.fhir.jaxrs.server.AbstractJaxRsProvider; import ca.uhn.fhir.jaxrs.server.test.TestJaxRsDummyPatientProvider; import ca.uhn.fhir.jaxrs.server.util.JaxRsRequest; import ca.uhn.fhir.rest.api.server.RequestDetails; -import ca.uhn.fhir.rest.server.exceptions.*; +import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; +import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; +import ca.uhn.fhir.rest.server.exceptions.NotImplementedOperationException; import ca.uhn.fhir.rest.server.interceptor.ExceptionHandlingInterceptor; +import jakarta.interceptor.InvocationContext; +import jakarta.servlet.ServletException; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.util.HashMap; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; public class JaxRsExceptionInterceptorTest { @@ -89,7 +98,7 @@ public class JaxRsExceptionInterceptorTest { when(context.proceed()).thenThrow(new ServletException()); JaxRsResponseException thrownException = new JaxRsResponseException(new NotImplementedOperationException("not implemented")); - doThrow(new javax.servlet.ServletException("someMessage")).when(exceptionHandler).handleException(request, thrownException); + doThrow(new jakarta.servlet.ServletException("someMessage")).when(exceptionHandler).handleException(request, thrownException); Response result = interceptor.convertExceptionIntoResponse(request, thrownException); assertEquals(InternalErrorException.STATUS_CODE, result.getStatus()); } diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsResponseExceptionTest.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsResponseExceptionTest.java index bfa5d6b8b8f..58a7a911f7a 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsResponseExceptionTest.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/interceptor/JaxRsResponseExceptionTest.java @@ -1,14 +1,12 @@ package ca.uhn.fhir.jaxrs.server.interceptor; +import ca.uhn.fhir.rest.server.exceptions.ForbiddenOperationException; +import jakarta.ejb.ApplicationException; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import javax.ejb.ApplicationException; - -import org.junit.jupiter.api.Test; - -import ca.uhn.fhir.rest.server.exceptions.ForbiddenOperationException; - public class JaxRsResponseExceptionTest { @Test diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsConformanceRestProvider.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsConformanceRestProvider.java index 7d9231b0930..30c3ddba7c8 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsConformanceRestProvider.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsConformanceRestProvider.java @@ -3,11 +3,11 @@ package ca.uhn.fhir.jaxrs.server.test; import ca.uhn.fhir.jaxrs.server.AbstractJaxRsConformanceProvider; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.server.IResourceProvider; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; +import jakarta.ejb.Stateless; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; -import javax.ejb.Stateless; import java.util.concurrent.ConcurrentHashMap; /** diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsConformanceRestProviderDstu3.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsConformanceRestProviderDstu3.java index 335272b506d..d9b1b675eae 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsConformanceRestProviderDstu3.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsConformanceRestProviderDstu3.java @@ -1,17 +1,15 @@ package ca.uhn.fhir.jaxrs.server.test; -import java.util.concurrent.ConcurrentHashMap; - -import javax.ejb.Stateless; - -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jaxrs.server.AbstractJaxRsConformanceProvider; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.server.IResourceProvider; +import jakarta.ejb.Stateless; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; + +import java.util.concurrent.ConcurrentHashMap; /** * A conformance provider exposes the mock patient and this provider diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPageProvider.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPageProvider.java index f489a7290f4..cff9cf63005 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPageProvider.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPageProvider.java @@ -1,13 +1,12 @@ package ca.uhn.fhir.jaxrs.server.test; -import javax.ejb.Stateless; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - import ca.uhn.fhir.jaxrs.server.AbstractJaxRsPageProvider; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.server.IPagingProvider; +import jakarta.ejb.Stateless; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; @Path("/") @Stateless diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPageProviderDstu3.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPageProviderDstu3.java index aecb104681f..25a140ec821 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPageProviderDstu3.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPageProviderDstu3.java @@ -1,9 +1,9 @@ package ca.uhn.fhir.jaxrs.server.test; -import javax.ejb.Stateless; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; +import jakarta.ejb.Stateless; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jaxrs.server.AbstractJaxRsPageProvider; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProvider.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProvider.java index 0f3d26d6fec..c765cecd6ea 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProvider.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProvider.java @@ -1,34 +1,48 @@ package ca.uhn.fhir.jaxrs.server.test; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import javax.ejb.Stateless; -import javax.interceptor.Interceptors; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import ca.uhn.fhir.rest.api.server.IBundleProvider; -import ca.uhn.fhir.rest.api.server.RequestDetails; -import ca.uhn.fhir.rest.param.DateRangeParam; -import ca.uhn.fhir.rest.server.SimpleBundleProvider; -import org.hl7.fhir.instance.model.api.IIdType; -import org.mockito.Mockito; - import ca.uhn.fhir.jaxrs.server.AbstractJaxRsResourceProvider; import ca.uhn.fhir.jaxrs.server.interceptor.JaxRsExceptionInterceptor; import ca.uhn.fhir.model.api.IResource; -import ca.uhn.fhir.model.dstu2.resource.*; +import ca.uhn.fhir.model.dstu2.resource.OperationOutcome; +import ca.uhn.fhir.model.dstu2.resource.Parameters; +import ca.uhn.fhir.model.dstu2.resource.Patient; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.model.primitive.StringDt; -import ca.uhn.fhir.rest.annotation.*; -import ca.uhn.fhir.rest.api.*; +import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; +import ca.uhn.fhir.rest.annotation.Create; +import ca.uhn.fhir.rest.annotation.Delete; +import ca.uhn.fhir.rest.annotation.History; +import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.annotation.Operation; +import ca.uhn.fhir.rest.annotation.OperationParam; +import ca.uhn.fhir.rest.annotation.Read; +import ca.uhn.fhir.rest.annotation.RequiredParam; +import ca.uhn.fhir.rest.annotation.ResourceParam; +import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.annotation.Update; +import ca.uhn.fhir.rest.annotation.Validate; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.rest.api.RequestTypeEnum; +import ca.uhn.fhir.rest.api.RestOperationTypeEnum; +import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.param.StringAndListParam; import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IPagingProvider; +import jakarta.ejb.Stateless; +import jakarta.interceptor.Interceptors; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.hl7.fhir.instance.model.api.IIdType; +import org.mockito.Mockito; + +import java.util.List; /** * A test server delegating each call to a mock diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu2Hl7Org.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu2Hl7Org.java index 99687058ced..963fe0b1779 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu2Hl7Org.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu2Hl7Org.java @@ -2,11 +2,11 @@ package ca.uhn.fhir.jaxrs.server.test; import java.util.List; -import javax.ejb.Stateless; -import javax.interceptor.Interceptors; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import jakarta.ejb.Stateless; +import jakarta.interceptor.Interceptors; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import org.hl7.fhir.dstu2.model.*; import org.hl7.fhir.instance.model.api.IBaseResource; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu2_1.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu2_1.java index 08aab47036e..973fc38d8da 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu2_1.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu2_1.java @@ -1,27 +1,46 @@ package ca.uhn.fhir.jaxrs.server.test; -import java.util.List; - -import javax.ejb.Stateless; -import javax.interceptor.Interceptors; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.hl7.fhir.dstu2016may.model.*; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.mockito.Mockito; - import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jaxrs.server.AbstractJaxRsResourceProvider; import ca.uhn.fhir.jaxrs.server.interceptor.JaxRsExceptionInterceptor; -import ca.uhn.fhir.rest.annotation.*; -import ca.uhn.fhir.rest.api.*; +import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; +import ca.uhn.fhir.rest.annotation.Create; +import ca.uhn.fhir.rest.annotation.Delete; +import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.annotation.Operation; +import ca.uhn.fhir.rest.annotation.OperationParam; +import ca.uhn.fhir.rest.annotation.Read; +import ca.uhn.fhir.rest.annotation.RequiredParam; +import ca.uhn.fhir.rest.annotation.ResourceParam; +import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.annotation.Update; +import ca.uhn.fhir.rest.annotation.Validate; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.rest.api.RequestTypeEnum; +import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.param.StringAndListParam; import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IPagingProvider; +import jakarta.ejb.Stateless; +import jakarta.interceptor.Interceptors; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.hl7.fhir.dstu2016may.model.IdType; +import org.hl7.fhir.dstu2016may.model.OperationOutcome; +import org.hl7.fhir.dstu2016may.model.Parameters; +import org.hl7.fhir.dstu2016may.model.Patient; +import org.hl7.fhir.dstu2016may.model.StringType; +import org.hl7.fhir.instance.model.api.IBaseResource; +import org.mockito.Mockito; + +import java.util.List; /** * A test server delegating each call to a mock diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu3.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu3.java index 398734ea1e3..03a1d81de9b 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu3.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderDstu3.java @@ -2,11 +2,11 @@ package ca.uhn.fhir.jaxrs.server.test; import java.util.List; -import javax.ejb.Stateless; -import javax.interceptor.Interceptors; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import jakarta.ejb.Stateless; +import jakarta.interceptor.Interceptors; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import org.hl7.fhir.dstu3.model.*; import org.hl7.fhir.instance.model.api.IBaseResource; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderR4.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderR4.java index 0b34916b778..ccaaa2664df 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderR4.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/test/TestJaxRsMockPatientRestProviderR4.java @@ -1,27 +1,46 @@ package ca.uhn.fhir.jaxrs.server.test; -import java.util.List; - -import javax.ejb.Stateless; -import javax.interceptor.Interceptors; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.hl7.fhir.r4.model.*; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.mockito.Mockito; - import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jaxrs.server.AbstractJaxRsResourceProvider; import ca.uhn.fhir.jaxrs.server.interceptor.JaxRsExceptionInterceptor; -import ca.uhn.fhir.rest.annotation.*; -import ca.uhn.fhir.rest.api.*; +import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; +import ca.uhn.fhir.rest.annotation.Create; +import ca.uhn.fhir.rest.annotation.Delete; +import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.annotation.Operation; +import ca.uhn.fhir.rest.annotation.OperationParam; +import ca.uhn.fhir.rest.annotation.Read; +import ca.uhn.fhir.rest.annotation.RequiredParam; +import ca.uhn.fhir.rest.annotation.ResourceParam; +import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.annotation.Update; +import ca.uhn.fhir.rest.annotation.Validate; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.rest.api.RequestTypeEnum; +import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.param.StringAndListParam; import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IPagingProvider; +import jakarta.ejb.Stateless; +import jakarta.interceptor.Interceptors; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.hl7.fhir.instance.model.api.IBaseResource; +import org.hl7.fhir.r4.model.IdType; +import org.hl7.fhir.r4.model.OperationOutcome; +import org.hl7.fhir.r4.model.Parameters; +import org.hl7.fhir.r4.model.Patient; +import org.hl7.fhir.r4.model.StringType; +import org.mockito.Mockito; + +import java.util.List; /** * A test server delegating each call to a mock diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequestDstu3Test.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequestDstu3Test.java index a9d22cac006..3fba820df81 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequestDstu3Test.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequestDstu3Test.java @@ -9,9 +9,9 @@ import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.UriInfo; import java.io.IOException; import java.net.URISyntaxException; import java.util.Arrays; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequestTest.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequestTest.java index f4badf06e66..5502f8acdc9 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequestTest.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsRequestTest.java @@ -3,15 +3,14 @@ package ca.uhn.fhir.jaxrs.server.util; import ca.uhn.fhir.jaxrs.server.test.TestJaxRsDummyPatientProvider; import ca.uhn.fhir.rest.api.RequestTypeEnum; import ca.uhn.fhir.rest.api.RestOperationTypeEnum; -import ca.uhn.fhir.rest.server.exceptions.NotImplementedOperationException; import org.apache.commons.lang3.StringUtils; import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.UriInfo; import java.io.IOException; import java.net.URISyntaxException; import java.util.Arrays; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponseDstu3Test.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponseDstu3Test.java index 9963c14f8b3..17842eeb0e1 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponseDstu3Test.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponseDstu3Test.java @@ -9,7 +9,7 @@ import java.net.URISyntaxException; import java.util.Collections; import java.util.Set; -import javax.ws.rs.core.Response; +import jakarta.ws.rs.core.Response; import org.hl7.fhir.dstu3.model.*; import org.hl7.fhir.instance.model.api.IBaseBinary; diff --git a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponseTest.java b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponseTest.java index 3d296572414..c743127d1e5 100644 --- a/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponseTest.java +++ b/hapi-fhir-jaxrsserver-base/src/test/java/ca/uhn/fhir/jaxrs/server/util/JaxRsResponseTest.java @@ -10,7 +10,7 @@ import java.net.URISyntaxException; import java.util.Collections; import java.util.Set; -import javax.ws.rs.core.Response; +import jakarta.ws.rs.core.Response; import org.hamcrest.Matchers; import org.hl7.fhir.instance.model.api.IBaseBinary; diff --git a/hapi-fhir-jpa/pom.xml b/hapi-fhir-jpa/pom.xml index 076d8328a69..b6830dcdfaf 100644 --- a/hapi-fhir-jpa/pom.xml +++ b/hapi-fhir-jpa/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -35,14 +35,6 @@
    - - org.hibernate - hibernate-entitymanager - - - org.hibernate - hibernate-java8 - org.hibernate.validator hibernate-validator @@ -59,7 +51,7 @@ org.hibernate.search - hibernate-search-mapper-orm + hibernate-search-mapper-orm-orm6 org.apache.logging.log4j diff --git a/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/config/HapiFhirLocalContainerEntityManagerFactoryBean.java b/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/config/HapiFhirLocalContainerEntityManagerFactoryBean.java index e00f858b49f..6dd0a286b55 100644 --- a/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/config/HapiFhirLocalContainerEntityManagerFactoryBean.java +++ b/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/config/HapiFhirLocalContainerEntityManagerFactoryBean.java @@ -21,7 +21,7 @@ package ca.uhn.fhir.jpa.config; import com.google.common.base.Strings; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.query.criteria.LiteralHandlingMode; +import org.hibernate.query.criteria.ValueHandlingMode; import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.orm.hibernate5.SpringBeanContainer; @@ -51,13 +51,14 @@ public class HapiFhirLocalContainerEntityManagerFactoryBean extends LocalContain Map retVal = super.getJpaPropertyMap(); // SOMEDAY these defaults can be set in the constructor. setJpaProperties does a merge. - if (!retVal.containsKey(AvailableSettings.CRITERIA_LITERAL_HANDLING_MODE)) { - retVal.put(AvailableSettings.CRITERIA_LITERAL_HANDLING_MODE, LiteralHandlingMode.BIND); + if (!retVal.containsKey(AvailableSettings.CRITERIA_VALUE_HANDLING_MODE)) { + retVal.put(AvailableSettings.CRITERIA_VALUE_HANDLING_MODE, ValueHandlingMode.BIND); } if (!retVal.containsKey(AvailableSettings.CONNECTION_HANDLING)) { retVal.put( - AvailableSettings.CONNECTION_HANDLING, PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_HOLD); + AvailableSettings.CONNECTION_HANDLING, + PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION); } /* diff --git a/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/sched/BaseSchedulerServiceImpl.java b/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/sched/BaseSchedulerServiceImpl.java index 58672a138a2..2bd359b21dd 100644 --- a/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/sched/BaseSchedulerServiceImpl.java +++ b/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/sched/BaseSchedulerServiceImpl.java @@ -27,6 +27,7 @@ import ca.uhn.fhir.jpa.model.sched.ISchedulerService; import ca.uhn.fhir.jpa.model.sched.ScheduledJobDefinition; import ca.uhn.fhir.util.StopWatch; import com.google.common.annotations.VisibleForTesting; +import jakarta.annotation.PostConstruct; import org.quartz.JobKey; import org.quartz.SchedulerException; import org.slf4j.Logger; @@ -41,7 +42,6 @@ import org.springframework.core.env.Environment; import java.util.Collection; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -import javax.annotation.PostConstruct; /** * This class provides task scheduling for the entire module using the Quartz library. diff --git a/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/util/DerbyTenSevenHapiFhirDialect.java b/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/util/DerbyTenSevenHapiFhirDialect.java index b83b99a13d9..7216e9fef42 100644 --- a/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/util/DerbyTenSevenHapiFhirDialect.java +++ b/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/util/DerbyTenSevenHapiFhirDialect.java @@ -19,33 +19,32 @@ */ package ca.uhn.fhir.jpa.util; -import org.hibernate.dialect.DerbyTenSevenDialect; -import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; -import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; +import org.hibernate.dialect.DerbyDialect; +import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor; +import org.hibernate.exception.spi.ViolatedConstraintNameExtractor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.SQLException; +import java.util.function.Function; -public class DerbyTenSevenHapiFhirDialect extends DerbyTenSevenDialect { +import static org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor.extractUsingTemplate; + +public class DerbyTenSevenHapiFhirDialect extends DerbyDialect { private static final Logger ourLog = LoggerFactory.getLogger(DerbyTenSevenHapiFhirDialect.class); @Override - public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() { - return new TemplatedViolatedConstraintNameExtracter() { - @Override - protected String doExtractConstraintName(SQLException theSqlException) throws NumberFormatException { - switch (theSqlException.getSQLState()) { - case "23505": - return this.extractUsingTemplate( - "unique or primary key constraint or unique index identified by '", - "'", - theSqlException.getMessage()); - default: - return null; - } + public ViolatedConstraintNameExtractor getViolatedConstraintNameExtractor() { + Function extractor = e -> { + switch (e.getSQLState()) { + case "23505": + return extractUsingTemplate( + "unique or primary key constraint or unique index identified by '", "'", e.getMessage()); + default: + return null; } }; + return new TemplatedViolatedConstraintNameExtractor(extractor); } } diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/ISequenceValueMassager.java b/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/util/ISequenceValueMassager.java similarity index 87% rename from hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/ISequenceValueMassager.java rename to hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/util/ISequenceValueMassager.java index df4c3a7ba52..a7bfc43a1bc 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/ISequenceValueMassager.java +++ b/hapi-fhir-jpa/src/main/java/ca/uhn/fhir/jpa/util/ISequenceValueMassager.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR JPA Model + * hapi-fhir-jpa * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% @@ -17,16 +17,18 @@ * limitations under the License. * #L% */ -package ca.uhn.fhir.jpa.model.dialect; +package ca.uhn.fhir.jpa.util; + +import org.hibernate.service.Service; import javax.annotation.Nullable; /** * This is an internal API and may change or disappear without notice * - * Implementations of this interface can modify the automatically generated sequence values created by hibernate seuqnece generator + * Implementations of this interface can modify the automatically generated sequence values created by hibernate sequence generator */ -public interface ISequenceValueMassager { +public interface ISequenceValueMassager extends Service { Long massage(String theGeneratorName, Long theId); diff --git a/hapi-fhir-jpaserver-base/pom.xml b/hapi-fhir-jpaserver-base/pom.xml index da09b2a7d82..915810128cf 100644 --- a/hapi-fhir-jpaserver-base/pom.xml +++ b/hapi-fhir-jpaserver-base/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -208,7 +208,7 @@ org.springdoc - springdoc-openapi-ui + springdoc-openapi-starter-webmvc-ui @@ -217,7 +217,7 @@ org.thymeleaf - thymeleaf-spring5 + thymeleaf-spring6 @@ -243,23 +243,12 @@ xml-patch - - - - - javax.interceptor - javax.interceptor-api - provided - - - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided @@ -308,11 +297,6 @@ org.springframework spring-websocket - - javax.el - javax.el-api - provided - org.glassfish jakarta.el @@ -325,12 +309,12 @@ - org.elasticsearch.client - elasticsearch-rest-high-level-client + co.elastic.clients + elasticsearch-java - org.apache.logging.log4j - log4j-api + jakarta.json + jakarta.json-api @@ -347,7 +331,7 @@ hibernate-search-backend-elasticsearch-aws - org.hibernate + org.hibernate.orm hibernate-envers @@ -435,98 +419,7 @@ - - de.jpdigital - hibernate56-ddl-maven-plugin - - - derby_10_7 - mysql57 - mariadb - oracle12c - sqlserver2012 - - - ca.uhn.fhir.jpa.model.dialect.HapiFhirH2Dialect - ca.uhn.fhir.jpa.model.dialect.HapiFhirPostgres94Dialect - org.hibernate.dialect.CockroachDB201Dialect - - ${project.build.directory}/classes/ca/uhn/hapi/fhir/jpa/docs/database - - ca.uhn.fhir.jpa.entity - ca.uhn.fhir.jpa.model.entity - - - - - process-classes - - gen-ddl - - - - - - - org.glassfish.jaxb - jaxb-runtime - ${jaxb_runtime_version} - - - ca.uhn.hapi.fhir - hapi-fhir-jpaserver-model - ${project.version} - - - org.hibernate - hibernate-core - ${hibernate_version} - - - org.hibernate - hibernate-envers - - ${hibernate_version} - - - javax.xml.bind - jaxb-api - ${jaxb_api_version} - - - com.sun.xml.bind - jaxb-impl - ${jaxb_api_version} - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - process-classes - - run - - - - - - - - - - - - - - - - + ca.uhn.hapi.fhir hapi-tinder-plugin @@ -637,6 +530,68 @@ + + + ca.uhn.hapi.fhir + hapi-tinder-plugin + ${project.version} + + + + generate-ddl + + + + + + ca.uhn.fhir.jpa.entity + ca.uhn.fhir.jpa.model.entity + + + + ca.uhn.fhir.jpa.model.dialect.HapiFhirDerbyDialect + derby.sql + + + ca.uhn.fhir.jpa.model.dialect.HapiFhirMySQLDialect + mysql.sql + + + ca.uhn.fhir.jpa.model.dialect.HapiFhirMariaDBDialect + mariadb.sql + + + ca.uhn.fhir.jpa.model.dialect.HapiFhirOracleDialect + oracle.sql + + + ca.uhn.fhir.jpa.model.dialect.HapiFhirSQLServerDialect + sqlserver.sql + + + ca.uhn.fhir.jpa.model.dialect.HapiFhirCockroachDialect + cockroachdb.sql + + + ca.uhn.fhir.jpa.model.dialect.HapiFhirH2Dialect + h2.sql + + + ca.uhn.fhir.jpa.model.dialect.HapiFhirPostgresDialect + classpath:ca/uhn/fhir/jpa/docs/database/hapifhirpostgres94-init01.sql + postgres.sql + + + ${project.build.directory}/classes/ca/uhn/hapi/fhir/jpa/docs/database + + + + ca.uhn.hapi.fhir + hapi-fhir-jpaserver-model + ${project.version} + + + org.codehaus.mojo build-helper-maven-plugin diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/batch2/JpaBatch2Config.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/batch2/JpaBatch2Config.java index c4803afcf86..6105c06bf17 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/batch2/JpaBatch2Config.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/batch2/JpaBatch2Config.java @@ -25,13 +25,12 @@ import ca.uhn.fhir.jpa.bulk.export.job.BulkExportJobConfig; import ca.uhn.fhir.jpa.dao.data.IBatch2JobInstanceRepository; import ca.uhn.fhir.jpa.dao.data.IBatch2WorkChunkRepository; import ca.uhn.fhir.jpa.dao.tx.IHapiTransactionService; +import jakarta.persistence.EntityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Primary; -import javax.persistence.EntityManager; - @Configuration @Import({BulkExportJobConfig.class}) public class JpaBatch2Config extends BaseBatch2Config { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/batch2/JpaJobPersistenceImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/batch2/JpaJobPersistenceImpl.java index 12bf7d12cec..d44374083cc 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/batch2/JpaJobPersistenceImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/batch2/JpaJobPersistenceImpl.java @@ -42,6 +42,9 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import jakarta.persistence.EntityManager; +import jakarta.persistence.LockModeType; +import jakarta.persistence.Query; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; @@ -66,9 +69,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.persistence.EntityManager; -import javax.persistence.LockModeType; -import javax.persistence.Query; import static ca.uhn.fhir.batch2.coordinator.WorkChunkProcessor.MAX_CHUNK_ERROR_COUNT; import static ca.uhn.fhir.jpa.entity.Batch2WorkChunkEntity.ERROR_MSG_MAX_LENGTH; @@ -296,7 +296,6 @@ public class JpaJobPersistenceImpl implements IJobPersistence { } @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) public WorkChunkStatusEnum onWorkChunkError(WorkChunkErrorEvent theParameters) { String chunkId = theParameters.getChunkId(); String errorMessage = truncateErrorMessage(theParameters.getErrorMsg()); diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/binstore/DatabaseBlobBinaryStorageSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/binstore/DatabaseBlobBinaryStorageSvcImpl.java index 58936143305..f4d906f52c6 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/binstore/DatabaseBlobBinaryStorageSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/binstore/DatabaseBlobBinaryStorageSvcImpl.java @@ -28,6 +28,9 @@ import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import com.google.common.hash.HashingInputStream; import com.google.common.io.ByteStreams; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.CountingInputStream; import org.hibernate.LobHelper; @@ -45,9 +48,6 @@ import java.sql.SQLException; import java.util.Date; import java.util.Optional; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; @Transactional public class DatabaseBlobBinaryStorageSvcImpl extends BaseBinaryStorageSvcImpl { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/export/svc/BulkDataExportJobSchedulingHelperImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/export/svc/BulkDataExportJobSchedulingHelperImpl.java index 5d352926733..74e01095381 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/export/svc/BulkDataExportJobSchedulingHelperImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/export/svc/BulkDataExportJobSchedulingHelperImpl.java @@ -34,6 +34,7 @@ import ca.uhn.fhir.jpa.model.sched.ScheduledJobDefinition; import ca.uhn.fhir.rest.api.server.SystemRequestDetails; import ca.uhn.fhir.util.Batch2JobDefinitionConstants; import ca.uhn.fhir.util.JsonUtil; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import org.hl7.fhir.instance.model.api.IBaseBinary; @@ -55,7 +56,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.Nonnull; -import javax.annotation.PostConstruct; import static org.slf4j.LoggerFactory.getLogger; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/export/svc/JpaBulkExportProcessor.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/export/svc/JpaBulkExportProcessor.java index 8245fdaf066..ab3c79551ce 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/export/svc/JpaBulkExportProcessor.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/export/svc/JpaBulkExportProcessor.java @@ -58,6 +58,7 @@ import ca.uhn.fhir.util.ExtensionUtil; import ca.uhn.fhir.util.HapiExtensions; import ca.uhn.fhir.util.Logs; import ca.uhn.fhir.util.SearchParameterUtil; +import jakarta.persistence.EntityManager; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.instance.model.api.IBaseExtension; import org.hl7.fhir.instance.model.api.IBaseReference; @@ -79,7 +80,6 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; import static ca.uhn.fhir.rest.api.Constants.PARAM_HAS; import static ca.uhn.fhir.rest.api.Constants.PARAM_ID; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/imprt/svc/BulkDataImportSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/imprt/svc/BulkDataImportSvcImpl.java index 301d7739466..9d9b5e9248e 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/imprt/svc/BulkDataImportSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/imprt/svc/BulkDataImportSvcImpl.java @@ -40,6 +40,7 @@ import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.util.Logs; import ca.uhn.fhir.util.ValidateUtil; import com.apicatalog.jsonld.StringUtils; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.time.DateUtils; import org.quartz.JobExecutionContext; import org.slf4j.Logger; @@ -59,7 +60,6 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.Semaphore; import javax.annotation.Nonnull; -import javax.annotation.PostConstruct; import static ca.uhn.fhir.batch2.jobs.importpull.BulkImportPullConfig.BULK_IMPORT_JOB_NAME; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/Batch2SupportConfig.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/Batch2SupportConfig.java index 16cda3e728c..3c3f228adff 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/Batch2SupportConfig.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/Batch2SupportConfig.java @@ -34,11 +34,10 @@ import ca.uhn.fhir.jpa.delete.batch2.DeleteExpungeSqlBuilder; import ca.uhn.fhir.jpa.delete.batch2.DeleteExpungeSvcImpl; import ca.uhn.fhir.jpa.reindex.Batch2DaoSvcImpl; import ca.uhn.fhir.jpa.searchparam.MatchUrlService; +import jakarta.persistence.EntityManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; -import javax.persistence.EntityManager; - public class Batch2SupportConfig { @Bean diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/EnversAuditConfig.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/EnversAuditConfig.java index 18fd08f7a28..be5702b2e89 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/EnversAuditConfig.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/EnversAuditConfig.java @@ -20,13 +20,12 @@ package ca.uhn.fhir.jpa.config; * #L% */ +import jakarta.persistence.EntityManagerFactory; import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import javax.persistence.EntityManagerFactory; - @Configuration public class EnversAuditConfig { private final EntityManagerFactory myEntityManagerFactory; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/HapiFhirHibernateJpaDialect.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/HapiFhirHibernateJpaDialect.java index 463e3a471cb..3043fe69b81 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/HapiFhirHibernateJpaDialect.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/HapiFhirHibernateJpaDialect.java @@ -27,6 +27,7 @@ import ca.uhn.fhir.jpa.model.entity.ResourceSearchUrlEntity; import ca.uhn.fhir.jpa.model.entity.ResourceTable; import ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException; import ca.uhn.fhir.system.HapiSystemProperties; +import jakarta.persistence.PersistenceException; import org.hibernate.HibernateException; import org.hibernate.PessimisticLockException; import org.hibernate.exception.ConstraintViolationException; @@ -36,7 +37,6 @@ import org.springframework.dao.DataAccessException; import org.springframework.orm.jpa.vendor.HibernateJpaDialect; import javax.annotation.Nonnull; -import javax.persistence.PersistenceException; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/JpaConfig.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/JpaConfig.java index 50ec76efa26..9d752b6694c 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/JpaConfig.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/JpaConfig.java @@ -51,7 +51,6 @@ import ca.uhn.fhir.jpa.dao.IJpaStorageResourceParser; import ca.uhn.fhir.jpa.dao.ISearchBuilder; import ca.uhn.fhir.jpa.dao.JpaStorageResourceParser; import ca.uhn.fhir.jpa.dao.MatchResourceUrlService; -import ca.uhn.fhir.jpa.dao.ObservationLastNIndexPersistSvc; import ca.uhn.fhir.jpa.dao.SearchBuilderFactory; import ca.uhn.fhir.jpa.dao.TransactionProcessor; import ca.uhn.fhir.jpa.dao.data.IResourceModifiedDao; @@ -223,7 +222,6 @@ public class JpaConfig { public static final String PERSISTED_JPA_BUNDLE_PROVIDER_BY_SEARCH = "PersistedJpaBundleProvider_BySearch"; public static final String PERSISTED_JPA_SEARCH_FIRST_PAGE_BUNDLE_PROVIDER = "PersistedJpaSearchFirstPageBundleProvider"; - public static final String SEARCH_BUILDER = "SearchBuilder"; public static final String HISTORY_BUILDER = "HistoryBuilder"; private static final String HAPI_DEFAULT_SCHEDULER_GROUP = "HAPI"; @@ -564,7 +562,8 @@ public class JpaConfig { @Bean(name = PERSISTED_JPA_BUNDLE_PROVIDER_BY_SEARCH) @Scope("prototype") - public PersistedJpaBundleProvider newPersistedJpaBundleProvider(RequestDetails theRequest, Search theSearch) { + public PersistedJpaBundleProvider newPersistedJpaBundleProviderBySearch( + RequestDetails theRequest, Search theSearch) { return new PersistedJpaBundleProvider(theRequest, theSearch); } @@ -694,7 +693,7 @@ public class JpaConfig { @Bean(name = HISTORY_BUILDER) @Scope("prototype") - public HistoryBuilder newPersistedJpaSearchFirstPageBundleProvider( + public HistoryBuilder newHistoryBuilder( @Nullable String theResourceType, @Nullable Long theResourceId, @Nullable Date theRangeStartInclusive, @@ -832,11 +831,6 @@ public class JpaConfig { return new TermReindexingSvcImpl(); } - @Bean - public ObservationLastNIndexPersistSvc baseObservationLastNIndexpersistSvc() { - return new ObservationLastNIndexPersistSvc(); - } - @Bean @Scope("prototype") public PersistenceContextProvider persistenceContextProvider() { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/util/HapiEntityManagerFactoryUtil.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/util/HapiEntityManagerFactoryUtil.java index f3c0a72e75f..1a28f92db97 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/util/HapiEntityManagerFactoryUtil.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/config/util/HapiEntityManagerFactoryUtil.java @@ -20,30 +20,88 @@ package ca.uhn.fhir.jpa.config.util; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; import ca.uhn.fhir.jpa.config.HapiFhirHibernateJpaDialect; import ca.uhn.fhir.jpa.config.HapiFhirLocalContainerEntityManagerFactoryBean; +import ca.uhn.fhir.jpa.util.ISequenceValueMassager; +import ca.uhn.fhir.util.ReflectionUtil; +import jakarta.persistence.spi.PersistenceUnitInfo; +import org.hibernate.boot.registry.BootstrapServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.jpa.HibernatePersistenceProvider; +import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; +import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; +import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import java.util.Map; + public final class HapiEntityManagerFactoryUtil { private HapiEntityManagerFactoryUtil() {} + /** * This method provides a partially completed entity manager * factory with HAPI FHIR customizations */ public static LocalContainerEntityManagerFactoryBean newEntityManagerFactory( - ConfigurableListableBeanFactory myConfigurableListableBeanFactory, FhirContext theFhirContext) { + ConfigurableListableBeanFactory myConfigurableListableBeanFactory, + FhirContext theFhirContext, + JpaStorageSettings theStorageSettings) { LocalContainerEntityManagerFactoryBean retVal = new HapiFhirLocalContainerEntityManagerFactoryBean(myConfigurableListableBeanFactory); - configureEntityManagerFactory(retVal, theFhirContext); + configureEntityManagerFactory(retVal, theFhirContext, theStorageSettings); return retVal; } public static void configureEntityManagerFactory( - LocalContainerEntityManagerFactoryBean theFactory, FhirContext theFhirContext) { + LocalContainerEntityManagerFactoryBean theFactory, + FhirContext theFhirContext, + JpaStorageSettings theStorageSettings) { theFactory.setJpaDialect(new HapiFhirHibernateJpaDialect(theFhirContext.getLocalizer())); theFactory.setPackagesToScan("ca.uhn.fhir.jpa.model.entity", "ca.uhn.fhir.jpa.entity"); - theFactory.setPersistenceProvider(new HibernatePersistenceProvider()); + theFactory.setPersistenceProvider(new MyHibernatePersistenceProvider(theStorageSettings)); + } + + private static class MyHibernatePersistenceProvider extends HibernatePersistenceProvider { + + private final JpaStorageSettings myStorageSettings; + + public MyHibernatePersistenceProvider(JpaStorageSettings theStorageSettings) { + myStorageSettings = theStorageSettings; + } + + /** + * @see MyEntityManagerFactoryBuilderImpl for an explanation of why we do this + */ + @Override + protected EntityManagerFactoryBuilder getEntityManagerFactoryBuilder( + PersistenceUnitInfo info, Map integration) { + return new MyEntityManagerFactoryBuilderImpl(info, integration); + } + + /** + * This class extends the default hibernate EntityManagerFactoryBuilder in order to + * register a custom service (the {@link ISequenceValueMassager}, which is used in + * {@link ca.uhn.fhir.jpa.model.dialect.HapiSequenceStyleGenerator}. + *

    + * In Hibernate 5 we didn't need to do this, since we could just register + * the service with Spring and Hibernate would ask Spring for it. This no longer + * seems to work in Hibernate 6, so we now have to manually register it. + */ + private class MyEntityManagerFactoryBuilderImpl extends EntityManagerFactoryBuilderImpl { + public MyEntityManagerFactoryBuilderImpl(PersistenceUnitInfo theInfo, Map theIntegration) { + super(new PersistenceUnitInfoDescriptor(theInfo), (Map) theIntegration); + } + + @Override + protected StandardServiceRegistryBuilder getStandardServiceRegistryBuilder(BootstrapServiceRegistry bsr) { + StandardServiceRegistryBuilder retVal = super.getStandardServiceRegistryBuilder(bsr); + ISequenceValueMassager sequenceValueMassager = + ReflectionUtil.newInstance(myStorageSettings.getSequenceValueMassagerClass()); + retVal.addService(ISequenceValueMassager.class, sequenceValueMassager); + return retVal; + } + } } } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirDao.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirDao.java index 13dfc7b25f0..af3d76dead1 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirDao.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirDao.java @@ -107,6 +107,16 @@ import com.google.common.collect.Sets; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; +import jakarta.annotation.PostConstruct; +import jakarta.persistence.EntityManager; +import jakarta.persistence.NoResultException; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; @@ -151,16 +161,6 @@ import java.util.StringTokenizer; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.annotation.PostConstruct; -import javax.persistence.EntityManager; -import javax.persistence.NoResultException; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import javax.xml.stream.events.Characters; import javax.xml.stream.events.XMLEvent; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirResourceDao.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirResourceDao.java index ba1a21a0eea..4d58d571ca7 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirResourceDao.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirResourceDao.java @@ -118,6 +118,11 @@ import ca.uhn.fhir.validation.ValidationOptions; import ca.uhn.fhir.validation.ValidationResult; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Streams; +import jakarta.annotation.PostConstruct; +import jakarta.persistence.LockModeType; +import jakarta.persistence.NoResultException; +import jakarta.persistence.TypedQuery; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBaseCoding; @@ -129,7 +134,6 @@ import org.hl7.fhir.instance.model.api.IPrimitiveType; import org.hl7.fhir.r4.model.Parameters; import org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Required; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Slice; import org.springframework.transaction.PlatformTransactionManager; @@ -155,11 +159,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.annotation.PostConstruct; -import javax.persistence.LockModeType; -import javax.persistence.NoResultException; -import javax.persistence.TypedQuery; -import javax.servlet.http.HttpServletResponse; import static java.util.Objects.isNull; import static org.apache.commons.lang3.StringUtils.isBlank; @@ -1224,7 +1223,6 @@ public abstract class BaseHapiFhirResourceDao extends B } @SuppressWarnings("unchecked") - @Required public void setResourceType(Class theTableType) { myResourceType = (Class) theTableType; } @@ -1657,8 +1655,11 @@ public abstract class BaseHapiFhirResourceDao extends B CURRENTLY_REINDEXING.put(theResource, Boolean.TRUE); } + SystemRequestDetails request = new SystemRequestDetails(); + request.getUserData().put(JpaConstants.SKIP_REINDEX_ON_UPDATE, Boolean.TRUE); + updateEntity( - null, theResource, theEntity, theEntity.getDeleted(), true, false, transactionDetails, true, false); + request, theResource, theEntity, theEntity.getDeleted(), true, false, transactionDetails, true, false); if (theResource != null) { CURRENTLY_REINDEXING.put(theResource, null); } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirSystemDao.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirSystemDao.java index 6696a3b0e52..961992748e1 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirSystemDao.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirSystemDao.java @@ -48,6 +48,15 @@ import ca.uhn.fhir.rest.api.server.storage.IResourcePersistentId; import ca.uhn.fhir.rest.server.exceptions.MethodNotAllowedException; import ca.uhn.fhir.util.StopWatch; import com.google.common.annotations.VisibleForTesting; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.JoinType; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; @@ -61,15 +70,6 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Nullable; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.JoinType; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; public abstract class BaseHapiFhirSystemDao extends BaseStorageDao implements IFhirSystemDao { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2.java index b9ab01c5c6a..76e6279ddd2 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu2.java @@ -23,11 +23,11 @@ import ca.uhn.fhir.jpa.model.entity.TagDefinition; import ca.uhn.fhir.model.dstu2.composite.MetaDt; import ca.uhn.fhir.model.dstu2.resource.Bundle; import ca.uhn.fhir.rest.api.server.RequestDetails; +import jakarta.persistence.TypedQuery; import org.hl7.fhir.instance.model.api.IBaseBundle; import java.util.Collection; import java.util.List; -import javax.persistence.TypedQuery; public class FhirSystemDaoDstu2 extends BaseHapiFhirSystemDao { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FulltextSearchSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FulltextSearchSvcImpl.java index 346b1063e3d..80bd0e9a7f1 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FulltextSearchSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/FulltextSearchSvcImpl.java @@ -53,6 +53,9 @@ import ca.uhn.fhir.rest.server.util.CompositeInterceptorBroadcaster; import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import ca.uhn.fhir.rest.server.util.ResourceSearchParams; import com.google.common.collect.Ordering; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; import org.hibernate.search.backend.elasticsearch.ElasticsearchExtension; import org.hibernate.search.engine.search.predicate.dsl.PredicateFinalStep; import org.hibernate.search.engine.search.predicate.dsl.SearchPredicateFactory; @@ -79,9 +82,6 @@ import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; import static ca.uhn.fhir.rest.server.BasePagingProvider.DEFAULT_MAX_PAGE_SIZE; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/HistoryBuilder.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/HistoryBuilder.java index 445e9d8860b..30a181df720 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/HistoryBuilder.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/HistoryBuilder.java @@ -32,6 +32,17 @@ import ca.uhn.fhir.rest.param.HistorySearchStyleEnum; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.Multimaps; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Expression; +import jakarta.persistence.criteria.JoinType; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Subquery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -43,17 +54,6 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Expression; -import javax.persistence.criteria.JoinType; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import javax.persistence.criteria.Subquery; import static ca.uhn.fhir.jpa.util.QueryParameterUtils.toPredicateArray; @@ -177,18 +177,13 @@ public class HistoryBuilder { if (!thePartitionId.isAllPartitions()) { if (thePartitionId.isDefaultPartition()) { - predicates.add(theCriteriaBuilder.isNull( - theFrom.get("myPartitionIdValue").as(Integer.class))); + predicates.add(theCriteriaBuilder.isNull(theFrom.get("myPartitionIdValue"))); } else if (thePartitionId.hasDefaultPartitionId()) { predicates.add(theCriteriaBuilder.or( - theCriteriaBuilder.isNull( - theFrom.get("myPartitionIdValue").as(Integer.class)), - theFrom.get("myPartitionIdValue") - .as(Integer.class) - .in(thePartitionId.getPartitionIdsWithoutDefault()))); + theCriteriaBuilder.isNull(theFrom.get("myPartitionIdValue")), + theFrom.get("myPartitionIdValue").in(thePartitionId.getPartitionIdsWithoutDefault()))); } else { - predicates.add( - theFrom.get("myPartitionIdValue").as(Integer.class).in(thePartitionId.getPartitionIds())); + predicates.add(theFrom.get("myPartitionIdValue").in(thePartitionId.getPartitionIds())); } } @@ -205,13 +200,12 @@ public class HistoryBuilder { if (HistorySearchStyleEnum.AT == theHistorySearchStyle && myResourceId != null) { addPredicateForAtQueryParameter(theCriteriaBuilder, theQuery, theFrom, predicates); } else { - predicates.add(theCriteriaBuilder.greaterThanOrEqualTo( - theFrom.get("myUpdated").as(Date.class), myRangeStartInclusive)); + predicates.add( + theCriteriaBuilder.greaterThanOrEqualTo(theFrom.get("myUpdated"), myRangeStartInclusive)); } } if (myRangeEndInclusive != null) { - predicates.add(theCriteriaBuilder.lessThanOrEqualTo( - theFrom.get("myUpdated").as(Date.class), myRangeEndInclusive)); + predicates.add(theCriteriaBuilder.lessThanOrEqualTo(theFrom.get("myUpdated"), myRangeEndInclusive)); } if (predicates.size() > 0) { @@ -226,20 +220,19 @@ public class HistoryBuilder { List thePredicates) { Subquery pastDateSubQuery = theQuery.subquery(Date.class); Root subQueryResourceHistory = pastDateSubQuery.from(ResourceHistoryTable.class); - Expression myUpdatedMostRecent = - theCriteriaBuilder.max(subQueryResourceHistory.get("myUpdated")).as(Date.class); - Expression myUpdatedMostRecentOrDefault = + Expression myUpdatedMostRecent = theCriteriaBuilder.max(subQueryResourceHistory.get("myUpdated")); + Expression myUpdatedMostRecentOrDefault = theCriteriaBuilder.coalesce(myUpdatedMostRecent, theCriteriaBuilder.literal(myRangeStartInclusive)); pastDateSubQuery .select(myUpdatedMostRecentOrDefault) .where( theCriteriaBuilder.lessThanOrEqualTo( - subQueryResourceHistory.get("myUpdated").as(Date.class), myRangeStartInclusive), + subQueryResourceHistory.get("myUpdated"), myRangeStartInclusive), theCriteriaBuilder.equal(subQueryResourceHistory.get("myResourceId"), myResourceId)); Predicate updatedDatePredicate = - theCriteriaBuilder.greaterThanOrEqualTo(theFrom.get("myUpdated").as(Date.class), pastDateSubQuery); + theCriteriaBuilder.greaterThanOrEqualTo(theFrom.get("myUpdated"), pastDateSubQuery); thePredicates.add(updatedDatePredicate); } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaPersistedResourceValidationSupport.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaPersistedResourceValidationSupport.java index 78b1eed3f6d..d3c32df28f8 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaPersistedResourceValidationSupport.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaPersistedResourceValidationSupport.java @@ -36,6 +36,7 @@ import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.rest.param.UriParam; import ca.uhn.fhir.sl.cache.Cache; import ca.uhn.fhir.sl.cache.CacheFactory; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IAnyResource; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -58,7 +59,6 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import javax.annotation.Nullable; -import javax.annotation.PostConstruct; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.hl7.fhir.common.hapi.validation.support.ValidationConstants.LOINC_LOW; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoCodeSystem.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoCodeSystem.java index 12a4f01a947..1a51e09e493 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoCodeSystem.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoCodeSystem.java @@ -42,6 +42,7 @@ import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.util.FhirTerser; import ca.uhn.hapi.converters.canonical.VersionCanonicalizer; +import jakarta.annotation.PostConstruct; import org.apache.commons.collections4.CollectionUtils; import org.hl7.fhir.common.hapi.validation.support.CommonCodeSystemsTerminologyService; import org.hl7.fhir.instance.model.api.IBaseCoding; @@ -59,7 +60,6 @@ import java.util.Date; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nonnull; -import javax.annotation.PostConstruct; import static ca.uhn.fhir.util.DatatypeUtil.toStringValue; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoComposition.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoComposition.java index 1ff023172a6..22b7da2f025 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoComposition.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoComposition.java @@ -27,12 +27,12 @@ import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.param.StringParam; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.instance.model.api.IPrimitiveType; import java.util.Collections; -import javax.servlet.http.HttpServletRequest; public class JpaResourceDaoComposition extends BaseHapiFhirResourceDao implements IFhirResourceDaoComposition { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoEncounter.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoEncounter.java index 9c365a43b7d..6e35f2e0341 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoEncounter.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoEncounter.java @@ -27,12 +27,12 @@ import ca.uhn.fhir.rest.api.SortSpec; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.param.StringParam; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.instance.model.api.IPrimitiveType; import java.util.Collections; -import javax.servlet.http.HttpServletRequest; public class JpaResourceDaoEncounter extends BaseHapiFhirResourceDao implements IFhirResourceDaoEncounter { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoObservation.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoObservation.java index 6181c2dedfc..b81db1c490c 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoObservation.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoObservation.java @@ -22,9 +22,7 @@ package ca.uhn.fhir.jpa.dao; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.api.dao.IFhirResourceDaoObservation; -import ca.uhn.fhir.jpa.model.cross.IBasePersistedResource; import ca.uhn.fhir.jpa.model.dao.JpaPid; -import ca.uhn.fhir.jpa.model.entity.ResourceTable; import ca.uhn.fhir.jpa.partition.IRequestPartitionHelperSvc; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; import ca.uhn.fhir.model.api.IQueryParameterType; @@ -34,22 +32,20 @@ import ca.uhn.fhir.rest.api.SortOrderEnum; import ca.uhn.fhir.rest.api.SortSpec; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.api.server.RequestDetails; -import ca.uhn.fhir.rest.api.server.storage.TransactionDetails; import ca.uhn.fhir.rest.param.ReferenceOrListParam; import ca.uhn.fhir.rest.param.ReferenceParam; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.servlet.http.HttpServletResponse; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Observation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.support.TransactionTemplate; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.TreeMap; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.servlet.http.HttpServletResponse; public class JpaResourceDaoObservation extends BaseHapiFhirResourceDao implements IFhirResourceDaoObservation { @@ -57,9 +53,6 @@ public class JpaResourceDaoObservation extends BaseHapi @PersistenceContext(type = PersistenceContextType.TRANSACTION) protected EntityManager myEntityManager; - @Autowired - ObservationLastNIndexPersistSvc myObservationLastNIndexPersistSvc; - @Autowired private IRequestPartitionHelperSvc myRequestPartitionHelperService; @@ -98,64 +91,6 @@ public class JpaResourceDaoObservation extends BaseHapi return Observation.SP_PATIENT; } - @Override - public ResourceTable updateEntity( - RequestDetails theRequest, - IBaseResource theResource, - IBasePersistedResource theEntity, - Date theDeletedTimestampOrNull, - boolean thePerformIndexing, - boolean theUpdateVersion, - TransactionDetails theTransactionDetails, - boolean theForceUpdate, - boolean theCreateNewHistoryEntry) { - return updateObservationEntity( - theRequest, - theResource, - theEntity, - theDeletedTimestampOrNull, - thePerformIndexing, - theUpdateVersion, - theTransactionDetails, - theForceUpdate, - theCreateNewHistoryEntry); - } - - protected ResourceTable updateObservationEntity( - RequestDetails theRequest, - IBaseResource theResource, - IBasePersistedResource theEntity, - Date theDeletedTimestampOrNull, - boolean thePerformIndexing, - boolean theUpdateVersion, - TransactionDetails theTransactionDetails, - boolean theForceUpdate, - boolean theCreateNewHistoryEntry) { - ResourceTable retVal = super.updateEntity( - theRequest, - theResource, - theEntity, - theDeletedTimestampOrNull, - thePerformIndexing, - theUpdateVersion, - theTransactionDetails, - theForceUpdate, - theCreateNewHistoryEntry); - - if (getStorageSettings().isLastNEnabled()) { - if (!retVal.isUnchangedInCurrentOperation()) { - if (retVal.getDeleted() == null) { - // Update indexes here for LastN operation. - myObservationLastNIndexPersistSvc.indexObservation(theResource); - } else { - myObservationLastNIndexPersistSvc.deleteObservationIndex(theEntity); - } - } - } - - return retVal; - } - protected void updateSearchParamsForLastn( SearchParameterMap theSearchParameterMap, RequestDetails theRequestDetails) { if (!isPagingProviderDatabaseBacked(theRequestDetails)) { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoPatient.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoPatient.java index 0a1a4540614..e94702fad0b 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoPatient.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/JpaResourceDaoPatient.java @@ -36,6 +36,7 @@ import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.param.StringAndListParam; import ca.uhn.fhir.rest.param.TokenOrListParam; import ca.uhn.fhir.rest.param.TokenParam; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.instance.model.api.IPrimitiveType; @@ -47,7 +48,6 @@ import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.Collections; -import javax.servlet.http.HttpServletRequest; public class JpaResourceDaoPatient extends BaseHapiFhirResourceDao implements IFhirResourceDaoPatient { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/ObservationLastNIndexPersistSvc.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/ObservationLastNIndexPersistSvc.java deleted file mode 100644 index fa8b6fb3274..00000000000 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/ObservationLastNIndexPersistSvc.java +++ /dev/null @@ -1,260 +0,0 @@ -/*- - * #%L - * HAPI FHIR JPA Server - * %% - * Copyright (C) 2014 - 2023 Smile CDR, Inc. - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package ca.uhn.fhir.jpa.dao; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.context.RuntimeSearchParam; -import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; -import ca.uhn.fhir.jpa.model.cross.IBasePersistedResource; -import ca.uhn.fhir.jpa.model.entity.ResourceIndexedSearchParamToken; -import ca.uhn.fhir.jpa.model.util.CodeSystemHash; -import ca.uhn.fhir.jpa.search.lastn.IElasticsearchSvc; -import ca.uhn.fhir.jpa.search.lastn.json.CodeJson; -import ca.uhn.fhir.jpa.search.lastn.json.ObservationJson; -import ca.uhn.fhir.jpa.searchparam.extractor.ISearchParamExtractor; -import ca.uhn.fhir.jpa.searchparam.extractor.PathAndRef; -import ca.uhn.fhir.parser.IParser; -import org.hl7.fhir.instance.model.api.IBase; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.springframework.beans.factory.annotation.Autowired; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; - -public class ObservationLastNIndexPersistSvc { - - @Autowired - private ISearchParamExtractor mySearchParameterExtractor; - - @Autowired(required = false) - private IElasticsearchSvc myElasticsearchSvc; - - @Autowired - private JpaStorageSettings myConfig; - - @Autowired - private FhirContext myContext; - - public void indexObservation(IBaseResource theResource) { - - if (myElasticsearchSvc == null) { - // Elasticsearch is not enabled and therefore no index needs to be updated. - return; - } - - List subjectReferenceElement = - mySearchParameterExtractor.extractValues("Observation.subject", theResource); - String subjectId = subjectReferenceElement.stream() - .map(refElement -> - mySearchParameterExtractor.extractReferenceLinkFromResource(refElement, "Observation.subject")) - .filter(Objects::nonNull) - .map(PathAndRef::getRef) - .filter(Objects::nonNull) - .map(subjectRef -> subjectRef.getReferenceElement().getValue()) - .filter(Objects::nonNull) - .findFirst() - .orElse(null); - - Date effectiveDtm = null; - List effectiveDateElement = - mySearchParameterExtractor.extractValues("Observation.effective", theResource); - if (effectiveDateElement.size() > 0) { - effectiveDtm = mySearchParameterExtractor.extractDateFromResource( - effectiveDateElement.get(0), "Observation.effective"); - } - - List observationCodeCodeableConcepts = - mySearchParameterExtractor.extractValues("Observation.code", theResource); - - // Only index for lastn if Observation has a code - if (observationCodeCodeableConcepts.size() == 0) { - return; - } - - List observationCategoryCodeableConcepts = - mySearchParameterExtractor.extractValues("Observation.category", theResource); - - createOrUpdateIndexedObservation( - theResource, - effectiveDtm, - subjectId, - observationCodeCodeableConcepts, - observationCategoryCodeableConcepts); - } - - private void createOrUpdateIndexedObservation( - IBaseResource theResource, - Date theEffectiveDtm, - String theSubjectId, - List theObservationCodeCodeableConcepts, - List theObservationCategoryCodeableConcepts) { - String resourcePID = theResource.getIdElement().getIdPart(); - - // Determine if an index already exists for Observation: - ObservationJson indexedObservation = null; - if (resourcePID != null) { - indexedObservation = myElasticsearchSvc.getObservationDocument(resourcePID); - } - if (indexedObservation == null) { - indexedObservation = new ObservationJson(); - } - - indexedObservation.setEffectiveDtm(theEffectiveDtm); - indexedObservation.setIdentifier(resourcePID); - if (myConfig.isStoreResourceInHSearchIndex()) { - indexedObservation.setResource(encodeResource(theResource)); - } - indexedObservation.setSubject(theSubjectId); - - addCodeToObservationIndex(theObservationCodeCodeableConcepts, indexedObservation); - - addCategoriesToObservationIndex(theObservationCategoryCodeableConcepts, indexedObservation); - - myElasticsearchSvc.createOrUpdateObservationIndex(resourcePID, indexedObservation); - } - - private String encodeResource(IBaseResource theResource) { - IParser parser = myContext.newJsonParser(); - return parser.encodeResourceToString(theResource); - } - - private void addCodeToObservationIndex( - List theObservationCodeCodeableConcepts, ObservationJson theIndexedObservation) { - // Determine if a Normalized ID was created previously for Observation Code - String existingObservationCodeNormalizedId = - getCodeCodeableConceptId(theObservationCodeCodeableConcepts.get(0)); - - // Create/update normalized Observation Code index record - CodeJson codeableConceptField = - getCodeCodeableConcept(theObservationCodeCodeableConcepts.get(0), existingObservationCodeNormalizedId); - - myElasticsearchSvc.createOrUpdateObservationCodeIndex( - codeableConceptField.getCodeableConceptId(), codeableConceptField); - - theIndexedObservation.setCode(codeableConceptField); - } - - private void addCategoriesToObservationIndex( - List observationCategoryCodeableConcepts, ObservationJson indexedObservation) { - // Build CodeableConcept entities for Observation.Category - List categoryCodeableConceptEntities = new ArrayList<>(); - for (IBase categoryCodeableConcept : observationCategoryCodeableConcepts) { - // Build CodeableConcept entities for each category CodeableConcept - categoryCodeableConceptEntities.add(getCategoryCodeableConceptEntities(categoryCodeableConcept)); - } - indexedObservation.setCategories(categoryCodeableConceptEntities); - } - - private CodeJson getCategoryCodeableConceptEntities(IBase theValue) { - String text = mySearchParameterExtractor.getDisplayTextFromCodeableConcept(theValue); - CodeJson categoryCodeableConcept = new CodeJson(); - categoryCodeableConcept.setCodeableConceptText(text); - - List codings = mySearchParameterExtractor.getCodingsFromCodeableConcept(theValue); - for (IBase nextCoding : codings) { - addCategoryCoding(nextCoding, categoryCodeableConcept); - } - return categoryCodeableConcept; - } - - private CodeJson getCodeCodeableConcept(IBase theValue, String observationCodeNormalizedId) { - String text = mySearchParameterExtractor.getDisplayTextFromCodeableConcept(theValue); - CodeJson codeCodeableConcept = new CodeJson(); - codeCodeableConcept.setCodeableConceptText(text); - codeCodeableConcept.setCodeableConceptId(observationCodeNormalizedId); - - List codings = mySearchParameterExtractor.getCodingsFromCodeableConcept(theValue); - for (IBase nextCoding : codings) { - addCodeCoding(nextCoding, codeCodeableConcept); - } - - return codeCodeableConcept; - } - - private String getCodeCodeableConceptId(IBase theValue) { - List codings = mySearchParameterExtractor.getCodingsFromCodeableConcept(theValue); - Optional codeCodeableConceptIdOptional = Optional.empty(); - - for (IBase nextCoding : codings) { - ResourceIndexedSearchParamToken param = mySearchParameterExtractor.createSearchParamForCoding( - "Observation", - new RuntimeSearchParam(null, null, "code", null, null, null, null, null, null, null), - nextCoding); - if (param != null) { - String system = param.getSystem(); - String code = param.getValue(); - String text = mySearchParameterExtractor.getDisplayTextForCoding(nextCoding); - - String codeSystemHash = String.valueOf(CodeSystemHash.hashCodeSystem(system, code)); - CodeJson codeCodeableConceptDocument = - myElasticsearchSvc.getObservationCodeDocument(codeSystemHash, text); - if (codeCodeableConceptDocument != null) { - codeCodeableConceptIdOptional = Optional.of(codeCodeableConceptDocument.getCodeableConceptId()); - break; - } - } - } - - return codeCodeableConceptIdOptional.orElse(UUID.randomUUID().toString()); - } - - private void addCategoryCoding(IBase theValue, CodeJson theCategoryCodeableConcept) { - ResourceIndexedSearchParamToken param = mySearchParameterExtractor.createSearchParamForCoding( - "Observation", - new RuntimeSearchParam(null, null, "category", null, null, null, null, null, null, null), - theValue); - if (param != null) { - String system = param.getSystem(); - String code = param.getValue(); - String text = mySearchParameterExtractor.getDisplayTextForCoding(theValue); - theCategoryCodeableConcept.addCoding(system, code, text); - } - } - - private void addCodeCoding(IBase theValue, CodeJson theObservationCode) { - ResourceIndexedSearchParamToken param = mySearchParameterExtractor.createSearchParamForCoding( - "Observation", - new RuntimeSearchParam(null, null, "code", null, null, null, null, null, null, null), - theValue); - if (param != null) { - String system = param.getSystem(); - String code = param.getValue(); - String text = mySearchParameterExtractor.getDisplayTextForCoding(theValue); - theObservationCode.addCoding(system, code, text); - } - } - - public void deleteObservationIndex(IBasePersistedResource theEntity) { - if (myElasticsearchSvc == null) { - // Elasticsearch is not enabled and therefore no index needs to be updated. - return; - } - - ObservationJson deletedObservationLastNEntity = - myElasticsearchSvc.getObservationDocument(theEntity.getIdDt().getIdPart()); - if (deletedObservationLastNEntity != null) { - myElasticsearchSvc.deleteObservationDocument(deletedObservationLastNEntity.getIdentifier()); - } - } -} diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/TransactionProcessor.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/TransactionProcessor.java index 16d58ec0be6..437677f99c5 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/TransactionProcessor.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/TransactionProcessor.java @@ -44,6 +44,16 @@ import ca.uhn.fhir.util.StopWatch; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.PersistenceException; +import jakarta.persistence.Tuple; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.apache.commons.lang3.Validate; import org.hibernate.internal.SessionImpl; import org.hl7.fhir.instance.model.api.IBase; @@ -65,16 +75,6 @@ import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.Nullable; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.PersistenceException; -import javax.persistence.Tuple; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import static ca.uhn.fhir.util.UrlUtil.determineResourceTypeInResourceUrl; import static org.apache.commons.lang3.StringUtils.countMatches; @@ -367,29 +367,25 @@ public class TransactionProcessor extends BaseTransactionProcessor { CriteriaBuilder cb = myEntityManager.getCriteriaBuilder(); CriteriaQuery cq = cb.createTupleQuery(); Root from = cq.from(ResourceIndexedSearchParamToken.class); - cq.multiselect( - from.get("myResourcePid").as(Long.class), - from.get(theIndexColumnName).as(Long.class)); + cq.multiselect(from.get("myResourcePid"), from.get(theIndexColumnName)); Predicate masterPredicate; if (theHashesForIndexColumn.size() == 1) { masterPredicate = cb.equal( - from.get(theIndexColumnName).as(Long.class), + from.get(theIndexColumnName), theHashesForIndexColumn.iterator().next()); } else { - masterPredicate = from.get(theIndexColumnName).as(Long.class).in(theHashesForIndexColumn); + masterPredicate = from.get(theIndexColumnName).in(theHashesForIndexColumn); } if (myPartitionSettings.isPartitioningEnabled() && !myPartitionSettings.isIncludePartitionInSearchHashes()) { if (theRequestPartitionId.isDefaultPartition()) { - Predicate partitionIdCriteria = - cb.isNull(from.get("myPartitionIdValue").as(Integer.class)); + Predicate partitionIdCriteria = cb.isNull(from.get("myPartitionIdValue")); masterPredicate = cb.and(partitionIdCriteria, masterPredicate); } else if (!theRequestPartitionId.isAllPartitions()) { - Predicate partitionIdCriteria = from.get("myPartitionIdValue") - .as(Integer.class) - .in(theRequestPartitionId.getPartitionIds()); + Predicate partitionIdCriteria = + from.get("myPartitionIdValue").in(theRequestPartitionId.getPartitionIds()); masterPredicate = cb.and(partitionIdCriteria, masterPredicate); } } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/data/IResourceHistoryTableDao.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/data/IResourceHistoryTableDao.java index bd65315bf30..b74a1b757f2 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/data/IResourceHistoryTableDao.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/data/IResourceHistoryTableDao.java @@ -44,30 +44,30 @@ public interface IResourceHistoryTableDao extends JpaRepository :dontWantVersion") Slice findForResourceId( Pageable thePage, @Param("resId") Long theId, @Param("dontWantVersion") Long theDontWantVersion); @Query( - "SELECT t FROM ResourceHistoryTable t LEFT OUTER JOIN FETCH t.myProvenance WHERE t.myResourceId = :resId AND t.myResourceVersion != :dontWantVersion") + "SELECT t FROM ResourceHistoryTable t LEFT OUTER JOIN FETCH t.myProvenance WHERE t.myResourceId = :resId AND t.myResourceVersion <> :dontWantVersion") Slice findForResourceIdAndReturnEntitiesAndFetchProvenance( Pageable thePage, @Param("resId") Long theId, @Param("dontWantVersion") Long theDontWantVersion); @Query("" + "SELECT v.myId FROM ResourceHistoryTable v " + "LEFT OUTER JOIN ResourceTable t ON (v.myResourceId = t.myId) " - + "WHERE v.myResourceVersion != t.myVersion AND " + + "WHERE v.myResourceVersion <> t.myVersion AND " + "t.myId = :resId") Slice findIdsOfPreviousVersionsOfResourceId(Pageable thePage, @Param("resId") Long theResourceId); @Query("" + "SELECT v.myId FROM ResourceHistoryTable v " + "LEFT OUTER JOIN ResourceTable t ON (v.myResourceId = t.myId) " - + "WHERE v.myResourceVersion != t.myVersion AND " + + "WHERE v.myResourceVersion <> t.myVersion AND " + "t.myResourceType = :restype") Slice findIdsOfPreviousVersionsOfResources(Pageable thePage, @Param("restype") String theResourceName); @Query("" + "SELECT v.myId FROM ResourceHistoryTable v " + "LEFT OUTER JOIN ResourceTable t ON (v.myResourceId = t.myId) " - + "WHERE v.myResourceVersion != t.myVersion") + + "WHERE v.myResourceVersion <> t.myVersion") Slice findIdsOfPreviousVersionsOfResources(Pageable thePage); @Modifying diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/data/custom/IResourceTableDaoImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/data/custom/IResourceTableDaoImpl.java index a8d86d69e43..208e8c78d1e 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/data/custom/IResourceTableDaoImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/data/custom/IResourceTableDaoImpl.java @@ -19,12 +19,12 @@ */ package ca.uhn.fhir.jpa.dao.data.custom; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; @Component /** diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/dstu3/FhirSystemDaoDstu3.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/dstu3/FhirSystemDaoDstu3.java index ced37678fdf..2865edc0c9b 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/dstu3/FhirSystemDaoDstu3.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/dstu3/FhirSystemDaoDstu3.java @@ -23,13 +23,13 @@ import ca.uhn.fhir.jpa.dao.BaseHapiFhirSystemDao; import ca.uhn.fhir.jpa.dao.JpaResourceDao; import ca.uhn.fhir.jpa.model.entity.TagDefinition; import ca.uhn.fhir.rest.api.server.RequestDetails; +import jakarta.persistence.TypedQuery; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.Meta; import org.hl7.fhir.instance.model.api.IBaseBundle; import java.util.Collection; import java.util.List; -import javax.persistence.TypedQuery; public class FhirSystemDaoDstu3 extends BaseHapiFhirSystemDao { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/expunge/ExpungeEverythingService.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/expunge/ExpungeEverythingService.java index 34f247edce7..9c192fa58e8 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/expunge/ExpungeEverythingService.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/expunge/ExpungeEverythingService.java @@ -78,6 +78,16 @@ import ca.uhn.fhir.rest.server.provider.ProviderConstants; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.rest.server.util.CompositeInterceptorBroadcaster; import ca.uhn.fhir.util.StopWatch; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.Query; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.metamodel.EntityType; +import jakarta.persistence.metamodel.Metamodel; +import jakarta.persistence.metamodel.SingularAttribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -85,14 +95,9 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import java.util.List; +import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; @Service public class ExpungeEverythingService implements IExpungeEverythingService { @@ -229,6 +234,7 @@ public class ExpungeEverythingService implements IExpungeEverythingService { expungeEverythingByTypeWithoutPurging(theRequest, ResourceHistoryTable.class, requestPartitionId)); counter.addAndGet( expungeEverythingByTypeWithoutPurging(theRequest, ResourceSearchUrlEntity.class, requestPartitionId)); + int counterBefore = counter.get(); counter.addAndGet(expungeEverythingByTypeWithoutPurging(theRequest, ResourceTable.class, requestPartitionId)); counter.addAndGet(expungeEverythingByTypeWithoutPurging(theRequest, PartitionEntity.class, requestPartitionId)); @@ -257,8 +263,10 @@ public class ExpungeEverythingService implements IExpungeEverythingService { myMemoryCacheService.invalidateAllCaches(); } - private int expungeEverythingByTypeWithoutPurging( - RequestDetails theRequest, Class theEntityType, RequestPartitionId theRequestPartitionId) { + private int expungeEverythingByTypeWithoutPurging( + RequestDetails theRequest, Class theEntityType, RequestPartitionId theRequestPartitionId) { + HapiTransactionService.noTransactionAllowed(); + int outcome = 0; while (true) { StopWatch sw = new StopWatch(); @@ -268,16 +276,49 @@ public class ExpungeEverythingService implements IExpungeEverythingService { .withPropagation(Propagation.REQUIRES_NEW) .withRequestPartitionId(theRequestPartitionId) .execute(() -> { - CriteriaBuilder cb = myEntityManager.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(theEntityType); - cq.from(theEntityType); - TypedQuery query = myEntityManager.createQuery(cq); - query.setMaxResults(1000); - List results = query.getResultList(); - for (Object result : results) { - myEntityManager.remove(result); + + /* + * This method uses a nice efficient mechanism where we figure out the PID datatype + * and load only the PIDs and delete by PID for all resource types except ResourceTable. + * We delete ResourceTable using the entitymanager so that Hibernate Search knows to + * delete the corresponding records it manages in ElasticSearch. See + * FhirResourceDaoR4SearchWithElasticSearchIT for a test that fails without the + * block below. + */ + if (ResourceTable.class.equals(theEntityType)) { + CriteriaBuilder cb = myEntityManager.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(theEntityType); + cq.from(theEntityType); + TypedQuery query = myEntityManager.createQuery(cq); + query.setMaxResults(800); + List results = query.getResultList(); + for (Object result : results) { + myEntityManager.remove(result); + } + return results.size(); } - return results.size(); + + Metamodel metamodel = myEntityManager.getMetamodel(); + EntityType entity = metamodel.entity(theEntityType); + Set> singularAttributes = entity.getSingularAttributes(); + String idProperty = null; + for (SingularAttribute singularAttribute : singularAttributes) { + if (singularAttribute.isId()) { + idProperty = singularAttribute.getName(); + break; + } + } + + Query nativeQuery = myEntityManager.createQuery( + "SELECT " + idProperty + " FROM " + theEntityType.getSimpleName()); + nativeQuery.setMaxResults(800); + List pids = nativeQuery.getResultList(); + + nativeQuery = myEntityManager.createQuery("DELETE FROM " + theEntityType.getSimpleName() + + " WHERE " + idProperty + " IN (:pids)"); + nativeQuery.setParameter("pids", pids); + nativeQuery.executeUpdate(); + return pids.size(); }); outcome += count; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/DaoSearchParamSynchronizer.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/DaoSearchParamSynchronizer.java index 458f5a428d5..fb6dda60d86 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/DaoSearchParamSynchronizer.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/DaoSearchParamSynchronizer.java @@ -24,18 +24,22 @@ import ca.uhn.fhir.jpa.model.entity.ResourceTable; import ca.uhn.fhir.jpa.searchparam.extractor.ResourceIndexedSearchParams; import ca.uhn.fhir.jpa.util.AddRemoveCount; import com.google.common.annotations.VisibleForTesting; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; @Service public class DaoSearchParamSynchronizer { + private static final Logger ourLog = LoggerFactory.getLogger(DaoSearchParamSynchronizer.class); + @PersistenceContext(type = PersistenceContextType.TRANSACTION) protected EntityManager myEntityManager; @@ -89,9 +93,13 @@ public class DaoSearchParamSynchronizer { tryToReuseIndexEntities(paramsToRemove, paramsToAdd); for (T next : paramsToRemove) { + if (!myEntityManager.contains(next)) { + // If a resource is created and deleted in the same transaction, we can end up + // in a state where we're deleting entities that don't actually exist. Hibernate + // 6 is stricter about this, so we skip here. + continue; + } myEntityManager.remove(next); - theEntity.getParamsQuantity().remove(next); - theEntity.getParamsQuantityNormalized().remove(next); } for (T next : paramsToAdd) { myEntityManager.merge(next); diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/IdHelperService.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/IdHelperService.java index cee2c8bfd08..e23720ad33d 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/IdHelperService.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/IdHelperService.java @@ -42,6 +42,15 @@ import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ListMultimap; import com.google.common.collect.MultimapBuilder; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.Tuple; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IAnyResource; @@ -66,15 +75,6 @@ import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.Tuple; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import static ca.uhn.fhir.jpa.search.builder.predicate.BaseJoiningPredicateBuilder.replaceDefaultPartitionIdIfNonNull; import static org.apache.commons.lang3.StringUtils.isNotBlank; @@ -377,10 +377,7 @@ public class IdHelperService implements IIdHelperService { * Only PG, and MSSql support INCLUDE COLUMNS. * @see AddIndexTask.generateSql */ - criteriaQuery.multiselect( - from.get("myId").as(Long.class), - from.get("myResourceType").as(String.class), - from.get("myFhirId").as(String.class)); + criteriaQuery.multiselect(from.get("myId"), from.get("myResourceType"), from.get("myFhirId")); // one create one clause per id. List predicates = new ArrayList<>(theIds.size()); @@ -389,11 +386,11 @@ public class IdHelperService implements IIdHelperService { List andPredicates = new ArrayList<>(3); if (isNotBlank(next.getResourceType())) { - Predicate typeCriteria = cb.equal(from.get("myResourceType").as(String.class), next.getResourceType()); + Predicate typeCriteria = cb.equal(from.get("myResourceType"), next.getResourceType()); andPredicates.add(typeCriteria); } - Predicate idCriteria = cb.equal(from.get("myFhirId").as(String.class), next.getIdPart()); + Predicate idCriteria = cb.equal(from.get("myFhirId"), next.getIdPart()); andPredicates.add(idCriteria); getOptionalPartitionPredicate(theRequestPartitionId, cb, from).ifPresent(andPredicates::add); predicates.add(cb.and(andPredicates.toArray(EMPTY_PREDICATE_ARRAY))); @@ -431,19 +428,16 @@ public class IdHelperService implements IIdHelperService { if (myPartitionSettings.isAllowUnqualifiedCrossPartitionReference()) { return Optional.empty(); } else if (theRequestPartitionId.isDefaultPartition() && myPartitionSettings.getDefaultPartitionId() == null) { - Predicate partitionIdCriteria = - cb.isNull(from.get("myPartitionIdValue").as(Integer.class)); + Predicate partitionIdCriteria = cb.isNull(from.get("myPartitionIdValue")); return Optional.of(partitionIdCriteria); } else if (!theRequestPartitionId.isAllPartitions()) { List partitionIds = theRequestPartitionId.getPartitionIds(); partitionIds = replaceDefaultPartitionIdIfNonNull(myPartitionSettings, partitionIds); if (partitionIds.size() > 1) { - Predicate partitionIdCriteria = - from.get("myPartitionIdValue").as(Integer.class).in(partitionIds); + Predicate partitionIdCriteria = from.get("myPartitionIdValue").in(partitionIds); return Optional.of(partitionIdCriteria); } else if (partitionIds.size() == 1) { - Predicate partitionIdCriteria = - cb.equal(from.get("myPartitionIdValue").as(Integer.class), partitionIds.get(0)); + Predicate partitionIdCriteria = cb.equal(from.get("myPartitionIdValue"), partitionIds.get(0)); return Optional.of(partitionIdCriteria); } } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/SearchParamWithInlineReferencesExtractor.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/SearchParamWithInlineReferencesExtractor.java index c77d2e206ce..24b04c5e508 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/SearchParamWithInlineReferencesExtractor.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/index/SearchParamWithInlineReferencesExtractor.java @@ -40,6 +40,9 @@ import ca.uhn.fhir.rest.api.server.storage.TransactionDetails; import ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException; import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import com.google.common.annotations.VisibleForTesting; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; import org.hl7.fhir.instance.model.api.IBaseResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; @@ -49,9 +52,6 @@ import java.util.Collection; import java.util.Iterator; import java.util.stream.Collectors; import javax.annotation.Nullable; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; @Service @Lazy diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/mdm/MdmLinkDaoJpaImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/mdm/MdmLinkDaoJpaImpl.java index 2206f36f829..b915187a6f6 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/mdm/MdmLinkDaoJpaImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/mdm/MdmLinkDaoJpaImpl.java @@ -38,6 +38,16 @@ import ca.uhn.fhir.mdm.dao.IMdmLinkDao; import ca.uhn.fhir.mdm.model.MdmPidTuple; import ca.uhn.fhir.rest.api.SortOrderEnum; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Expression; +import jakarta.persistence.criteria.Order; +import jakarta.persistence.criteria.Path; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; +import jakarta.validation.constraints.NotNull; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang3.ObjectUtils; @@ -65,16 +75,6 @@ import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Expression; -import javax.persistence.criteria.Order; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import javax.validation.constraints.NotNull; import static ca.uhn.fhir.mdm.api.params.MdmQuerySearchParameters.GOLDEN_RESOURCE_NAME; import static ca.uhn.fhir.mdm.api.params.MdmQuerySearchParameters.GOLDEN_RESOURCE_PID_NAME; @@ -88,10 +88,10 @@ public class MdmLinkDaoJpaImpl implements IMdmLinkDao { private static final Logger ourLog = LoggerFactory.getLogger(MdmLinkDaoJpaImpl.class); @Autowired - IMdmLinkJpaRepository myMdmLinkDao; + protected EntityManager myEntityManager; @Autowired - protected EntityManager myEntityManager; + IMdmLinkJpaRepository myMdmLinkDao; @Autowired private IIdHelperService myIdHelperService; @@ -247,6 +247,8 @@ public class MdmLinkDaoJpaImpl implements IMdmLinkDao { @Override public Page search(MdmQuerySearchParameters theParams) { + Long totalResults = countTotalResults(theParams); + CriteriaBuilder criteriaBuilder = myEntityManager.getCriteriaBuilder(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(MdmLink.class); Root from = criteriaQuery.from(MdmLink.class); @@ -258,14 +260,9 @@ public class MdmLinkDaoJpaImpl implements IMdmLinkDao { if (!orderList.isEmpty()) { criteriaQuery.orderBy(orderList); } - TypedQuery typedQuery = myEntityManager.createQuery(criteriaQuery.where(finalQuery)); - CriteriaQuery countQuery = criteriaBuilder.createQuery(Long.class); - countQuery.select(criteriaBuilder.count(countQuery.from(MdmLink.class))).where(finalQuery); - - Long totalResults = myEntityManager.createQuery(countQuery).getSingleResult(); MdmPageRequest pageRequest = theParams.getPageRequest(); - + TypedQuery typedQuery = myEntityManager.createQuery(criteriaQuery.where(finalQuery)); List result = typedQuery .setFirstResult(pageRequest.getOffset()) .setMaxResults(pageRequest.getCount()) @@ -274,13 +271,26 @@ public class MdmLinkDaoJpaImpl implements IMdmLinkDao { return new PageImpl<>(result, PageRequest.of(pageRequest.getPage(), pageRequest.getCount()), totalResults); } + private Long countTotalResults(MdmQuerySearchParameters theParams) { + CriteriaBuilder criteriaBuilder = myEntityManager.getCriteriaBuilder(); + CriteriaQuery countQuery = criteriaBuilder.createQuery(Long.class); + Root from = countQuery.from(MdmLink.class); + + List andPredicates = buildPredicates(theParams, criteriaBuilder, from); + Predicate finalQuery = criteriaBuilder.and(andPredicates.toArray(new Predicate[0])); + + countQuery.select(criteriaBuilder.count(from)).where(finalQuery); + + return myEntityManager.createQuery(countQuery).getSingleResult(); + } + @NotNull private List buildPredicates( MdmQuerySearchParameters theParams, CriteriaBuilder criteriaBuilder, Root from) { List andPredicates = new ArrayList<>(); if (theParams.getGoldenResourceId() != null) { Predicate goldenResourcePredicate = criteriaBuilder.equal( - from.get(GOLDEN_RESOURCE_PID_NAME).as(Long.class), + from.get(GOLDEN_RESOURCE_PID_NAME), (myIdHelperService.getPidOrThrowException( RequestPartitionId.allPartitions(), theParams.getGoldenResourceId())) .getId()); @@ -288,33 +298,31 @@ public class MdmLinkDaoJpaImpl implements IMdmLinkDao { } if (theParams.getSourceId() != null) { Predicate sourceIdPredicate = criteriaBuilder.equal( - from.get(SOURCE_PID_NAME).as(Long.class), + from.get(SOURCE_PID_NAME), (myIdHelperService.getPidOrThrowException( RequestPartitionId.allPartitions(), theParams.getSourceId())) .getId()); andPredicates.add(sourceIdPredicate); } if (theParams.getMatchResult() != null) { - Predicate matchResultPredicate = criteriaBuilder.equal( - from.get(MATCH_RESULT_NAME).as(MdmMatchResultEnum.class), theParams.getMatchResult()); + Predicate matchResultPredicate = + criteriaBuilder.equal(from.get(MATCH_RESULT_NAME), theParams.getMatchResult()); andPredicates.add(matchResultPredicate); } if (theParams.getLinkSource() != null) { - Predicate linkSourcePredicate = criteriaBuilder.equal( - from.get(LINK_SOURCE_NAME).as(MdmLinkSourceEnum.class), theParams.getLinkSource()); + Predicate linkSourcePredicate = + criteriaBuilder.equal(from.get(LINK_SOURCE_NAME), theParams.getLinkSource()); andPredicates.add(linkSourcePredicate); } if (!CollectionUtils.isEmpty(theParams.getPartitionIds())) { - Expression exp = - from.get(PARTITION_ID_NAME).get(PARTITION_ID_NAME).as(Integer.class); + Expression exp = from.get(PARTITION_ID_NAME).get(PARTITION_ID_NAME); Predicate linkSourcePredicate = exp.in(theParams.getPartitionIds()); andPredicates.add(linkSourcePredicate); } if (theParams.getResourceType() != null) { Predicate resourceTypePredicate = criteriaBuilder.equal( - from.get(GOLDEN_RESOURCE_NAME).get(RESOURCE_TYPE_NAME).as(String.class), - theParams.getResourceType()); + from.get(GOLDEN_RESOURCE_NAME).get(RESOURCE_TYPE_NAME), theParams.getResourceType()); andPredicates.add(resourceTypePredicate); } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/mdm/MdmMetricSvcJpaImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/mdm/MdmMetricSvcJpaImpl.java index db20645a928..3bc7bd5ecfb 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/mdm/MdmMetricSvcJpaImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/mdm/MdmMetricSvcJpaImpl.java @@ -29,15 +29,15 @@ import ca.uhn.fhir.mdm.model.MdmLinkMetrics; import ca.uhn.fhir.mdm.model.MdmLinkScoreMetrics; import ca.uhn.fhir.mdm.model.MdmMetrics; import ca.uhn.fhir.mdm.model.MdmResourceMetrics; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Query; import org.springframework.transaction.annotation.Transactional; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Query; public class MdmMetricSvcJpaImpl extends BaseMdmMetricSvc { @@ -128,7 +128,7 @@ public class MdmMetricSvcJpaImpl extends BaseMdmMetricSvc { int length = row.length; for (int i = 0; i < length; i++) { // if there's nothing in the db, these values will all be null - BigInteger bi = row[i] != null ? (BigInteger) row[i] : BigInteger.valueOf(0); + Number bi = row[i] != null ? (Number) row[i] : BigInteger.valueOf(0); double bucket = getBucket(i); if (i == 0) { metrics.addScore(NULL_VALUE, bi.longValue()); diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4/FhirSystemDaoR4.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4/FhirSystemDaoR4.java index 74bbcf58162..2ed5f0c2cca 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4/FhirSystemDaoR4.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4/FhirSystemDaoR4.java @@ -23,13 +23,13 @@ import ca.uhn.fhir.jpa.dao.BaseHapiFhirSystemDao; import ca.uhn.fhir.jpa.dao.JpaResourceDao; import ca.uhn.fhir.jpa.model.entity.TagDefinition; import ca.uhn.fhir.rest.api.server.RequestDetails; +import jakarta.persistence.TypedQuery; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Meta; import java.util.Collection; import java.util.List; -import javax.persistence.TypedQuery; public class FhirSystemDaoR4 extends BaseHapiFhirSystemDao { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4b/FhirSystemDaoR4B.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4b/FhirSystemDaoR4B.java index 8867aa89d13..b950fe13981 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4b/FhirSystemDaoR4B.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r4b/FhirSystemDaoR4B.java @@ -23,13 +23,13 @@ import ca.uhn.fhir.jpa.dao.BaseHapiFhirSystemDao; import ca.uhn.fhir.jpa.dao.JpaResourceDao; import ca.uhn.fhir.jpa.model.entity.TagDefinition; import ca.uhn.fhir.rest.api.server.RequestDetails; +import jakarta.persistence.TypedQuery; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.r4b.model.Bundle; import org.hl7.fhir.r4b.model.Meta; import java.util.Collection; import java.util.List; -import javax.persistence.TypedQuery; public class FhirSystemDaoR4B extends BaseHapiFhirSystemDao { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r5/FhirSystemDaoR5.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r5/FhirSystemDaoR5.java index 5925f9ee531..b1af9191e57 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r5/FhirSystemDaoR5.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/r5/FhirSystemDaoR5.java @@ -23,13 +23,13 @@ import ca.uhn.fhir.jpa.dao.BaseHapiFhirSystemDao; import ca.uhn.fhir.jpa.dao.JpaResourceDao; import ca.uhn.fhir.jpa.model.entity.TagDefinition; import ca.uhn.fhir.rest.api.server.RequestDetails; +import jakarta.persistence.TypedQuery; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.r5.model.Bundle; import org.hl7.fhir.r5.model.Meta; import java.util.Collection; import java.util.List; -import javax.persistence.TypedQuery; public class FhirSystemDaoR5 extends BaseHapiFhirSystemDao { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/search/PathContext.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/search/PathContext.java index eb87d87dcfd..f059361e7c6 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/search/PathContext.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/search/PathContext.java @@ -19,6 +19,7 @@ */ package ca.uhn.fhir.jpa.dao.search; +import org.hibernate.search.engine.search.predicate.SearchPredicate; import org.hibernate.search.engine.search.predicate.dsl.*; import org.hibernate.search.util.common.annotation.Incubating; @@ -108,80 +109,153 @@ class PathContext implements SearchPredicateFactory { // implement SearchPredicateFactory + @Override public MatchAllPredicateOptionsStep matchAll() { return myPredicateFactory.matchAll(); } + @Override + public MatchNonePredicateFinalStep matchNone() { + return myPredicateFactory.matchNone(); + } + + @Override public MatchIdPredicateMatchingStep id() { return myPredicateFactory.id(); } + @Override public BooleanPredicateClausesStep bool() { return myPredicateFactory.bool(); } + @Override public PredicateFinalStep bool(Consumer> clauseContributor) { return myPredicateFactory.bool(clauseContributor); } + @Override + public SimpleBooleanPredicateClausesStep and() { + return myPredicateFactory.and(); + } + + @Override + public SimpleBooleanPredicateOptionsStep and( + SearchPredicate theSearchPredicate, SearchPredicate... theSearchPredicates) { + return myPredicateFactory.and(theSearchPredicate, theSearchPredicates); + } + + @Override + public SimpleBooleanPredicateOptionsStep and( + PredicateFinalStep thePredicateFinalStep, PredicateFinalStep... thePredicateFinalSteps) { + return myPredicateFactory.and(thePredicateFinalStep, thePredicateFinalSteps); + } + + @Override + public SimpleBooleanPredicateClausesStep or() { + return myPredicateFactory.or(); + } + + @Override + public SimpleBooleanPredicateOptionsStep or( + SearchPredicate theSearchPredicate, SearchPredicate... theSearchPredicates) { + return myPredicateFactory.or(theSearchPredicate, theSearchPredicates); + } + + @Override + public SimpleBooleanPredicateOptionsStep or( + PredicateFinalStep thePredicateFinalStep, PredicateFinalStep... thePredicateFinalSteps) { + return myPredicateFactory.or(thePredicateFinalStep, thePredicateFinalSteps); + } + + @Override + public NotPredicateFinalStep not(SearchPredicate theSearchPredicate) { + return myPredicateFactory.not(theSearchPredicate); + } + + @Override + public NotPredicateFinalStep not(PredicateFinalStep thePredicateFinalStep) { + return myPredicateFactory.not(thePredicateFinalStep); + } + + @Override public MatchPredicateFieldStep match() { return myPredicateFactory.match(); } + @Override public RangePredicateFieldStep range() { return myPredicateFactory.range(); } + @Override public PhrasePredicateFieldStep phrase() { return myPredicateFactory.phrase(); } + @Override public WildcardPredicateFieldStep wildcard() { return myPredicateFactory.wildcard(); } + @Override public RegexpPredicateFieldStep regexp() { return myPredicateFactory.regexp(); } + @Override public TermsPredicateFieldStep terms() { return myPredicateFactory.terms(); } + @Override public NestedPredicateFieldStep nested() { return myPredicateFactory.nested(); } + @Override + public NestedPredicateClausesStep nested(String theObjectFieldPath) { + return myPredicateFactory.nested(theObjectFieldPath); + } + + @Override public SimpleQueryStringPredicateFieldStep simpleQueryString() { return myPredicateFactory.simpleQueryString(); } + @Override public ExistsPredicateFieldStep exists() { return myPredicateFactory.exists(); } + @Override public SpatialPredicateInitialStep spatial() { return myPredicateFactory.spatial(); } + @Override @Incubating public NamedPredicateOptionsStep named(String path) { return myPredicateFactory.named(path); } + @Override public T extension(SearchPredicateFactoryExtension extension) { return myPredicateFactory.extension(extension); } + @Override public SearchPredicateFactoryExtensionIfSupportedStep extension() { return myPredicateFactory.extension(); } + @Override @Incubating public SearchPredicateFactory withRoot(String objectFieldPath) { return myPredicateFactory.withRoot(objectFieldPath); } + @Override @Incubating public String toAbsolutePath(String relativeFieldPath) { return myPredicateFactory.toAbsolutePath(relativeFieldPath); diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/delete/DeleteConflictFinderService.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/delete/DeleteConflictFinderService.java index 1e52953446b..33a1932a48c 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/delete/DeleteConflictFinderService.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/delete/DeleteConflictFinderService.java @@ -21,13 +21,13 @@ package ca.uhn.fhir.jpa.delete; import ca.uhn.fhir.jpa.model.entity.ResourceLink; import ca.uhn.fhir.jpa.model.entity.ResourceTable; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.TypedQuery; import org.springframework.stereotype.Service; import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.TypedQuery; @Service public class DeleteConflictFinderService { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/delete/batch2/DeleteExpungeSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/delete/batch2/DeleteExpungeSvcImpl.java index 9e7e7ff4474..9aee0268557 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/delete/batch2/DeleteExpungeSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/delete/batch2/DeleteExpungeSvcImpl.java @@ -23,13 +23,13 @@ import ca.uhn.fhir.jpa.api.svc.IDeleteExpungeSvc; import ca.uhn.fhir.jpa.dao.IFulltextSearchSvc; import ca.uhn.fhir.jpa.model.dao.JpaPid; import ca.uhn.fhir.jpa.model.entity.ResourceTable; +import jakarta.persistence.EntityManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; public class DeleteExpungeSvcImpl implements IDeleteExpungeSvc { private static final Logger ourLog = LoggerFactory.getLogger(DeleteExpungeSvcImpl.class); diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/Batch2JobInstanceEntity.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/Batch2JobInstanceEntity.java index dd9205a8f30..311f201d141 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/Batch2JobInstanceEntity.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/Batch2JobInstanceEntity.java @@ -21,24 +21,24 @@ package ca.uhn.fhir.jpa.entity; import ca.uhn.fhir.batch2.model.JobDefinition; import ca.uhn.fhir.batch2.model.StatusEnum; +import jakarta.persistence.Basic; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.Lob; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.Version; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.io.Serializable; import java.util.Date; -import javax.persistence.Basic; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.Lob; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Version; import static ca.uhn.fhir.batch2.model.JobDefinition.ID_MAX_LENGTH; import static ca.uhn.fhir.jpa.entity.Batch2WorkChunkEntity.ERROR_MSG_MAX_LENGTH; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/Batch2WorkChunkEntity.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/Batch2WorkChunkEntity.java index e65c8814faa..159be9b503f 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/Batch2WorkChunkEntity.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/Batch2WorkChunkEntity.java @@ -20,27 +20,27 @@ package ca.uhn.fhir.jpa.entity; import ca.uhn.fhir.batch2.model.WorkChunkStatusEnum; +import jakarta.persistence.Basic; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.Lob; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.Version; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.io.Serializable; import java.util.Date; -import javax.persistence.Basic; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.Lob; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Version; import static ca.uhn.fhir.batch2.model.JobDefinition.ID_MAX_LENGTH; import static ca.uhn.fhir.jpa.entity.Batch2JobInstanceEntity.STATUS_MAX_LENGTH; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportCollectionEntity.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportCollectionEntity.java index 7903eab9004..f564688c247 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportCollectionEntity.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportCollectionEntity.java @@ -20,23 +20,23 @@ package ca.uhn.fhir.jpa.entity; import ca.uhn.fhir.jpa.model.entity.ResourceTable; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Version; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Version; /* * These classes are no longer needed. diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportCollectionFileEntity.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportCollectionFileEntity.java index 96ee1f1f8cc..0dcf6851d52 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportCollectionFileEntity.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportCollectionFileEntity.java @@ -20,19 +20,19 @@ package ca.uhn.fhir.jpa.entity; import ca.uhn.fhir.jpa.model.entity.ResourceTable; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; /* * These classes are no longer needed. diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportJobEntity.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportJobEntity.java index a9bf341724a..8d70aeecbcd 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportJobEntity.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkExportJobEntity.java @@ -19,6 +19,20 @@ */ package ca.uhn.fhir.jpa.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.OneToMany; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.UniqueConstraint; +import jakarta.persistence.Version; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.hl7.fhir.r5.model.InstantType; @@ -27,20 +41,6 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.OneToMany; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.UniqueConstraint; -import javax.persistence.Version; import static ca.uhn.fhir.rest.api.Constants.UUID_LENGTH; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkImportJobEntity.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkImportJobEntity.java index f3151ea2ba4..7fff537777f 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkImportJobEntity.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkImportJobEntity.java @@ -22,22 +22,22 @@ package ca.uhn.fhir.jpa.entity; import ca.uhn.fhir.jpa.bulk.imprt.model.BulkImportJobJson; import ca.uhn.fhir.jpa.bulk.imprt.model.BulkImportJobStatusEnum; import ca.uhn.fhir.jpa.bulk.imprt.model.JobFileRowProcessingModeEnum; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.UniqueConstraint; +import jakarta.persistence.Version; import java.io.Serializable; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.UniqueConstraint; -import javax.persistence.Version; import static ca.uhn.fhir.rest.api.Constants.UUID_LENGTH; import static org.apache.commons.lang3.StringUtils.left; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkImportJobFileEntity.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkImportJobFileEntity.java index 11a2998989f..00ee7169465 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkImportJobFileEntity.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/BulkImportJobFileEntity.java @@ -20,21 +20,21 @@ package ca.uhn.fhir.jpa.entity; import ca.uhn.fhir.jpa.bulk.imprt.model.BulkImportJobFileJson; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.Lob; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import java.io.Serializable; import java.nio.charset.StandardCharsets; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.Lob; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; import static org.apache.commons.lang3.StringUtils.left; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/HapiFhirEnversRevision.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/HapiFhirEnversRevision.java index 9daa452e844..03417a1c66a 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/HapiFhirEnversRevision.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/HapiFhirEnversRevision.java @@ -19,6 +19,13 @@ */ package ca.uhn.fhir.jpa.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import org.apache.commons.lang3.builder.ToStringBuilder; import org.hibernate.envers.RevisionEntity; import org.hibernate.envers.RevisionNumber; @@ -26,13 +33,6 @@ import org.hibernate.envers.RevisionTimestamp; import java.io.Serializable; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; /** * This class exists strictly to override the default names used to generate Hibernate Envers revision table. diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/MdmLink.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/MdmLink.java index 4363bde74c5..3294240982c 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/MdmLink.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/MdmLink.java @@ -26,29 +26,31 @@ import ca.uhn.fhir.mdm.api.IMdmLink; import ca.uhn.fhir.mdm.api.MdmLinkSourceEnum; import ca.uhn.fhir.mdm.api.MdmMatchResultEnum; import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.UniqueConstraint; import org.apache.commons.lang3.builder.ToStringBuilder; +import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.envers.AuditTable; import org.hibernate.envers.Audited; import org.hibernate.envers.NotAudited; +import org.hibernate.type.SqlTypes; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.UniqueConstraint; @Entity @Table( @@ -139,10 +141,12 @@ public class MdmLink extends AuditableBasePartitionable implements IMdmLink { } protected void init700() { + /* ************************************************ + * Start of 6.10 migrations + *********************************************** */ + Builder version = forVersion(VersionEnum.V7_0_0); // new indices on MdmLink diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/packages/JpaPackageCache.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/packages/JpaPackageCache.java index 67af3c9a49d..8f8b0e4fe89 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/packages/JpaPackageCache.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/packages/JpaPackageCache.java @@ -50,6 +50,15 @@ import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import ca.uhn.fhir.util.BinaryUtil; import ca.uhn.fhir.util.ResourceUtil; import ca.uhn.fhir.util.StringUtil; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Join; +import jakarta.persistence.criteria.JoinType; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.apache.commons.collections4.comparators.ReverseComparator; import org.apache.commons.lang3.Validate; import org.hl7.fhir.exceptions.FHIRException; @@ -85,15 +94,6 @@ import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Join; -import javax.persistence.criteria.JoinType; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import static ca.uhn.fhir.jpa.util.QueryParameterUtils.toPredicateArray; import static ca.uhn.fhir.util.StringUtil.toUtf8String; @@ -788,25 +788,23 @@ public class JpaPackageCache extends BasePackageCacheManager implements IHapiPac Join resources = theRoot.join("myResources", JoinType.LEFT); - predicates.add(theCb.equal( - resources.get("myCanonicalUrl").as(String.class), thePackageSearchSpec.getResourceUrl())); + predicates.add(theCb.equal(resources.get("myCanonicalUrl"), thePackageSearchSpec.getResourceUrl())); } if (isNotBlank(thePackageSearchSpec.getDescription())) { String searchTerm = "%" + thePackageSearchSpec.getDescription() + "%"; searchTerm = StringUtil.normalizeStringForSearchIndexing(searchTerm); - predicates.add(theCb.like(theRoot.get("myDescriptionUpper").as(String.class), searchTerm)); + predicates.add(theCb.like(theRoot.get("myDescriptionUpper"), searchTerm)); } if (isNotBlank(thePackageSearchSpec.getFhirVersion())) { if (!thePackageSearchSpec.getFhirVersion().matches("([0-9]+\\.)+[0-9]+")) { FhirVersionEnum versionEnum = FhirVersionEnum.forVersionString(thePackageSearchSpec.getFhirVersion()); if (versionEnum != null) { - predicates.add(theCb.equal(theRoot.get("myFhirVersion").as(FhirVersionEnum.class), versionEnum)); + predicates.add(theCb.equal(theRoot.get("myFhirVersion").as(String.class), versionEnum.name())); } } else { - predicates.add(theCb.like( - theRoot.get("myFhirVersionId").as(String.class), thePackageSearchSpec.getFhirVersion() + "%")); + predicates.add(theCb.like(theRoot.get("myFhirVersionId"), thePackageSearchSpec.getFhirVersion() + "%")); } } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/packages/PackageInstallerSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/packages/PackageInstallerSvcImpl.java index 6b09789cca6..b38552017dd 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/packages/PackageInstallerSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/packages/PackageInstallerSvcImpl.java @@ -50,6 +50,7 @@ import ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException; import ca.uhn.fhir.util.FhirTerser; import ca.uhn.fhir.util.SearchParameterUtil; import com.google.common.annotations.VisibleForTesting; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -69,7 +70,6 @@ import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Optional; -import javax.annotation.PostConstruct; import static ca.uhn.fhir.jpa.packages.util.PackageUtils.DEFAULT_INSTALL_TYPES; import static ca.uhn.fhir.util.SearchParameterUtil.getBaseAsStrings; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/partition/PartitionLookupSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/partition/PartitionLookupSvcImpl.java index 60c04157046..655af28fcbc 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/partition/PartitionLookupSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/partition/PartitionLookupSvcImpl.java @@ -36,6 +36,7 @@ import ca.uhn.fhir.rest.server.exceptions.MethodNotAllowedException; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.ICallable; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,7 +51,6 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.Nonnull; -import javax.annotation.PostConstruct; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderCodeSystem.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderCodeSystem.java index 85b88f5f0bc..671649edb29 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderCodeSystem.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderCodeSystem.java @@ -32,6 +32,7 @@ import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseCoding; import org.hl7.fhir.instance.model.api.IBaseDatatype; import org.hl7.fhir.instance.model.api.IBaseParameters; @@ -43,7 +44,6 @@ import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import java.util.Optional; import java.util.function.Supplier; -import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderComposition.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderComposition.java index 42eb7b187ce..7e733249f96 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderComposition.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderComposition.java @@ -44,7 +44,7 @@ public abstract class BaseJpaResourceProviderComposition */ @Operation(name = JpaConstants.OPERATION_EVERYTHING, idempotent = true, bundleType = BundleTypeEnum.SEARCHSET) public IBundleProvider EncounterInstanceEverything( - javax.servlet.http.HttpServletRequest theServletRequest, + jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IIdType theId, @Description( formalDefinition = @@ -76,7 +76,7 @@ public abstract class BaseJpaResourceProviderEncounter */ @Operation(name = JpaConstants.OPERATION_EVERYTHING, idempotent = true, bundleType = BundleTypeEnum.SEARCHSET) public IBundleProvider EncounterTypeEverything( - javax.servlet.http.HttpServletRequest theServletRequest, + jakarta.servlet.http.HttpServletRequest theServletRequest, @Description( formalDefinition = "Results from this method are returned across multiple pages. This parameter controls the size of those pages.") diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderEncounterDstu2.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderEncounterDstu2.java index ef78d56c9e3..92d43b2ce75 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderEncounterDstu2.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderEncounterDstu2.java @@ -40,7 +40,7 @@ public abstract class BaseJpaResourceProviderEncounterDstu2 extends BaseJpaResou */ @Operation(name = JpaConstants.OPERATION_EVERYTHING, idempotent = true, bundleType = BundleTypeEnum.SEARCHSET) public IBundleProvider EncounterInstanceEverything( - javax.servlet.http.HttpServletRequest theServletRequest, + jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam ca.uhn.fhir.model.primitive.IdDt theId, @Description( formalDefinition = @@ -74,7 +74,7 @@ public abstract class BaseJpaResourceProviderEncounterDstu2 extends BaseJpaResou */ @Operation(name = JpaConstants.OPERATION_EVERYTHING, idempotent = true, bundleType = BundleTypeEnum.SEARCHSET) public IBundleProvider EncounterTypeEverything( - javax.servlet.http.HttpServletRequest theServletRequest, + jakarta.servlet.http.HttpServletRequest theServletRequest, @Description( formalDefinition = "Results from this method are returned across multiple pages. This parameter controls the size of those pages.") diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderObservation.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderObservation.java index da112acefe2..f74a8e684d1 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderObservation.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProviderObservation.java @@ -45,8 +45,8 @@ public abstract class BaseJpaResourceProviderObservation ex idempotent = true, bundleType = BundleTypeEnum.SEARCHSET) public IBundleProvider patientInstanceEverything( - javax.servlet.http.HttpServletRequest theServletRequest, + jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IIdType theId, @Description( shortDefinition = @@ -143,7 +143,7 @@ public abstract class BaseJpaResourceProviderPatient ex idempotent = true, bundleType = BundleTypeEnum.SEARCHSET) public IBundleProvider patientTypeEverything( - javax.servlet.http.HttpServletRequest theServletRequest, + jakarta.servlet.http.HttpServletRequest theServletRequest, @Description( shortDefinition = "Results from this method are returned across multiple pages. This parameter controls the size of those pages.") diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java index 4e5b15d8eab..d264abdca15 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java @@ -35,6 +35,7 @@ import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.provider.ProviderConstants; import ca.uhn.fhir.util.ParametersUtil; import ca.uhn.fhir.util.StopWatch; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.exception.ExceptionUtils; import org.hl7.fhir.instance.model.api.IBaseParameters; import org.slf4j.Logger; @@ -42,7 +43,6 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; -import javax.servlet.http.HttpServletRequest; public abstract class BaseJpaSystemProvider extends BaseStorageSystemProvider implements IJpaSystemProvider { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/JpaConformanceProviderDstu2.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/JpaConformanceProviderDstu2.java index dd06075d423..5cf700a423b 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/JpaConformanceProviderDstu2.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/JpaConformanceProviderDstu2.java @@ -44,12 +44,12 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.provider.dstu2.ServerConformanceProvider; import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.util.ExtensionConstants; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.dstu2.model.Subscription; import java.util.Collections; import java.util.List; import java.util.Map; -import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ProcessMessageProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ProcessMessageProvider.java index 803254ea8bb..695544c4555 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ProcessMessageProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ProcessMessageProvider.java @@ -25,11 +25,10 @@ import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.api.server.RequestDetails; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.http.HttpServletRequest; - import static ca.uhn.fhir.jpa.provider.BaseJpaProvider.endRequest; import static ca.uhn.fhir.jpa.provider.BaseJpaProvider.startRequest; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/TerminologyUploaderProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/TerminologyUploaderProvider.java index 85928273a71..88dc83093ec 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/TerminologyUploaderProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/TerminologyUploaderProvider.java @@ -40,6 +40,7 @@ import ca.uhn.fhir.util.ValidateUtil; import com.google.common.base.Charsets; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.convertors.advisors.impl.BaseAdvisor_30_40; import org.hl7.fhir.convertors.advisors.impl.BaseAdvisor_40_50; import org.hl7.fhir.convertors.factory.VersionConvertorFactory_30_40; @@ -60,7 +61,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; -import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.*; @@ -446,6 +446,10 @@ public class TerminologyUploaderProvider extends BaseJpaProvider { return retVal; } + public void setTerminologyLoaderSvc(ITermLoaderSvc theTermLoaderSvc) { + myTerminologyLoaderSvc = theTermLoaderSvc; + } + public static class FileBackedFileDescriptor implements ITermLoaderSvc.FileDescriptor { private final File myNextFile; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ValueSetOperationProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ValueSetOperationProvider.java index 2bb327cf9c7..ba41fc11e68 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ValueSetOperationProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ValueSetOperationProvider.java @@ -39,6 +39,7 @@ import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.provider.ProviderConstants; import ca.uhn.fhir.util.ParametersUtil; import com.google.common.annotations.VisibleForTesting; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.common.hapi.validation.support.ValidationSupportChain; import org.hl7.fhir.instance.model.api.IBaseCoding; import org.hl7.fhir.instance.model.api.IBaseParameters; @@ -53,7 +54,6 @@ import org.springframework.beans.factory.annotation.Qualifier; import java.util.Optional; import java.util.function.Supplier; -import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ValueSetOperationProviderDstu2.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ValueSetOperationProviderDstu2.java index 0480f0290d2..5659c8129c4 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ValueSetOperationProviderDstu2.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/ValueSetOperationProviderDstu2.java @@ -27,6 +27,7 @@ import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.util.FhirTerser; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseCoding; import org.hl7.fhir.instance.model.api.IBaseParameters; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -35,7 +36,6 @@ import org.hl7.fhir.instance.model.api.IPrimitiveType; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; -import javax.servlet.http.HttpServletRequest; import static ca.uhn.fhir.jpa.provider.BaseJpaResourceProviderCodeSystem.applyVersionToSystem; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/dstu3/JpaConformanceProviderDstu3.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/dstu3/JpaConformanceProviderDstu3.java index 2d971de810c..35a78056874 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/dstu3/JpaConformanceProviderDstu3.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/dstu3/JpaConformanceProviderDstu3.java @@ -31,6 +31,7 @@ import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import ca.uhn.fhir.rest.server.util.ResourceSearchParams; import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.util.ExtensionConstants; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.CapabilityStatement; import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementRestComponent; @@ -49,7 +50,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/r4/MemberMatchR4ResourceProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/r4/MemberMatchR4ResourceProvider.java index 4d09f9fed84..6ad2956d88d 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/r4/MemberMatchR4ResourceProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/r4/MemberMatchR4ResourceProvider.java @@ -58,7 +58,7 @@ public class MemberMatchR4ResourceProvider { idempotent = false, returnParameters = {@OperationParam(name = "MemberIdentifier", typeName = "string")}) public Parameters patientMemberMatch( - javax.servlet.http.HttpServletRequest theServletRequest, + jakarta.servlet.http.HttpServletRequest theServletRequest, @Description(shortDefinition = "The target of the operation. Contain member Patient demographics.") @OperationParam(name = Constants.PARAM_MEMBER_PATIENT, min = 1, max = 1) Patient theMemberPatient, diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/HapiHSearchAnalysisConfigurers.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/HapiHSearchAnalysisConfigurers.java index a280d7e8293..b17cff10ace 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/HapiHSearchAnalysisConfigurers.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/HapiHSearchAnalysisConfigurers.java @@ -60,68 +60,68 @@ public class HapiHSearchAnalysisConfigurers { theLuceneCtx .analyzer("autocompleteEdgeAnalyzer") .custom() - .tokenizer(PatternTokenizerFactory.class) - .param("pattern", "(.*)") - .param("group", "1") - .tokenFilter(LowerCaseFilterFactory.class) - .tokenFilter(StopFilterFactory.class) - .tokenFilter(EdgeNGramFilterFactory.class) + .tokenizer(PatternTokenizerFactory.NAME) + .param(PatternTokenizerFactory.PATTERN, "(.*)") + .param(PatternTokenizerFactory.GROUP, "1") + .tokenFilter(LowerCaseFilterFactory.NAME) + .tokenFilter(StopFilterFactory.NAME) + .tokenFilter(EdgeNGramFilterFactory.NAME) .param("minGramSize", "3") .param("maxGramSize", "50"); theLuceneCtx .analyzer("autocompletePhoneticAnalyzer") .custom() - .tokenizer(StandardTokenizerFactory.class) - .tokenFilter(StopFilterFactory.class) - .tokenFilter(PhoneticFilterFactory.class) - .param("encoder", "DoubleMetaphone") - .tokenFilter(SnowballPorterFilterFactory.class) + .tokenizer(StandardTokenizerFactory.NAME) + .tokenFilter(StopFilterFactory.NAME) + .tokenFilter(PhoneticFilterFactory.NAME) + .param(PhoneticFilterFactory.ENCODER, "DoubleMetaphone") + .tokenFilter(SnowballPorterFilterFactory.NAME) .param("language", "English"); theLuceneCtx .analyzer("autocompleteNGramAnalyzer") .custom() - .tokenizer(StandardTokenizerFactory.class) - .tokenFilter(WordDelimiterGraphFilterFactory.class) - .tokenFilter(LowerCaseFilterFactory.class) - .tokenFilter(NGramFilterFactory.class) + .tokenizer(StandardTokenizerFactory.NAME) + .tokenFilter(WordDelimiterGraphFilterFactory.NAME) + .tokenFilter(LowerCaseFilterFactory.NAME) + .tokenFilter(NGramFilterFactory.NAME) .param("minGramSize", "3") .param("maxGramSize", "20"); theLuceneCtx .analyzer("autocompleteWordEdgeAnalyzer") .custom() - .tokenizer(StandardTokenizerFactory.class) - .tokenFilter(LowerCaseFilterFactory.class) - .tokenFilter(StopFilterFactory.class) - .tokenFilter(EdgeNGramFilterFactory.class) + .tokenizer(StandardTokenizerFactory.NAME) + .tokenFilter(LowerCaseFilterFactory.NAME) + .tokenFilter(StopFilterFactory.NAME) + .tokenFilter(EdgeNGramFilterFactory.NAME) .param("minGramSize", "3") .param("maxGramSize", "20"); theLuceneCtx .analyzer(STANDARD_ANALYZER) .custom() - .tokenizer(StandardTokenizerFactory.class) - .tokenFilter(LowerCaseFilterFactory.class) - .tokenFilter(ASCIIFoldingFilterFactory.class); + .tokenizer(StandardTokenizerFactory.NAME) + .tokenFilter(LowerCaseFilterFactory.NAME) + .tokenFilter(ASCIIFoldingFilterFactory.NAME); theLuceneCtx .analyzer(NORM_STRING_ANALYZER) .custom() - .tokenizer(KeywordTokenizerFactory.class) - .tokenFilter(LowerCaseFilterFactory.class) - .tokenFilter(ASCIIFoldingFilterFactory.class); + .tokenizer(KeywordTokenizerFactory.NAME) + .tokenFilter(LowerCaseFilterFactory.NAME) + .tokenFilter(ASCIIFoldingFilterFactory.NAME); - theLuceneCtx.analyzer(EXACT_ANALYZER).custom().tokenizer(KeywordTokenizerFactory.class); + theLuceneCtx.analyzer(EXACT_ANALYZER).custom().tokenizer(KeywordTokenizerFactory.NAME); - theLuceneCtx.analyzer("conceptParentPidsAnalyzer").custom().tokenizer(WhitespaceTokenizerFactory.class); + theLuceneCtx.analyzer("conceptParentPidsAnalyzer").custom().tokenizer(WhitespaceTokenizerFactory.NAME); theLuceneCtx .normalizer(LOWERCASE_ASCIIFOLDING_NORMALIZER) .custom() - .tokenFilter(LowerCaseFilterFactory.class) - .tokenFilter(ASCIIFoldingFilterFactory.class); + .tokenFilter(LowerCaseFilterFactory.NAME) + .tokenFilter(ASCIIFoldingFilterFactory.NAME); } } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/PersistedJpaBundleProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/PersistedJpaBundleProvider.java index 51a994e7afa..b25435b6751 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/PersistedJpaBundleProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/PersistedJpaBundleProvider.java @@ -58,6 +58,8 @@ import ca.uhn.fhir.rest.server.method.ResponsePage; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.rest.server.util.CompositeInterceptorBroadcaster; import com.google.common.annotations.VisibleForTesting; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; import org.hl7.fhir.instance.model.api.IBaseResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,8 +72,6 @@ import java.util.Optional; import java.util.Set; import java.util.function.Function; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; public class PersistedJpaBundleProvider implements IBundleProvider { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/ResourceSearchUrlSvc.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/ResourceSearchUrlSvc.java index ee380067c7e..47512f96648 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/ResourceSearchUrlSvc.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/ResourceSearchUrlSvc.java @@ -26,13 +26,13 @@ import ca.uhn.fhir.jpa.model.dao.JpaPid; import ca.uhn.fhir.jpa.model.entity.ResourceSearchUrlEntity; import ca.uhn.fhir.jpa.searchparam.MatchUrlService; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; +import jakarta.persistence.EntityManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; -import javax.persistence.EntityManager; /** * This service ensures uniqueness of resources during create or create-on-update by storing the resource searchUrl. diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/SynchronousSearchSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/SynchronousSearchSvcImpl.java index 89f77e51b14..8d2a9367820 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/SynchronousSearchSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/SynchronousSearchSvcImpl.java @@ -47,6 +47,7 @@ import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.interceptor.ServerInterceptorUtil; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.rest.server.util.CompositeInterceptorBroadcaster; +import jakarta.persistence.EntityManager; import org.hl7.fhir.instance.model.api.IBaseResource; import org.springframework.beans.factory.annotation.Autowired; @@ -55,7 +56,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; -import javax.persistence.EntityManager; import static ca.uhn.fhir.jpa.util.SearchParameterMapCalculator.isWantCount; import static ca.uhn.fhir.jpa.util.SearchParameterMapCalculator.isWantOnlyCount; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/SearchBuilder.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/SearchBuilder.java index 88f5f75a87e..bc40f4c3c19 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/SearchBuilder.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/SearchBuilder.java @@ -95,6 +95,13 @@ import ca.uhn.fhir.util.StringUtil; import ca.uhn.fhir.util.UrlUtil; import com.google.common.collect.Streams; import com.healthmarketscience.sqlbuilder.Condition; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.Query; +import jakarta.persistence.Tuple; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.math.NumberUtils; @@ -121,13 +128,6 @@ import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.Query; -import javax.persistence.Tuple; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; import static ca.uhn.fhir.jpa.model.util.JpaConstants.UNDESIRED_RESOURCE_LINKAGES_FOR_EVERYTHING_ON_PATIENT_INSTANCE; import static ca.uhn.fhir.jpa.search.builder.QueryStack.LOCATION_POSITION; @@ -495,15 +495,8 @@ public class SearchBuilder implements ISearchBuilder { myRequestPartitionId, myResourceName, String.valueOf(lastNResourceId))) .collect(Collectors.toList()); } else { - if (myIElasticsearchSvc == null) { - throw new InvalidRequestException(Msg.code(2033) - + "LastN operation is not enabled on this service, can not process this request"); - } - // use the dedicated observation ES/Lucene index to support lastN query - return myIElasticsearchSvc.executeLastN(myParams, myContext, theMaximumResults).stream() - .map(lastnResourceId -> myIdHelperService.resolveResourcePersistentIds( - myRequestPartitionId, myResourceName, lastnResourceId)) - .collect(Collectors.toList()); + throw new InvalidRequestException( + Msg.code(2033) + "LastN operation is not enabled on this service, can not process this request"); } } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/predicate/BaseQuantityPredicateBuilder.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/predicate/BaseQuantityPredicateBuilder.java index 78b7f115ab6..4f427431418 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/predicate/BaseQuantityPredicateBuilder.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/predicate/BaseQuantityPredicateBuilder.java @@ -33,10 +33,10 @@ import com.healthmarketscience.sqlbuilder.ComboCondition; import com.healthmarketscience.sqlbuilder.Condition; import com.healthmarketscience.sqlbuilder.dbspec.basic.DbColumn; import com.healthmarketscience.sqlbuilder.dbspec.basic.DbTable; +import jakarta.persistence.criteria.CriteriaBuilder; import org.springframework.beans.factory.annotation.Autowired; import java.math.BigDecimal; -import javax.persistence.criteria.CriteriaBuilder; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilder.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilder.java index e840bdec9d3..3a310e5c4d7 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilder.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilder.java @@ -64,7 +64,9 @@ import com.healthmarketscience.sqlbuilder.dbspec.basic.DbTable; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.pagination.AbstractLimitHandler; -import org.hibernate.engine.spi.RowSelection; +import org.hibernate.query.internal.QueryOptionsImpl; +import org.hibernate.query.spi.Limit; +import org.hibernate.query.spi.QueryOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -501,10 +503,11 @@ public class SearchQueryBuilder { maxResultsToFetch = defaultIfNull(maxResultsToFetch, 10000); AbstractLimitHandler limitHandler = (AbstractLimitHandler) myDialect.getLimitHandler(); - RowSelection selection = new RowSelection(); + Limit selection = new Limit(); selection.setFirstRow(offset); selection.setMaxRows(maxResultsToFetch); - sql = limitHandler.processSql(sql, selection); + QueryOptions queryOptions = new QueryOptionsImpl(); + sql = limitHandler.processSql(sql, selection, queryOptions); int startOfQueryParameterIndex = 0; @@ -517,14 +520,14 @@ public class SearchQueryBuilder { if (sql.contains("top(?)")) { bindVariables.add(0, maxResultsToFetch); } - if (sql.contains("offset 0 rows fetch next ? rows only")) { + if (sql.contains("offset 0 rows fetch first ? rows only")) { bindVariables.add(maxResultsToFetch); } if (sql.contains("offset ? rows fetch next ? rows only")) { bindVariables.add(theOffset); bindVariables.add(maxResultsToFetch); } - if (offset != null && sql.contains("__row__")) { + if (offset != null && sql.contains("rownumber_")) { bindVariables.add(theOffset + 1); bindVariables.add(theOffset + maxResultsToFetch + 1); } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryExecutor.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryExecutor.java index 8f8d4600ee5..d1edddeda4f 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryExecutor.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryExecutor.java @@ -25,6 +25,11 @@ import ca.uhn.fhir.jpa.search.builder.ISearchQueryExecutor; import ca.uhn.fhir.jpa.util.ScrollableResultsIterator; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.util.IoUtil; +import jakarta.persistence.EntityManager; +import jakarta.persistence.FlushModeType; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.Query; import org.apache.commons.lang3.Validate; import org.hibernate.CacheMode; import org.hibernate.ScrollMode; @@ -33,11 +38,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; -import javax.persistence.EntityManager; -import javax.persistence.FlushModeType; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.Query; +import java.util.Objects; public class SearchQueryExecutor implements ISearchQueryExecutor { @@ -51,7 +52,7 @@ public class SearchQueryExecutor implements ISearchQueryExecutor { private EntityManager myEntityManager; private boolean myQueryInitialized; - private ScrollableResultsIterator myResultSet; + private ScrollableResultsIterator myResultSet; private Long myNext; /** @@ -144,7 +145,13 @@ public class SearchQueryExecutor implements ISearchQueryExecutor { if (myResultSet == null || !myResultSet.hasNext()) { myNext = NO_MORE; } else { - Number next = myResultSet.next(); + Object nextRow = Objects.requireNonNull(myResultSet.next()); + Number next; + if (nextRow instanceof Number) { + next = (Number) nextRow; + } else { + next = (Number) ((Object[]) nextRow)[0]; + } myNext = next.longValue(); } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/tasks/SearchTask.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/tasks/SearchTask.java index 9396f7d9542..700d409e216 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/tasks/SearchTask.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/builder/tasks/SearchTask.java @@ -57,7 +57,6 @@ import co.elastic.apm.api.Transaction; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.exception.ExceptionUtils; import org.hl7.fhir.instance.model.api.IBaseResource; -import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import java.io.IOException; @@ -447,7 +446,6 @@ public class SearchTask implements Callable { myTxService .withRequest(myRequest) .withRequestPartitionId(myRequestPartitionId) - .withIsolation(Isolation.READ_COMMITTED) .execute(() -> doSearch()); mySearchRuntimeDetails.setSearchStatus(mySearch.getStatus()); diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/cache/DatabaseSearchCacheSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/cache/DatabaseSearchCacheSvcImpl.java index 0f666f60505..1e886ca9c1b 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/cache/DatabaseSearchCacheSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/cache/DatabaseSearchCacheSvcImpl.java @@ -33,6 +33,7 @@ import ca.uhn.fhir.jpa.entity.Search; import ca.uhn.fhir.jpa.model.search.SearchStatusEnum; import ca.uhn.fhir.system.HapiSystemProperties; import com.google.common.annotations.VisibleForTesting; +import jakarta.persistence.EntityManager; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.time.DateUtils; import org.hibernate.Session; @@ -53,7 +54,6 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; public class DatabaseSearchCacheSvcImpl implements ISearchCacheSvc { /* diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/ElasticsearchRestClientFactory.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/ElasticsearchRestClientFactory.java index a5c8481b8a5..564d39bf804 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/ElasticsearchRestClientFactory.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/ElasticsearchRestClientFactory.java @@ -21,6 +21,10 @@ package ca.uhn.fhir.jpa.search.lastn; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.i18n.Msg; +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.json.jackson.JacksonJsonpMapper; +import co.elastic.clients.transport.ElasticsearchTransport; +import co.elastic.clients.transport.rest_client.RestClientTransport; import org.apache.commons.lang3.StringUtils; import org.apache.http.Header; import org.apache.http.HttpHost; @@ -32,7 +36,6 @@ import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Node; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; -import org.elasticsearch.client.RestHighLevelClient; import java.util.Arrays; import java.util.List; @@ -41,7 +44,7 @@ import javax.annotation.Nullable; public class ElasticsearchRestClientFactory { - public static RestHighLevelClient createElasticsearchHighLevelRestClient( + public static ElasticsearchClient createElasticsearchHighLevelRestClient( String protocol, String hosts, @Nullable String theUsername, @Nullable String thePassword) { if (hosts.contains("://")) { @@ -78,6 +81,12 @@ public class ElasticsearchRestClientFactory { Header[] defaultHeaders = new Header[] {new BasicHeader("Content-Type", "application/json")}; clientBuilder.setDefaultHeaders(defaultHeaders); - return new RestHighLevelClient(clientBuilder); + RestClient restClient = clientBuilder.build(); + + // Create the transport with a Jackson mapper + ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper()); + + // And create the API client + return new ElasticsearchClient(transport); } } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/ElasticsearchSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/ElasticsearchSvcImpl.java index 1479b017cd8..f9d344277d4 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/ElasticsearchSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/ElasticsearchSvcImpl.java @@ -23,108 +23,41 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.jpa.dao.TolerantJsonParser; import ca.uhn.fhir.jpa.model.config.PartitionSettings; -import ca.uhn.fhir.jpa.model.util.CodeSystemHash; -import ca.uhn.fhir.jpa.search.lastn.json.CodeJson; import ca.uhn.fhir.jpa.search.lastn.json.ObservationJson; -import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; -import ca.uhn.fhir.jpa.searchparam.util.LastNParameterHelper; -import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.rest.api.server.storage.IResourcePersistentId; -import ca.uhn.fhir.rest.param.DateParam; -import ca.uhn.fhir.rest.param.ParamPrefixEnum; -import ca.uhn.fhir.rest.param.ReferenceParam; -import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.elasticsearch._types.FieldValue; +import co.elastic.clients.elasticsearch.core.SearchRequest; +import co.elastic.clients.elasticsearch.core.SearchResponse; +import co.elastic.clients.elasticsearch.core.search.Hit; +import co.elastic.clients.elasticsearch.indices.ExistsRequest; import com.google.common.annotations.VisibleForTesting; -import org.apache.commons.lang3.Validate; -import org.elasticsearch.action.DocWriteResponse; -import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; -import org.elasticsearch.action.index.IndexRequest; -import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.client.RequestOptions; -import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.client.indices.CreateIndexRequest; -import org.elasticsearch.client.indices.CreateIndexResponse; -import org.elasticsearch.client.indices.GetIndexRequest; -import org.elasticsearch.index.query.BoolQueryBuilder; -import org.elasticsearch.index.query.MatchQueryBuilder; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.index.query.RangeQueryBuilder; -import org.elasticsearch.index.reindex.DeleteByQueryRequest; -import org.elasticsearch.search.SearchHit; -import org.elasticsearch.search.SearchHits; -import org.elasticsearch.search.aggregations.AggregationBuilder; -import org.elasticsearch.search.aggregations.AggregationBuilders; -import org.elasticsearch.search.aggregations.Aggregations; -import org.elasticsearch.search.aggregations.BucketOrder; -import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder; -import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder; -import org.elasticsearch.search.aggregations.bucket.composite.ParsedComposite; -import org.elasticsearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder; -import org.elasticsearch.search.aggregations.bucket.terms.ParsedTerms; -import org.elasticsearch.search.aggregations.bucket.terms.Terms; -import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; -import org.elasticsearch.search.aggregations.metrics.ParsedTopHits; -import org.elasticsearch.search.builder.SearchSourceBuilder; -import org.elasticsearch.search.sort.SortOrder; -import org.elasticsearch.xcontent.XContentType; import org.hl7.fhir.instance.model.api.IBaseResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Arrays; +import java.io.StringReader; import java.util.Collection; import java.util.List; -import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; -import static org.apache.commons.lang3.StringUtils.isBlank; - public class ElasticsearchSvcImpl implements IElasticsearchSvc { - private static final Logger ourLog = LoggerFactory.getLogger(ElasticsearchSvcImpl.class); - // Index Constants public static final String OBSERVATION_INDEX = "observation_index"; public static final String OBSERVATION_CODE_INDEX = "code_index"; - public static final String OBSERVATION_DOCUMENT_TYPE = - "ca.uhn.fhir.jpa.model.entity.ObservationIndexedSearchParamLastNEntity"; - public static final String CODE_DOCUMENT_TYPE = - "ca.uhn.fhir.jpa.model.entity.ObservationIndexedCodeCodeableConceptEntity"; public static final String OBSERVATION_INDEX_SCHEMA_FILE = "ObservationIndexSchema.json"; public static final String OBSERVATION_CODE_INDEX_SCHEMA_FILE = "ObservationCodeIndexSchema.json"; // Aggregation Constants - private static final String GROUP_BY_SUBJECT = "group_by_subject"; - private static final String GROUP_BY_SYSTEM = "group_by_system"; - private static final String GROUP_BY_CODE = "group_by_code"; - private static final String MOST_RECENT_EFFECTIVE = "most_recent_effective"; // Observation index document element names private static final String OBSERVATION_IDENTIFIER_FIELD_NAME = "identifier"; - private static final String OBSERVATION_SUBJECT_FIELD_NAME = "subject"; - private static final String OBSERVATION_CODEVALUE_FIELD_NAME = "codeconceptcodingcode"; - private static final String OBSERVATION_CODESYSTEM_FIELD_NAME = "codeconceptcodingsystem"; - private static final String OBSERVATION_CODEHASH_FIELD_NAME = "codeconceptcodingcode_system_hash"; - private static final String OBSERVATION_CODEDISPLAY_FIELD_NAME = "codeconceptcodingdisplay"; - private static final String OBSERVATION_CODE_TEXT_FIELD_NAME = "codeconcepttext"; - private static final String OBSERVATION_EFFECTIVEDTM_FIELD_NAME = "effectivedtm"; - private static final String OBSERVATION_CATEGORYHASH_FIELD_NAME = "categoryconceptcodingcode_system_hash"; - private static final String OBSERVATION_CATEGORYVALUE_FIELD_NAME = "categoryconceptcodingcode"; - private static final String OBSERVATION_CATEGORYSYSTEM_FIELD_NAME = "categoryconceptcodingsystem"; - private static final String OBSERVATION_CATEGORYDISPLAY_FIELD_NAME = "categoryconceptcodingdisplay"; - private static final String OBSERVATION_CATEGORYTEXT_FIELD_NAME = "categoryconcepttext"; // Code index document element names private static final String CODE_HASH = "codingcode_system_hash"; @@ -132,12 +65,7 @@ public class ElasticsearchSvcImpl implements IElasticsearchSvc { private static final String OBSERVATION_RESOURCE_NAME = "Observation"; - private final RestHighLevelClient myRestHighLevelClient; - - private final ObjectMapper objectMapper = new ObjectMapper(); - - @Autowired - private PartitionSettings myPartitionSettings; + private final ElasticsearchClient myRestHighLevelClient; @Autowired private FhirContext myContext; @@ -150,11 +78,11 @@ public class ElasticsearchSvcImpl implements IElasticsearchSvc { @Nullable String theUsername, @Nullable String thePassword) { this(theProtocol, theHostname, theUsername, thePassword); - this.myPartitionSettings = thePartitionSetings; } public ElasticsearchSvcImpl( String theProtocol, String theHostname, @Nullable String theUsername, @Nullable String thePassword) { + myRestHighLevelClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient( theProtocol, theHostname, theUsername, thePassword); @@ -200,648 +128,30 @@ public class ElasticsearchSvcImpl implements IElasticsearchSvc { } private boolean createIndex(String theIndexName, String theMapping) throws IOException { - CreateIndexRequest request = new CreateIndexRequest(theIndexName); - request.source(theMapping, XContentType.JSON); - CreateIndexResponse createIndexResponse = - myRestHighLevelClient.indices().create(request, RequestOptions.DEFAULT); - return createIndexResponse.isAcknowledged(); + return myRestHighLevelClient + .indices() + .create(cir -> cir.index(theIndexName).withJson(new StringReader(theMapping))) + .acknowledged(); } private boolean indexExists(String theIndexName) throws IOException { - GetIndexRequest request = new GetIndexRequest(theIndexName); - return myRestHighLevelClient.indices().exists(request, RequestOptions.DEFAULT); - } - - @Override - public List executeLastN( - SearchParameterMap theSearchParameterMap, FhirContext theFhirContext, Integer theMaxResultsToFetch) { - Validate.isTrue( - !myPartitionSettings.isPartitioningEnabled(), - "$lastn is not currently supported on partitioned servers"); - - String[] topHitsInclude = {OBSERVATION_IDENTIFIER_FIELD_NAME}; - return buildAndExecuteSearch( - theSearchParameterMap, - theFhirContext, - topHitsInclude, - ObservationJson::getIdentifier, - theMaxResultsToFetch); - } - - private List buildAndExecuteSearch( - SearchParameterMap theSearchParameterMap, - FhirContext theFhirContext, - String[] topHitsInclude, - Function setValue, - Integer theMaxResultsToFetch) { - String patientParamName = LastNParameterHelper.getPatientParamName(theFhirContext); - String subjectParamName = LastNParameterHelper.getSubjectParamName(theFhirContext); - List searchResults = new ArrayList<>(); - if (theSearchParameterMap.containsKey(patientParamName) - || theSearchParameterMap.containsKey(subjectParamName)) { - for (String subject : - getSubjectReferenceCriteria(patientParamName, subjectParamName, theSearchParameterMap)) { - if (theMaxResultsToFetch != null && searchResults.size() >= theMaxResultsToFetch) { - break; - } - SearchRequest myLastNRequest = buildObservationsSearchRequest( - subject, - theSearchParameterMap, - theFhirContext, - createObservationSubjectAggregationBuilder( - getMaxParameter(theSearchParameterMap), topHitsInclude)); - ourLog.debug("ElasticSearch query: {}", myLastNRequest.source().toString()); - try { - SearchResponse lastnResponse = executeSearchRequest(myLastNRequest); - searchResults.addAll(buildObservationList( - lastnResponse, setValue, theSearchParameterMap, theFhirContext, theMaxResultsToFetch)); - } catch (IOException theE) { - throw new InvalidRequestException(Msg.code(1178) + "Unable to execute LastN request", theE); - } - } - } else { - SearchRequest myLastNRequest = buildObservationsSearchRequest( - theSearchParameterMap, - theFhirContext, - createObservationCodeAggregationBuilder(getMaxParameter(theSearchParameterMap), topHitsInclude)); - ourLog.debug("ElasticSearch query: {}", myLastNRequest.source().toString()); - try { - SearchResponse lastnResponse = executeSearchRequest(myLastNRequest); - searchResults.addAll(buildObservationList( - lastnResponse, setValue, theSearchParameterMap, theFhirContext, theMaxResultsToFetch)); - } catch (IOException theE) { - throw new InvalidRequestException(Msg.code(1179) + "Unable to execute LastN request", theE); - } - } - return searchResults; - } - - private int getMaxParameter(SearchParameterMap theSearchParameterMap) { - if (theSearchParameterMap.getLastNMax() == null) { - return 1; - } else { - return theSearchParameterMap.getLastNMax(); - } - } - - private List getSubjectReferenceCriteria( - String thePatientParamName, String theSubjectParamName, SearchParameterMap theSearchParameterMap) { - List subjectReferenceCriteria = new ArrayList<>(); - - List> patientParams = new ArrayList<>(); - if (theSearchParameterMap.get(thePatientParamName) != null) { - patientParams.addAll(theSearchParameterMap.get(thePatientParamName)); - } - if (theSearchParameterMap.get(theSubjectParamName) != null) { - patientParams.addAll(theSearchParameterMap.get(theSubjectParamName)); - } - for (List nextSubjectList : patientParams) { - subjectReferenceCriteria.addAll(getReferenceValues(nextSubjectList)); - } - return subjectReferenceCriteria; - } - - private List getReferenceValues(List referenceParams) { - List referenceList = new ArrayList<>(); - - for (IQueryParameterType nextOr : referenceParams) { - - if (nextOr instanceof ReferenceParam) { - ReferenceParam ref = (ReferenceParam) nextOr; - if (isBlank(ref.getChain())) { - referenceList.add(ref.getValue()); - } - } else { - throw new IllegalArgumentException( - Msg.code(1180) + "Invalid token type (expecting ReferenceParam): " + nextOr.getClass()); - } - } - return referenceList; - } - - private CompositeAggregationBuilder createObservationSubjectAggregationBuilder( - Integer theMaxNumberObservationsPerCode, String[] theTopHitsInclude) { - CompositeValuesSourceBuilder subjectValuesBuilder = - new TermsValuesSourceBuilder(OBSERVATION_SUBJECT_FIELD_NAME).field(OBSERVATION_SUBJECT_FIELD_NAME); - List> compositeAggSubjectSources = new ArrayList<>(); - compositeAggSubjectSources.add(subjectValuesBuilder); - CompositeAggregationBuilder compositeAggregationSubjectBuilder = - new CompositeAggregationBuilder(GROUP_BY_SUBJECT, compositeAggSubjectSources); - compositeAggregationSubjectBuilder.subAggregation( - createObservationCodeAggregationBuilder(theMaxNumberObservationsPerCode, theTopHitsInclude)); - compositeAggregationSubjectBuilder.size(10000); - - return compositeAggregationSubjectBuilder; - } - - private TermsAggregationBuilder createObservationCodeAggregationBuilder( - int theMaxNumberObservationsPerCode, String[] theTopHitsInclude) { - TermsAggregationBuilder observationCodeCodeAggregationBuilder = - new TermsAggregationBuilder(GROUP_BY_CODE).field(OBSERVATION_CODEVALUE_FIELD_NAME); - observationCodeCodeAggregationBuilder.order(BucketOrder.key(true)); - // Top Hits Aggregation - observationCodeCodeAggregationBuilder.subAggregation(AggregationBuilders.topHits(MOST_RECENT_EFFECTIVE) - .sort(OBSERVATION_EFFECTIVEDTM_FIELD_NAME, SortOrder.DESC) - .fetchSource(theTopHitsInclude, null) - .size(theMaxNumberObservationsPerCode)); - observationCodeCodeAggregationBuilder.size(10000); - TermsAggregationBuilder observationCodeSystemAggregationBuilder = - new TermsAggregationBuilder(GROUP_BY_SYSTEM).field(OBSERVATION_CODESYSTEM_FIELD_NAME); - observationCodeSystemAggregationBuilder.order(BucketOrder.key(true)); - observationCodeSystemAggregationBuilder.subAggregation(observationCodeCodeAggregationBuilder); - return observationCodeSystemAggregationBuilder; - } - - private SearchResponse executeSearchRequest(SearchRequest searchRequest) throws IOException { - return myRestHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); - } - - private List buildObservationList( - SearchResponse theSearchResponse, - Function setValue, - SearchParameterMap theSearchParameterMap, - FhirContext theFhirContext, - Integer theMaxResultsToFetch) - throws IOException { - List theObservationList = new ArrayList<>(); - if (theSearchParameterMap.containsKey(LastNParameterHelper.getPatientParamName(theFhirContext)) - || theSearchParameterMap.containsKey(LastNParameterHelper.getSubjectParamName(theFhirContext))) { - for (ParsedComposite.ParsedBucket subjectBucket : getSubjectBuckets(theSearchResponse)) { - if (theMaxResultsToFetch != null && theObservationList.size() >= theMaxResultsToFetch) { - break; - } - for (Terms.Bucket observationCodeBucket : getObservationCodeBuckets(subjectBucket)) { - if (theMaxResultsToFetch != null && theObservationList.size() >= theMaxResultsToFetch) { - break; - } - for (SearchHit lastNMatch : getLastNMatches(observationCodeBucket)) { - if (theMaxResultsToFetch != null && theObservationList.size() >= theMaxResultsToFetch) { - break; - } - String indexedObservation = lastNMatch.getSourceAsString(); - ObservationJson observationJson = - objectMapper.readValue(indexedObservation, ObservationJson.class); - theObservationList.add(setValue.apply(observationJson)); - } - } - } - } else { - for (Terms.Bucket observationCodeBucket : getObservationCodeBuckets(theSearchResponse)) { - if (theMaxResultsToFetch != null && theObservationList.size() >= theMaxResultsToFetch) { - break; - } - for (SearchHit lastNMatch : getLastNMatches(observationCodeBucket)) { - if (theMaxResultsToFetch != null && theObservationList.size() >= theMaxResultsToFetch) { - break; - } - String indexedObservation = lastNMatch.getSourceAsString(); - ObservationJson observationJson = objectMapper.readValue(indexedObservation, ObservationJson.class); - theObservationList.add(setValue.apply(observationJson)); - } - } - } - - return theObservationList; - } - - private List getSubjectBuckets(SearchResponse theSearchResponse) { - Aggregations responseAggregations = theSearchResponse.getAggregations(); - ParsedComposite aggregatedSubjects = responseAggregations.get(GROUP_BY_SUBJECT); - return aggregatedSubjects.getBuckets(); - } - - private List getObservationCodeBuckets(SearchResponse theSearchResponse) { - Aggregations responseAggregations = theSearchResponse.getAggregations(); - return getObservationCodeBuckets(responseAggregations); - } - - private List getObservationCodeBuckets(ParsedComposite.ParsedBucket theSubjectBucket) { - Aggregations observationCodeSystemAggregations = theSubjectBucket.getAggregations(); - return getObservationCodeBuckets(observationCodeSystemAggregations); - } - - private List getObservationCodeBuckets(Aggregations theObservationCodeSystemAggregations) { - List retVal = new ArrayList<>(); - ParsedTerms aggregatedObservationCodeSystems = theObservationCodeSystemAggregations.get(GROUP_BY_SYSTEM); - for (Terms.Bucket observationCodeSystem : aggregatedObservationCodeSystems.getBuckets()) { - Aggregations observationCodeCodeAggregations = observationCodeSystem.getAggregations(); - ParsedTerms aggregatedObservationCodeCodes = observationCodeCodeAggregations.get(GROUP_BY_CODE); - retVal.addAll(aggregatedObservationCodeCodes.getBuckets()); - } - return retVal; - } - - private SearchHit[] getLastNMatches(Terms.Bucket theObservationCodeBucket) { - Aggregations topHitObservationCodes = theObservationCodeBucket.getAggregations(); - ParsedTopHits parsedTopHits = topHitObservationCodes.get(MOST_RECENT_EFFECTIVE); - return parsedTopHits.getHits().getHits(); - } - - private SearchRequest buildObservationsSearchRequest( - SearchParameterMap theSearchParameterMap, - FhirContext theFhirContext, - AggregationBuilder theAggregationBuilder) { - SearchRequest searchRequest = new SearchRequest(OBSERVATION_INDEX); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - // Query - if (!searchParamsHaveLastNCriteria(theSearchParameterMap, theFhirContext)) { - searchSourceBuilder.query(QueryBuilders.matchAllQuery()); - } else { - BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); - addCategoriesCriteria(boolQueryBuilder, theSearchParameterMap, theFhirContext); - addObservationCodeCriteria(boolQueryBuilder, theSearchParameterMap, theFhirContext); - addDateCriteria(boolQueryBuilder, theSearchParameterMap, theFhirContext); - searchSourceBuilder.query(boolQueryBuilder); - } - searchSourceBuilder.size(0); - - // Aggregation by order codes - searchSourceBuilder.aggregation(theAggregationBuilder); - searchRequest.source(searchSourceBuilder); - - return searchRequest; - } - - private SearchRequest buildObservationsSearchRequest( - String theSubjectParam, - SearchParameterMap theSearchParameterMap, - FhirContext theFhirContext, - AggregationBuilder theAggregationBuilder) { - SearchRequest searchRequest = new SearchRequest(OBSERVATION_INDEX); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - // Query - BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); - boolQueryBuilder.must(QueryBuilders.termQuery(OBSERVATION_SUBJECT_FIELD_NAME, theSubjectParam)); - addCategoriesCriteria(boolQueryBuilder, theSearchParameterMap, theFhirContext); - addObservationCodeCriteria(boolQueryBuilder, theSearchParameterMap, theFhirContext); - addDateCriteria(boolQueryBuilder, theSearchParameterMap, theFhirContext); - searchSourceBuilder.query(boolQueryBuilder); - searchSourceBuilder.size(0); - - // Aggregation by order codes - searchSourceBuilder.aggregation(theAggregationBuilder); - searchRequest.source(searchSourceBuilder); - - return searchRequest; - } - - private Boolean searchParamsHaveLastNCriteria( - SearchParameterMap theSearchParameterMap, FhirContext theFhirContext) { - return theSearchParameterMap != null - && (theSearchParameterMap.containsKey(LastNParameterHelper.getPatientParamName(theFhirContext)) - || theSearchParameterMap.containsKey(LastNParameterHelper.getSubjectParamName(theFhirContext)) - || theSearchParameterMap.containsKey(LastNParameterHelper.getCategoryParamName(theFhirContext)) - || theSearchParameterMap.containsKey(LastNParameterHelper.getCodeParamName(theFhirContext))); - } - - private void addCategoriesCriteria( - BoolQueryBuilder theBoolQueryBuilder, - SearchParameterMap theSearchParameterMap, - FhirContext theFhirContext) { - String categoryParamName = LastNParameterHelper.getCategoryParamName(theFhirContext); - if (theSearchParameterMap.containsKey(categoryParamName)) { - ArrayList codeSystemHashList = new ArrayList<>(); - ArrayList codeOnlyList = new ArrayList<>(); - ArrayList systemOnlyList = new ArrayList<>(); - ArrayList textOnlyList = new ArrayList<>(); - List> andOrParams = theSearchParameterMap.get(categoryParamName); - for (List nextAnd : andOrParams) { - codeSystemHashList.addAll(getCodingCodeSystemValues(nextAnd)); - codeOnlyList.addAll(getCodingCodeOnlyValues(nextAnd)); - systemOnlyList.addAll(getCodingSystemOnlyValues(nextAnd)); - textOnlyList.addAll(getCodingTextOnlyValues(nextAnd)); - } - if (codeSystemHashList.size() > 0) { - theBoolQueryBuilder.must( - QueryBuilders.termsQuery(OBSERVATION_CATEGORYHASH_FIELD_NAME, codeSystemHashList)); - } - if (codeOnlyList.size() > 0) { - theBoolQueryBuilder.must(QueryBuilders.termsQuery(OBSERVATION_CATEGORYVALUE_FIELD_NAME, codeOnlyList)); - } - if (systemOnlyList.size() > 0) { - theBoolQueryBuilder.must( - QueryBuilders.termsQuery(OBSERVATION_CATEGORYSYSTEM_FIELD_NAME, systemOnlyList)); - } - if (textOnlyList.size() > 0) { - BoolQueryBuilder myTextBoolQueryBuilder = QueryBuilders.boolQuery(); - for (String textOnlyParam : textOnlyList) { - myTextBoolQueryBuilder.should(QueryBuilders.matchPhrasePrefixQuery( - OBSERVATION_CATEGORYDISPLAY_FIELD_NAME, textOnlyParam)); - myTextBoolQueryBuilder.should( - QueryBuilders.matchPhrasePrefixQuery(OBSERVATION_CATEGORYTEXT_FIELD_NAME, textOnlyParam)); - } - theBoolQueryBuilder.must(myTextBoolQueryBuilder); - } - } - } - - private List getCodingCodeSystemValues(List codeParams) { - ArrayList codeSystemHashList = new ArrayList<>(); - for (IQueryParameterType nextOr : codeParams) { - if (nextOr instanceof TokenParam) { - TokenParam ref = (TokenParam) nextOr; - if (ref.getSystem() != null && ref.getValue() != null) { - codeSystemHashList.add( - String.valueOf(CodeSystemHash.hashCodeSystem(ref.getSystem(), ref.getValue()))); - } - } else { - throw new IllegalArgumentException( - Msg.code(1181) + "Invalid token type (expecting TokenParam): " + nextOr.getClass()); - } - } - return codeSystemHashList; - } - - private List getCodingCodeOnlyValues(List codeParams) { - ArrayList codeOnlyList = new ArrayList<>(); - for (IQueryParameterType nextOr : codeParams) { - - if (nextOr instanceof TokenParam) { - TokenParam ref = (TokenParam) nextOr; - if (ref.getValue() != null && ref.getSystem() == null && !ref.isText()) { - codeOnlyList.add(ref.getValue()); - } - } else { - throw new IllegalArgumentException( - Msg.code(1182) + "Invalid token type (expecting TokenParam): " + nextOr.getClass()); - } - } - return codeOnlyList; - } - - private List getCodingSystemOnlyValues(List codeParams) { - ArrayList systemOnlyList = new ArrayList<>(); - for (IQueryParameterType nextOr : codeParams) { - - if (nextOr instanceof TokenParam) { - TokenParam ref = (TokenParam) nextOr; - if (ref.getValue() == null && ref.getSystem() != null) { - systemOnlyList.add(ref.getSystem()); - } - } else { - throw new IllegalArgumentException( - Msg.code(1183) + "Invalid token type (expecting TokenParam): " + nextOr.getClass()); - } - } - return systemOnlyList; - } - - private List getCodingTextOnlyValues(List codeParams) { - ArrayList textOnlyList = new ArrayList<>(); - for (IQueryParameterType nextOr : codeParams) { - - if (nextOr instanceof TokenParam) { - TokenParam ref = (TokenParam) nextOr; - if (ref.isText() && ref.getValue() != null) { - textOnlyList.add(ref.getValue()); - } - } else { - throw new IllegalArgumentException( - Msg.code(1184) + "Invalid token type (expecting TokenParam): " + nextOr.getClass()); - } - } - return textOnlyList; - } - - private void addObservationCodeCriteria( - BoolQueryBuilder theBoolQueryBuilder, - SearchParameterMap theSearchParameterMap, - FhirContext theFhirContext) { - String codeParamName = LastNParameterHelper.getCodeParamName(theFhirContext); - if (theSearchParameterMap.containsKey(codeParamName)) { - ArrayList codeSystemHashList = new ArrayList<>(); - ArrayList codeOnlyList = new ArrayList<>(); - ArrayList systemOnlyList = new ArrayList<>(); - ArrayList textOnlyList = new ArrayList<>(); - List> andOrParams = theSearchParameterMap.get(codeParamName); - for (List nextAnd : andOrParams) { - codeSystemHashList.addAll(getCodingCodeSystemValues(nextAnd)); - codeOnlyList.addAll(getCodingCodeOnlyValues(nextAnd)); - systemOnlyList.addAll(getCodingSystemOnlyValues(nextAnd)); - textOnlyList.addAll(getCodingTextOnlyValues(nextAnd)); - } - if (codeSystemHashList.size() > 0) { - theBoolQueryBuilder.must(QueryBuilders.termsQuery(OBSERVATION_CODEHASH_FIELD_NAME, codeSystemHashList)); - } - if (codeOnlyList.size() > 0) { - theBoolQueryBuilder.must(QueryBuilders.termsQuery(OBSERVATION_CODEVALUE_FIELD_NAME, codeOnlyList)); - } - if (systemOnlyList.size() > 0) { - theBoolQueryBuilder.must(QueryBuilders.termsQuery(OBSERVATION_CODESYSTEM_FIELD_NAME, systemOnlyList)); - } - if (textOnlyList.size() > 0) { - BoolQueryBuilder myTextBoolQueryBuilder = QueryBuilders.boolQuery(); - for (String textOnlyParam : textOnlyList) { - myTextBoolQueryBuilder.should( - QueryBuilders.matchPhrasePrefixQuery(OBSERVATION_CODEDISPLAY_FIELD_NAME, textOnlyParam)); - myTextBoolQueryBuilder.should( - QueryBuilders.matchPhrasePrefixQuery(OBSERVATION_CODE_TEXT_FIELD_NAME, textOnlyParam)); - } - theBoolQueryBuilder.must(myTextBoolQueryBuilder); - } - } - } - - private void addDateCriteria( - BoolQueryBuilder theBoolQueryBuilder, - SearchParameterMap theSearchParameterMap, - FhirContext theFhirContext) { - String dateParamName = LastNParameterHelper.getEffectiveParamName(theFhirContext); - if (theSearchParameterMap.containsKey(dateParamName)) { - List> andOrParams = theSearchParameterMap.get(dateParamName); - for (List nextAnd : andOrParams) { - BoolQueryBuilder myDateBoolQueryBuilder = new BoolQueryBuilder(); - for (IQueryParameterType nextOr : nextAnd) { - if (nextOr instanceof DateParam) { - DateParam myDate = (DateParam) nextOr; - createDateCriteria(myDate, myDateBoolQueryBuilder); - } - } - theBoolQueryBuilder.must(myDateBoolQueryBuilder); - } - } - } - - private void createDateCriteria(DateParam theDate, BoolQueryBuilder theBoolQueryBuilder) { - Long dateInstant = theDate.getValue().getTime(); - RangeQueryBuilder myRangeQueryBuilder = new RangeQueryBuilder(OBSERVATION_EFFECTIVEDTM_FIELD_NAME); - - ParamPrefixEnum prefix = theDate.getPrefix(); - if (prefix == ParamPrefixEnum.GREATERTHAN || prefix == ParamPrefixEnum.STARTS_AFTER) { - theBoolQueryBuilder.should(myRangeQueryBuilder.gt(dateInstant)); - } else if (prefix == ParamPrefixEnum.LESSTHAN || prefix == ParamPrefixEnum.ENDS_BEFORE) { - theBoolQueryBuilder.should(myRangeQueryBuilder.lt(dateInstant)); - } else if (prefix == ParamPrefixEnum.LESSTHAN_OR_EQUALS) { - theBoolQueryBuilder.should(myRangeQueryBuilder.lte(dateInstant)); - } else if (prefix == ParamPrefixEnum.GREATERTHAN_OR_EQUALS) { - theBoolQueryBuilder.should(myRangeQueryBuilder.gte(dateInstant)); - } else { - theBoolQueryBuilder.should(new MatchQueryBuilder(OBSERVATION_EFFECTIVEDTM_FIELD_NAME, dateInstant)); - } - } - - @VisibleForTesting - public List executeLastNWithAllFieldsForTest( - SearchParameterMap theSearchParameterMap, FhirContext theFhirContext) { - return buildAndExecuteSearch(theSearchParameterMap, theFhirContext, null, t -> t, 100); - } - - @VisibleForTesting - List queryAllIndexedObservationCodesForTest() throws IOException { - SearchRequest codeSearchRequest = new SearchRequest(OBSERVATION_CODE_INDEX); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - // Query - searchSourceBuilder.query(QueryBuilders.matchAllQuery()); - searchSourceBuilder.size(1000); - codeSearchRequest.source(searchSourceBuilder); - SearchResponse codeSearchResponse = executeSearchRequest(codeSearchRequest); - return buildCodeResult(codeSearchResponse); - } - - private List buildCodeResult(SearchResponse theSearchResponse) throws JsonProcessingException { - SearchHits codeHits = theSearchResponse.getHits(); - List codes = new ArrayList<>(); - for (SearchHit codeHit : codeHits) { - CodeJson code = objectMapper.readValue(codeHit.getSourceAsString(), CodeJson.class); - codes.add(code); - } - return codes; - } - - @Override - public ObservationJson getObservationDocument(String theDocumentID) { - if (theDocumentID == null) { - throw new InvalidRequestException( - Msg.code(1185) + "Require non-null document ID for observation document query"); - } - SearchRequest theSearchRequest = buildSingleObservationSearchRequest(theDocumentID); - ObservationJson observationDocumentJson = null; - try { - SearchResponse observationDocumentResponse = executeSearchRequest(theSearchRequest); - SearchHit[] observationDocumentHits = - observationDocumentResponse.getHits().getHits(); - if (observationDocumentHits.length > 0) { - // There should be no more than one hit for the identifier - String observationDocument = observationDocumentHits[0].getSourceAsString(); - observationDocumentJson = objectMapper.readValue(observationDocument, ObservationJson.class); - } - - } catch (IOException theE) { - throw new InvalidRequestException( - Msg.code(1186) + "Unable to execute observation document query for ID " + theDocumentID, theE); - } - - return observationDocumentJson; - } - - private SearchRequest buildSingleObservationSearchRequest(String theObservationIdentifier) { - SearchRequest searchRequest = new SearchRequest(OBSERVATION_INDEX); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); - boolQueryBuilder.must(QueryBuilders.termQuery(OBSERVATION_IDENTIFIER_FIELD_NAME, theObservationIdentifier)); - searchSourceBuilder.query(boolQueryBuilder); - searchSourceBuilder.size(1); - - searchRequest.source(searchSourceBuilder); - - return searchRequest; - } - - @Override - public CodeJson getObservationCodeDocument(String theCodeSystemHash, String theText) { - if (theCodeSystemHash == null && theText == null) { - throw new InvalidRequestException(Msg.code(1187) - + "Require a non-null code system hash value or display value for observation code document query"); - } - SearchRequest theSearchRequest = buildSingleObservationCodeSearchRequest(theCodeSystemHash, theText); - CodeJson observationCodeDocumentJson = null; - try { - SearchResponse observationCodeDocumentResponse = executeSearchRequest(theSearchRequest); - SearchHit[] observationCodeDocumentHits = - observationCodeDocumentResponse.getHits().getHits(); - if (observationCodeDocumentHits.length > 0) { - // There should be no more than one hit for the code lookup. - String observationCodeDocument = observationCodeDocumentHits[0].getSourceAsString(); - observationCodeDocumentJson = objectMapper.readValue(observationCodeDocument, CodeJson.class); - } - - } catch (IOException theE) { - throw new InvalidRequestException( - Msg.code(1188) + "Unable to execute observation code document query hash code or display", theE); - } - - return observationCodeDocumentJson; - } - - private SearchRequest buildSingleObservationCodeSearchRequest(String theCodeSystemHash, String theText) { - SearchRequest searchRequest = new SearchRequest(OBSERVATION_CODE_INDEX); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); - if (theCodeSystemHash != null) { - boolQueryBuilder.must(QueryBuilders.termQuery(CODE_HASH, theCodeSystemHash)); - } else { - boolQueryBuilder.must(QueryBuilders.matchPhraseQuery(CODE_TEXT, theText)); - } - - searchSourceBuilder.query(boolQueryBuilder); - searchSourceBuilder.size(1); - - searchRequest.source(searchSourceBuilder); - - return searchRequest; - } - - @Override - public Boolean createOrUpdateObservationIndex(String theDocumentId, ObservationJson theObservationDocument) { - try { - String documentToIndex = objectMapper.writeValueAsString(theObservationDocument); - return performIndex( - OBSERVATION_INDEX, theDocumentId, documentToIndex, ElasticsearchSvcImpl.OBSERVATION_DOCUMENT_TYPE); - } catch (IOException theE) { - throw new InvalidRequestException( - Msg.code(1189) + "Unable to persist Observation document " + theDocumentId); - } - } - - @Override - public Boolean createOrUpdateObservationCodeIndex( - String theCodeableConceptID, CodeJson theObservationCodeDocument) { - try { - String documentToIndex = objectMapper.writeValueAsString(theObservationCodeDocument); - return performIndex( - OBSERVATION_CODE_INDEX, - theCodeableConceptID, - documentToIndex, - ElasticsearchSvcImpl.CODE_DOCUMENT_TYPE); - } catch (IOException theE) { - throw new InvalidRequestException( - Msg.code(1190) + "Unable to persist Observation Code document " + theCodeableConceptID); - } - } - - private boolean performIndex( - String theIndexName, String theDocumentId, String theIndexDocument, String theDocumentType) - throws IOException { - IndexResponse indexResponse = myRestHighLevelClient.index( - createIndexRequest(theIndexName, theDocumentId, theIndexDocument, theDocumentType), - RequestOptions.DEFAULT); - - return (indexResponse.getResult() == DocWriteResponse.Result.CREATED) - || (indexResponse.getResult() == DocWriteResponse.Result.UPDATED); + ExistsRequest request = new ExistsRequest.Builder().index(theIndexName).build(); + return myRestHighLevelClient.indices().exists(request).value(); } @Override public void close() throws IOException { - myRestHighLevelClient.close(); + // nothing } @Override public List getObservationResources(Collection thePids) { SearchRequest searchRequest = buildObservationResourceSearchRequest(thePids); try { - SearchResponse observationDocumentResponse = executeSearchRequest(searchRequest); - SearchHit[] observationDocumentHits = - observationDocumentResponse.getHits().getHits(); + SearchResponse observationDocumentResponse = + myRestHighLevelClient.search(searchRequest, ObservationJson.class); + List> observationDocumentHits = + observationDocumentResponse.hits().hits(); IParser parser = TolerantJsonParser.createWithLenientErrorHandling(myContext, null); Class resourceType = myContext.getResourceDefinition(OBSERVATION_RESOURCE_NAME).getImplementingClass(); @@ -849,8 +159,8 @@ public class ElasticsearchSvcImpl implements IElasticsearchSvc { * @see ca.uhn.fhir.jpa.dao.BaseHapiFhirDao#toResource(Class, IBaseResourceEntity, Collection, boolean) for * details about parsing raw json to BaseResource */ - return Arrays.stream(observationDocumentHits) - .map(this::parseObservationJson) + return observationDocumentHits.stream() + .map(Hit::source) .map(observationJson -> parser.parseResource(resourceType, observationJson.getResource())) .collect(Collectors.toList()); } catch (IOException theE) { @@ -859,55 +169,23 @@ public class ElasticsearchSvcImpl implements IElasticsearchSvc { } } - private ObservationJson parseObservationJson(SearchHit theSearchHit) { - try { - return objectMapper.readValue(theSearchHit.getSourceAsString(), ObservationJson.class); - } catch (JsonProcessingException exp) { - throw new InvalidRequestException(Msg.code(2004) + "Unable to parse the observation resource json", exp); - } - } - private SearchRequest buildObservationResourceSearchRequest(Collection thePids) { - SearchRequest searchRequest = new SearchRequest(OBSERVATION_INDEX); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - // Query - BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); - List pidParams = thePids.stream().map(Object::toString).collect(Collectors.toList()); - boolQueryBuilder.must(QueryBuilders.termsQuery(OBSERVATION_IDENTIFIER_FIELD_NAME, pidParams)); - searchSourceBuilder.query(boolQueryBuilder); - searchSourceBuilder.size(thePids.size()); - searchRequest.source(searchSourceBuilder); - return searchRequest; - } + List values = thePids.stream() + .map(Object::toString) + .map(v -> FieldValue.of(v)) + .collect(Collectors.toList()); - private IndexRequest createIndexRequest( - String theIndexName, String theDocumentId, String theObservationDocument, String theDocumentType) { - IndexRequest request = new IndexRequest(theIndexName); - request.id(theDocumentId); - request.source(theObservationDocument, XContentType.JSON); - return request; - } - - @Override - public void deleteObservationDocument(String theDocumentId) { - DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(OBSERVATION_INDEX); - deleteByQueryRequest.setQuery(QueryBuilders.termQuery(OBSERVATION_IDENTIFIER_FIELD_NAME, theDocumentId)); - try { - myRestHighLevelClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT); - } catch (IOException theE) { - throw new InvalidRequestException(Msg.code(1191) + "Unable to delete Observation " + theDocumentId); - } - } - - @VisibleForTesting - public void deleteAllDocumentsForTest(String theIndexName) throws IOException { - DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(theIndexName); - deleteByQueryRequest.setQuery(QueryBuilders.matchAllQuery()); - myRestHighLevelClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT); + return SearchRequest.of(sr -> sr.index(OBSERVATION_INDEX) + .query(qb -> qb.bool(bb -> bb.must(bbm -> { + bbm.terms(terms -> + terms.field(OBSERVATION_IDENTIFIER_FIELD_NAME).terms(termsb -> termsb.value(values))); + return bbm; + }))) + .size(thePids.size())); } @VisibleForTesting public void refreshIndex(String theIndexName) throws IOException { - myRestHighLevelClient.indices().refresh(new RefreshRequest(theIndexName), RequestOptions.DEFAULT); + myRestHighLevelClient.indices().refresh(fn -> fn.index(theIndexName)); } } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/IElasticsearchSvc.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/IElasticsearchSvc.java index c6f8209fe0f..1ddf74ac6c0 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/IElasticsearchSvc.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/lastn/IElasticsearchSvc.java @@ -19,10 +19,6 @@ */ package ca.uhn.fhir.jpa.search.lastn; -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.jpa.search.lastn.json.CodeJson; -import ca.uhn.fhir.jpa.search.lastn.json.ObservationJson; -import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; import ca.uhn.fhir.rest.api.server.storage.IResourcePersistentId; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -32,59 +28,6 @@ import java.util.List; public interface IElasticsearchSvc { - /** - * Returns identifiers for the last most recent N observations that meet the specified criteria. - * - * @param theSearchParameterMap SearchParameterMap containing search parameters used for filtering the last N observations. Supported parameters include Subject, Patient, Code, Category and Max (the parameter used to determine N). - * @param theFhirContext Current FhirContext. - * @param theMaxResultsToFetch The maximum number of results to return for the purpose of paging. - * @return - */ - List executeLastN( - SearchParameterMap theSearchParameterMap, FhirContext theFhirContext, Integer theMaxResultsToFetch); - - /** - * Returns index document for a single Observation - * - * @param theDocumentID Identifier of Observation resource. - * @return - */ - ObservationJson getObservationDocument(String theDocumentID); - - /** - * Returns index document for a single Observation Code that either has a coding that matches a specified Code value and system or that has a specified text value. - * - * @param theCodeSystemHash A hash string constructed from a Code value and Code system used to match to an Observation Code. - * @param theText A text value used to match to an Observation Code. - * @return - */ - CodeJson getObservationCodeDocument(String theCodeSystemHash, String theText); - - /** - * Creates or updates index for an Observation Resource. - * - * @param theDocumentId Identifier for Observation resource. - * @param theObservationDocument Indexing document for Observation. - * @return True if Observation indexed successfully. - */ - Boolean createOrUpdateObservationIndex(String theDocumentId, ObservationJson theObservationDocument); - - /** - * Creates or updates index for an Observation Code. - * - * @param theCodeableConceptID Identifier for Observation resource. - * @param theObservationCodeDocument Indexing document for Observation. - * @return True if Observation Code indexed successfully. - */ - Boolean createOrUpdateObservationCodeIndex(String theCodeableConceptID, CodeJson theObservationCodeDocument); - - /** - * Deletes index for an Observation Resource. - * - * @param theDocumentId Identifier for Observation resource. - */ - void deleteObservationDocument(String theDocumentId); - /** * Invoked when shutting down. */ diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/reindex/ResourceReindexingSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/reindex/ResourceReindexingSvcImpl.java index 064e193bfad..ad429000749 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/reindex/ResourceReindexingSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/reindex/ResourceReindexingSvcImpl.java @@ -39,6 +39,11 @@ import ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException; import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import ca.uhn.fhir.util.StopWatch; import com.google.common.annotations.VisibleForTesting; +import jakarta.annotation.PostConstruct; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.Query; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.commons.lang3.time.DateUtils; @@ -70,11 +75,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import javax.annotation.Nullable; -import javax.annotation.PostConstruct; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.Query; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/warm/CacheWarmingSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/warm/CacheWarmingSvcImpl.java index 1cbc2a5e69f..0e2305703b7 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/warm/CacheWarmingSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/search/warm/CacheWarmingSvcImpl.java @@ -34,6 +34,7 @@ import ca.uhn.fhir.jpa.model.sched.ScheduledJobDefinition; import ca.uhn.fhir.jpa.searchparam.MatchUrlService; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; import ca.uhn.fhir.util.UrlUtil; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.time.DateUtils; import org.quartz.JobExecutionContext; import org.slf4j.Logger; @@ -47,7 +48,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; -import javax.annotation.PostConstruct; @Component public class CacheWarmingSvcImpl implements ICacheWarmingSvc, IHasScheduledJobs { diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermCodeSystemStorageSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermCodeSystemStorageSvcImpl.java index fe35f7c8d4d..e8f2c66b6c3 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermCodeSystemStorageSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermCodeSystemStorageSvcImpl.java @@ -53,6 +53,9 @@ import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import ca.uhn.fhir.util.ObjectUtil; import ca.uhn.fhir.util.ValidateUtil; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.r4.model.CodeSystem; @@ -82,9 +85,6 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; import static ca.uhn.fhir.jpa.api.dao.IDao.RESOURCE_PID_KEY; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermConceptClientMappingSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermConceptClientMappingSvcImpl.java index de3a7809bb1..63c6d2bc328 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermConceptClientMappingSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermConceptClientMappingSvcImpl.java @@ -37,6 +37,15 @@ import ca.uhn.fhir.jpa.term.api.ITermConceptClientMappingSvc; import ca.uhn.fhir.jpa.util.MemoryCacheService; import ca.uhn.fhir.jpa.util.ScrollableResultsIterator; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Join; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.apache.commons.lang3.StringUtils; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; @@ -54,15 +63,6 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Join; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermReadSvcImpl.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermReadSvcImpl.java index 9372b9b03b9..0869b8e47f0 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermReadSvcImpl.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/TermReadSvcImpl.java @@ -91,6 +91,11 @@ import ca.uhn.hapi.converters.canonical.VersionCanonicalizer; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Stopwatch; import com.google.common.collect.ArrayListMultimap; +import jakarta.annotation.PostConstruct; +import jakarta.persistence.EntityManager; +import jakarta.persistence.NonUniqueResultException; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang3.ObjectUtils; @@ -171,11 +176,6 @@ import java.util.function.Consumer; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.annotation.PostConstruct; -import javax.persistence.EntityManager; -import javax.persistence.NonUniqueResultException; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; import static ca.uhn.fhir.jpa.entity.TermConceptPropertyBinder.CONCEPT_PROPERTY_PREFIX_NAME; import static ca.uhn.fhir.jpa.term.api.ITermLoaderSvc.LOINC_URI; @@ -665,7 +665,7 @@ public class TermReadSvcImpl implements ITermReadSvc, IHasScheduledJobs { } private boolean isOracleDialect() { - return myHibernatePropertiesProvider.getDialect() instanceof org.hibernate.dialect.Oracle12cDialect; + return myHibernatePropertiesProvider.getDialect() instanceof org.hibernate.dialect.OracleDialect; } private void expandConcepts( diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/PersistenceContextProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/PersistenceContextProvider.java index fec6c6290c1..18771e6ef27 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/PersistenceContextProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/PersistenceContextProvider.java @@ -19,8 +19,8 @@ */ package ca.uhn.fhir.jpa.util; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; /** * Utility class that provides a proxied entityManager. It can be directly injected or diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/QueryParameterUtils.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/QueryParameterUtils.java index 545935497c8..2da96d1c54f 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/QueryParameterUtils.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/QueryParameterUtils.java @@ -37,6 +37,9 @@ import com.healthmarketscience.sqlbuilder.ComboCondition; import com.healthmarketscience.sqlbuilder.Condition; import com.healthmarketscience.sqlbuilder.InCondition; import com.healthmarketscience.sqlbuilder.dbspec.basic.DbColumn; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.From; +import jakarta.persistence.criteria.Predicate; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.bidimap.DualHashBidiMap; import org.apache.commons.collections4.bidimap.UnmodifiableBidiMap; @@ -53,9 +56,6 @@ import java.util.Objects; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.From; -import javax.persistence.criteria.Predicate; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/ScrollableResultsIterator.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/ScrollableResultsIterator.java index b201778ebc8..a79a7834e9b 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/ScrollableResultsIterator.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/ScrollableResultsIterator.java @@ -39,7 +39,7 @@ public class ScrollableResultsIterator extends BaseIterator if (myNext == null) { if (myScroll.next()) { hasNext = true; - myNext = (T) myScroll.get(0); + myNext = (T) myScroll.get(); } else { hasNext = false; } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/validation/JpaValidationSupportChain.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/validation/JpaValidationSupportChain.java index 8f88c3a88ec..5c8274fcda4 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/validation/JpaValidationSupportChain.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/validation/JpaValidationSupportChain.java @@ -24,6 +24,8 @@ import ca.uhn.fhir.context.support.IValidationSupport; import ca.uhn.fhir.jpa.packages.NpmJpaValidationSupport; import ca.uhn.fhir.jpa.term.api.ITermConceptMappingSvc; import ca.uhn.fhir.jpa.term.api.ITermReadSvc; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import org.hl7.fhir.common.hapi.validation.support.CommonCodeSystemsTerminologyService; import org.hl7.fhir.common.hapi.validation.support.InMemoryTerminologyServerValidationSupport; import org.hl7.fhir.common.hapi.validation.support.SnapshotGeneratingValidationSupport; @@ -32,9 +34,6 @@ import org.hl7.fhir.common.hapi.validation.support.ValidationSupportChain; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - public class JpaValidationSupportChain extends ValidationSupportChain { private final FhirContext myFhirContext; diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/index/DaoSearchParamSynchronizerTest.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/index/DaoSearchParamSynchronizerTest.java index 672a023b65e..848f407b512 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/index/DaoSearchParamSynchronizerTest.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/index/DaoSearchParamSynchronizerTest.java @@ -12,7 +12,7 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.math.BigDecimal; import java.util.List; diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/pom.xml b/hapi-fhir-jpaserver-elastic-test-utilities/pom.xml index 6fcd53ab9ab..672c17c1096 100644 --- a/hapi-fhir-jpaserver-elastic-test-utilities/pom.xml +++ b/hapi-fhir-jpaserver-elastic-test-utilities/pom.xml @@ -6,7 +6,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -71,38 +71,6 @@ org.apache.derby derby - - org.eclipse.jetty - jetty-servlets - - - org.eclipse.jetty - jetty-servlet - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-util - - - org.eclipse.jetty - jetty-webapp - - - org.eclipse.jetty.websocket - websocket-jetty-api - - - org.eclipse.jetty.websocket - websocket-core-client - - - org.eclipse.jetty.websocket - websocket-jetty-server - org.springframework.boot spring-boot-test @@ -161,12 +129,12 @@ mockito-core - com.helger - ph-schematron + com.helger.schematron + ph-schematron-api - com.helger - ph-commons + com.helger.schematron + ph-schematron-xslt org.testcontainers diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/ElasticsearchWithPrefixConfig.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/ElasticsearchWithPrefixConfig.java index 7d93aa506e4..d882b4ed076 100644 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/ElasticsearchWithPrefixConfig.java +++ b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/ElasticsearchWithPrefixConfig.java @@ -3,6 +3,7 @@ package ca.uhn.fhir.jpa.config; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; +import ca.uhn.fhir.jpa.config.util.HapiEntityManagerFactoryUtil; import ca.uhn.fhir.jpa.dao.r4.ElasticsearchPrefixTest; import ca.uhn.fhir.jpa.model.dialect.HapiFhirH2Dialect; import ca.uhn.fhir.jpa.search.HapiHSearchAnalysisConfigurers; @@ -11,14 +12,12 @@ import ca.uhn.fhir.jpa.search.lastn.ElasticsearchRestClientFactory; import ca.uhn.fhir.jpa.test.config.BlockLargeNumbersOfParamsListener; import ca.uhn.fhir.jpa.test.config.TestHSearchAddInConfig; import ca.uhn.fhir.jpa.util.CurrentThreadCaptureQueriesListener; +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.elasticsearch.indices.PutTemplateResponse; +import co.elastic.clients.json.JsonData; import net.ttddyy.dsproxy.listener.logging.SLF4JLogLevel; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.apache.commons.dbcp2.BasicDataSource; -import org.elasticsearch.action.support.master.AcknowledgedResponse; -import org.elasticsearch.client.RequestOptions; -import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.client.indices.PutIndexTemplateRequest; -import org.elasticsearch.common.settings.Settings; import org.hibernate.jpa.HibernatePersistenceProvider; import org.hibernate.search.backend.elasticsearch.cfg.ElasticsearchBackendSettings; import org.hibernate.search.backend.elasticsearch.cfg.ElasticsearchIndexSettings; @@ -36,7 +35,7 @@ import org.testcontainers.elasticsearch.ElasticsearchContainer; import javax.sql.DataSource; import java.io.IOException; -import java.util.Arrays; +import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; @@ -65,11 +64,9 @@ public class ElasticsearchWithPrefixConfig { } @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory) { - LocalContainerEntityManagerFactoryBean retVal = new HapiFhirLocalContainerEntityManagerFactoryBean(theConfigurableListableBeanFactory); - retVal.setJpaDialect(new HapiFhirHibernateJpaDialect(fhirContext().getLocalizer())); - retVal.setPackagesToScan("ca.uhn.fhir.jpa.model.entity", "ca.uhn.fhir.jpa.entity"); - retVal.setPersistenceProvider(new HibernatePersistenceProvider()); + public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext, JpaStorageSettings theStorageSettings) { + LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); + retVal.setPersistenceUnitName("PU_HapiFhirJpaR4"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); @@ -126,14 +123,15 @@ public class ElasticsearchWithPrefixConfig { //This tells elasticsearch to use our custom index naming strategy. extraProperties.put(BackendSettings.backendKey(ElasticsearchBackendSettings.LAYOUT_STRATEGY), IndexNamePrefixLayoutStrategy.class.getName()); - PutIndexTemplateRequest ngramTemplate = new PutIndexTemplateRequest("ngram-template") - .patterns(Arrays.asList("*resourcetable-*", "*termconcept-*")) - .settings(Settings.builder().put("index.max_ngram_diff", 50)); - try { - RestHighLevelClient elasticsearchHighLevelRestClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient("http", host + ":" + httpPort, "", ""); - AcknowledgedResponse acknowledgedResponse = elasticsearchHighLevelRestClient.indices().putTemplate(ngramTemplate, RequestOptions.DEFAULT); - assert acknowledgedResponse.isAcknowledged(); + ElasticsearchClient elasticsearchHighLevelRestClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient("http", host + ":" + httpPort, "", ""); + PutTemplateResponse acknowledgedResponse = elasticsearchHighLevelRestClient + .indices() + .putTemplate(b -> b + .name("ngram-template") + .indexPatterns("*resourcetable-*", "*termconcept-*") + .settings(Map.of("index.max_ngram_diff", JsonData.of(50)))); + assert acknowledgedResponse.acknowledged(); } catch (IOException theE) { theE.printStackTrace(); throw new ConfigurationException("Couldn't connect to the elasticsearch server to create necessary templates. Ensure the Elasticsearch user has permissions to create templates."); diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/ElasticsearchPrefixTest.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/ElasticsearchPrefixTest.java index 2f85e652a52..f9bc8977988 100644 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/ElasticsearchPrefixTest.java +++ b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/ElasticsearchPrefixTest.java @@ -3,11 +3,10 @@ package ca.uhn.fhir.jpa.dao.r4; import ca.uhn.fhir.jpa.config.ElasticsearchWithPrefixConfig; import ca.uhn.fhir.jpa.search.lastn.ElasticsearchRestClientFactory; import ca.uhn.fhir.test.utilities.docker.RequiresDocker; -import org.apache.http.util.EntityUtils; -import org.elasticsearch.client.Request; -import org.elasticsearch.client.Response; -import org.elasticsearch.client.RestClient; -import org.elasticsearch.client.RestHighLevelClient; +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.elasticsearch.cat.IndicesResponse; +import co.elastic.clients.elasticsearch.cat.indices.IndicesRecord; +import co.elastic.clients.elasticsearch.indices.GetIndexResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -17,6 +16,7 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.testcontainers.elasticsearch.ElasticsearchContainer; import java.io.IOException; +import java.util.stream.Collectors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -36,13 +36,15 @@ public class ElasticsearchPrefixTest { @Test public void test() throws IOException { //Given - RestHighLevelClient elasticsearchHighLevelRestClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient( + ElasticsearchClient elasticsearchHighLevelRestClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient( "http", elasticsearchContainer.getHost() + ":" + elasticsearchContainer.getMappedPort(9200), "", ""); //When - RestClient lowLevelClient = elasticsearchHighLevelRestClient.getLowLevelClient(); - Response get = lowLevelClient.performRequest(new Request("GET", "/_cat/indices")); - String catIndexes = EntityUtils.toString(get.getEntity()); + IndicesResponse indicesResponse = elasticsearchHighLevelRestClient + .cat() + .indices(); + + String catIndexes = indicesResponse.valueBody().stream().map(IndicesRecord::index).collect(Collectors.joining(",")); //Then assertThat(catIndexes, containsString(ELASTIC_PREFIX + "-resourcetable-000001")); diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNAsyncIT.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNAsyncIT.java index 22274d942d3..355925c596c 100644 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNAsyncIT.java +++ b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNAsyncIT.java @@ -38,6 +38,17 @@ public class FhirResourceDaoR4SearchLastNAsyncIT extends BaseR4SearchLastN { @Autowired private ISearchDao mySearchDao; + @BeforeEach + public void enableAdvancedHSearchIndexing() { + myStorageSettings.setLastNEnabled(true); + myStorageSettings.setAdvancedHSearchIndexing(true); + } + + @AfterEach + public void disableAdvancedHSearchIndex() { + myStorageSettings.setAdvancedHSearchIndexing(new JpaStorageSettings().isAdvancedHSearchIndexing()); + } + @Override @BeforeEach public void before() throws Exception { @@ -123,7 +134,7 @@ public class FhirResourceDaoR4SearchLastNAsyncIT extends BaseR4SearchLastN { // The first chunked query should have a full complement of PIDs StringBuilder firstQueryPattern = new StringBuilder(".*RES_ID in \\('[0-9]+'"); for (int pidIndex = 1; pidIndex < 50; pidIndex++) { - firstQueryPattern.append(" , '[0-9]+'"); + firstQueryPattern.append(",'[0-9]+'"); } firstQueryPattern.append("\\).*"); assertThat(queries.get(4), matchesPattern(firstQueryPattern.toString())); @@ -131,10 +142,10 @@ public class FhirResourceDaoR4SearchLastNAsyncIT extends BaseR4SearchLastN { // the second chunked query should be padded with "-1". StringBuilder secondQueryPattern = new StringBuilder(".*RES_ID in \\('[0-9]+'"); for (int pidIndex = 1; pidIndex < 25; pidIndex++) { - secondQueryPattern.append(" , '[0-9]+'"); + secondQueryPattern.append(",'[0-9]+'"); } for (int pidIndex = 0; pidIndex < 25; pidIndex++) { - secondQueryPattern.append(" , '-1'"); + secondQueryPattern.append(",'-1'"); } secondQueryPattern.append("\\).*"); assertThat(queries.get(5), matchesPattern(secondQueryPattern.toString())); diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNIT.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNIT.java index f9307f1cfb2..33dbef51e44 100644 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNIT.java +++ b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNIT.java @@ -1,10 +1,11 @@ package ca.uhn.fhir.jpa.dao.r4; import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; -import ca.uhn.fhir.jpa.model.dao.JpaPid; +import ca.uhn.fhir.jpa.dao.IHSearchEventListener; import ca.uhn.fhir.jpa.search.builder.SearchBuilder; import ca.uhn.fhir.jpa.search.lastn.ElasticsearchSvcImpl; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; +import ca.uhn.fhir.jpa.test.util.TestHSearchEventDispatcher; import ca.uhn.fhir.rest.param.ReferenceParam; import ca.uhn.fhir.rest.param.TokenParam; import org.hl7.fhir.instance.model.api.IIdType; @@ -14,7 +15,11 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.IOException; @@ -25,26 +30,37 @@ import java.util.UUID; import java.util.stream.Collectors; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.matchesPattern; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(SpringExtension.class) public class FhirResourceDaoR4SearchLastNIT extends BaseR4SearchLastN { + private static final Logger ourLog = LoggerFactory.getLogger(FhirResourceDaoR4SearchLastNIT.class); + @BeforeEach public void enableAdvancedHSearchIndexing() { myStorageSettings.setLastNEnabled(true); + myStorageSettings.setAdvancedHSearchIndexing(true); + myHSearchEventDispatcher.register(mySearchEventListener); + ourLog.info("enableAdvancedHSearchIndexing finished. lastn {} advancedHSearchIndexing {}", myStorageSettings.isLastNEnabled(), myStorageSettings.isAdvancedHSearchIndexing()); } @AfterEach public void reset() { SearchBuilder.setMaxPageSize50ForTest(false); myStorageSettings.setStoreResourceInHSearchIndex(new JpaStorageSettings().isStoreResourceInHSearchIndex()); + myStorageSettings.setAdvancedHSearchIndexing(new JpaStorageSettings().isAdvancedHSearchIndexing()); } + @Autowired + private TestHSearchEventDispatcher myHSearchEventDispatcher; + + @Mock + private IHSearchEventListener mySearchEventListener; + + + @Test public void testLastNChunking() { @@ -76,28 +92,22 @@ public class FhirResourceDaoR4SearchLastNIT extends BaseR4SearchLastN { .getSelectQueriesForCurrentThread() .stream() .map(t -> t.getSql(true, false)) - .collect(Collectors.toList()); + .toList(); // Two chunked queries executed by the QueryIterator (in current thread) and two chunked queries to retrieve resources by PID. assertEquals(4, queries.size()); // The first and third chunked queries should have a full complement of PIDs StringBuilder firstQueryPattern = new StringBuilder(".*RES_ID IN \\('[0-9]+'"); - for (int pidIndex = 1; pidIndex < 50; pidIndex++) { - firstQueryPattern.append(",'[0-9]+'"); - } + firstQueryPattern.append(",'[0-9]+'".repeat(49)); firstQueryPattern.append("\\).*"); assertThat(queries.get(0).toUpperCase().replaceAll(" , ", ","), matchesPattern(firstQueryPattern.toString())); assertThat(queries.get(2).toUpperCase().replaceAll(" , ", ","), matchesPattern(firstQueryPattern.toString())); // the second and fourth chunked queries should be padded with "-1". StringBuilder secondQueryPattern = new StringBuilder(".*RES_ID IN \\('[0-9]+'"); - for (int pidIndex = 1; pidIndex < 25; pidIndex++) { - secondQueryPattern.append(",'[0-9]+'"); - } - for (int pidIndex = 0; pidIndex < 25; pidIndex++) { - secondQueryPattern.append(",'-1'"); - } + secondQueryPattern.append(",'[0-9]+'".repeat(24)); + secondQueryPattern.append(",'-1'".repeat(25)); secondQueryPattern.append("\\).*"); assertThat(queries.get(1).toUpperCase().replaceAll(" , ", ","), matchesPattern(secondQueryPattern.toString())); assertThat(queries.get(3).toUpperCase().replaceAll(" , ", ","), matchesPattern(secondQueryPattern.toString())); @@ -134,18 +144,12 @@ public class FhirResourceDaoR4SearchLastNIT extends BaseR4SearchLastN { } + /** + * We pull the resources from Hibernate Search when LastN uses Hibernate Search + * Override the test verification to validate only one search was performed + */ void verifyResourcesLoadedFromElastic(List theObservationIds, List theResults) { - List expectedArgumentPids = JpaPid.fromLongList( - theObservationIds.stream().map(IIdType::getIdPartAsLong).collect(Collectors.toList()) - ); - ArgumentCaptor> actualPids = ArgumentCaptor.forClass(List.class); - verify(myElasticsearchSvc, times(1)).getObservationResources(actualPids.capture()); - assertThat(actualPids.getValue(), is(expectedArgumentPids)); - - List expectedObservationList = theObservationIds.stream() - .map(id -> id.toUnqualifiedVersionless().getValue()).collect(Collectors.toList()); - assertEquals(expectedObservationList, theResults); - + Mockito.verify(mySearchEventListener, Mockito.times(1)) + .hsearchEvent(IHSearchEventListener.HSearchEventType.SEARCH); } - } diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexAsyncIT.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexAsyncIT.java deleted file mode 100644 index 0e547dca1f7..00000000000 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexAsyncIT.java +++ /dev/null @@ -1,27 +0,0 @@ -package ca.uhn.fhir.jpa.dao.r4; - -import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -/** - * Run entire @see {@link FhirResourceDaoR4SearchLastNAsyncIT} test suite this time - * using Extended HSearch index as search target - */ -@ExtendWith(SpringExtension.class) -public class FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexAsyncIT extends FhirResourceDaoR4SearchLastNAsyncIT { - - @BeforeEach - public void enableAdvancedHSearchIndexing() { - myStorageSettings.setLastNEnabled(true); - myStorageSettings.setAdvancedHSearchIndexing(true); - } - - @AfterEach - public void disableAdvancedHSearchIndex() { - myStorageSettings.setAdvancedHSearchIndexing(new JpaStorageSettings().isAdvancedHSearchIndexing()); - } - -} diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexIT.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexIT.java deleted file mode 100644 index 057ed57e48e..00000000000 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexIT.java +++ /dev/null @@ -1,60 +0,0 @@ -package ca.uhn.fhir.jpa.dao.r4; - -import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; -import ca.uhn.fhir.jpa.dao.IHSearchEventListener; -import ca.uhn.fhir.jpa.test.util.TestHSearchEventDispatcher; -import org.hl7.fhir.instance.model.api.IIdType; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import java.util.List; - -/** - * Run entire @see {@link FhirResourceDaoR4SearchLastNIT} test suite this time - * using Extended HSearch index as search target. - * - * The other implementation is obsolete, and we can merge these someday. - */ -@ExtendWith(SpringExtension.class) -public class FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexIT extends FhirResourceDaoR4SearchLastNIT { - private static final Logger ourLog = LoggerFactory.getLogger(FhirResourceDaoR4SearchLastNUsingExtendedHSearchIndexIT.class); - - @Autowired - private TestHSearchEventDispatcher myHSearchEventDispatcher; - - @Mock - private IHSearchEventListener mySearchEventListener; - - - @BeforeEach - public void enableAdvancedHSearchIndexing() { - myStorageSettings.setLastNEnabled(true); - myStorageSettings.setAdvancedHSearchIndexing(true); - myHSearchEventDispatcher.register(mySearchEventListener); - ourLog.info("enableAdvancedHSearchIndexing finished. lastn {} advancedHSearchIndexing {}", myStorageSettings.isLastNEnabled(), myStorageSettings.isAdvancedHSearchIndexing()); - - } - - @AfterEach - public void disableAdvancedHSearchIndex() { - myStorageSettings.setAdvancedHSearchIndexing(new JpaStorageSettings().isAdvancedHSearchIndexing()); - } - - /** - * We pull the resources from Hibernate Search when LastN uses Hibernate Search - * Override the test verification to validate only one search was performed - */ - @Override - void verifyResourcesLoadedFromElastic(List theObservationIds, List theResults) { - Mockito.verify(mySearchEventListener, Mockito.times(1)) - .hsearchEvent(IHSearchEventListener.HSearchEventType.SEARCH); - } - -} diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchWithElasticSearchIT.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchWithElasticSearchIT.java index 16f6a63cc19..b24e2b46ab8 100644 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchWithElasticSearchIT.java +++ b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchWithElasticSearchIT.java @@ -104,7 +104,7 @@ import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/HSearchSandboxTest.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/HSearchSandboxTest.java index 452217fe751..77d3a743f65 100644 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/HSearchSandboxTest.java +++ b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/HSearchSandboxTest.java @@ -42,7 +42,7 @@ import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.PlatformTransactionManager; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.util.Collections; import java.util.List; diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/PersistObservationIndexedSearchParamLastNR4IT.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/PersistObservationIndexedSearchParamLastNR4IT.java deleted file mode 100644 index 8d9d0d8c15e..00000000000 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/r4/PersistObservationIndexedSearchParamLastNR4IT.java +++ /dev/null @@ -1,474 +0,0 @@ -package ca.uhn.fhir.jpa.dao.r4; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; -import ca.uhn.fhir.jpa.api.dao.IFhirSystemDao; -import ca.uhn.fhir.jpa.config.TestR4ConfigWithElasticHSearch; -import ca.uhn.fhir.jpa.dao.ObservationLastNIndexPersistSvc; -import ca.uhn.fhir.jpa.model.entity.ResourceTable; -import ca.uhn.fhir.jpa.search.lastn.ElasticsearchSvcImpl; -import ca.uhn.fhir.jpa.search.lastn.json.CodeJson; -import ca.uhn.fhir.jpa.search.lastn.json.ObservationJson; -import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; -import ca.uhn.fhir.parser.IParser; -import ca.uhn.fhir.rest.param.ReferenceAndListParam; -import ca.uhn.fhir.rest.param.ReferenceOrListParam; -import ca.uhn.fhir.rest.param.ReferenceParam; -import ca.uhn.fhir.rest.param.TokenAndListParam; -import ca.uhn.fhir.rest.param.TokenOrListParam; -import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.test.utilities.docker.RequiresDocker; -import com.google.common.base.Charsets; -import org.apache.commons.io.IOUtils; -import org.hl7.fhir.r4.model.Bundle; -import org.hl7.fhir.r4.model.CodeableConcept; -import org.hl7.fhir.r4.model.Coding; -import org.hl7.fhir.r4.model.DateTimeType; -import org.hl7.fhir.r4.model.IdType; -import org.hl7.fhir.r4.model.Meta; -import org.hl7.fhir.r4.model.Observation; -import org.hl7.fhir.r4.model.Reference; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - - -@ExtendWith(SpringExtension.class) -@RequiresDocker -@ContextConfiguration(classes = TestR4ConfigWithElasticHSearch.class) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class PersistObservationIndexedSearchParamLastNR4IT { - - private final String SINGLE_SUBJECT_ID = "4567"; - private final String SINGLE_OBSERVATION_PID = "123"; - private final Date SINGLE_EFFECTIVEDTM = new Date(); - private final String SINGLE_OBSERVATION_CODE_TEXT = "Test Codeable Concept Field for Code"; - private final String CATEGORYFIRSTCODINGSYSTEM = "http://mycodes.org/fhir/observation-category"; - private final String FIRSTCATEGORYFIRSTCODINGCODE = "test-heart-rate"; - private final String CODEFIRSTCODINGSYSTEM = "http://mycodes.org/fhir/observation-code"; - private final String CODEFIRSTCODINGCODE = "test-code"; - @PersistenceContext(type = PersistenceContextType.TRANSACTION) - protected EntityManager myEntityManager; - @Autowired - protected FhirContext myFhirCtx; - @Autowired - ObservationLastNIndexPersistSvc testObservationPersist; - @Autowired - private ElasticsearchSvcImpl elasticsearchSvc; - @Autowired - private IFhirSystemDao myDao; - @Autowired - private JpaStorageSettings myStorageSettings; - private ReferenceAndListParam multiSubjectParams = null; - - @BeforeEach - public void before() throws IOException { - myStorageSettings.setLastNEnabled(true); - - elasticsearchSvc.deleteAllDocumentsForTest(ElasticsearchSvcImpl.OBSERVATION_INDEX); - elasticsearchSvc.deleteAllDocumentsForTest(ElasticsearchSvcImpl.OBSERVATION_CODE_INDEX); - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_INDEX); - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_CODE_INDEX); - - } - - @AfterEach - public void afterDisableLastN() { - myStorageSettings.setLastNEnabled(new JpaStorageSettings().isLastNEnabled()); - } - - @Order(0) - @Test - public void testDeleteObservation() throws IOException { - indexMultipleObservations(); - SearchParameterMap searchParameterMap = new SearchParameterMap(); - searchParameterMap.setLastNMax(100); - List observationDocuments = elasticsearchSvc.executeLastNWithAllFieldsForTest(searchParameterMap, myFhirCtx); - assertEquals(100, observationDocuments.size()); - // Check that fifth observation for fifth patient has been indexed. - ObservationJson observation = elasticsearchSvc.getObservationDocument("55"); - assertNotNull(observation); - - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, multiSubjectParams); - searchParameterMap.setLastNMax(10); - List observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirCtx, 200); - assertEquals(100, observationIdsOnly.size()); - assertTrue(observationIdsOnly.contains("55")); - - // Delete fifth observation for fifth patient. - ResourceTable entity = new ResourceTable(); - entity.setId(55L); - entity.setResourceType("Observation"); - entity.setVersionForUnitTest(0L); - - testObservationPersist.deleteObservationIndex(entity); - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_INDEX); - - // Confirm that observation was deleted. - searchParameterMap = new SearchParameterMap(); - searchParameterMap.setLastNMax(100); - observationDocuments = elasticsearchSvc.executeLastNWithAllFieldsForTest(searchParameterMap, myFhirCtx); - assertEquals(99, observationDocuments.size()); - observation = elasticsearchSvc.getObservationDocument("55"); - assertNull(observation); - - observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirCtx, 200); - assertEquals(99, observationIdsOnly.size()); - assertTrue(!observationIdsOnly.contains("55")); - - } - - - - private void indexSingleObservation() throws IOException { - - Observation myObservation = new Observation(); - IdType observationID = new IdType("Observation", SINGLE_OBSERVATION_PID, "1"); - myObservation.setId(observationID); - Reference subjectId = new Reference(SINGLE_SUBJECT_ID); - myObservation.setSubject(subjectId); - myObservation.setEffective(new DateTimeType(SINGLE_EFFECTIVEDTM)); - - myObservation.setCategory(getCategoryCode()); - - myObservation.setCode(getObservationCode()); - - testObservationPersist.indexObservation(myObservation); - - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_INDEX); - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_CODE_INDEX); - - } - - private List getCategoryCode() { - // Add three CodeableConcepts for category - List categoryConcepts = new ArrayList<>(); - // Create three codings and first category CodeableConcept - List category = new ArrayList<>(); - CodeableConcept categoryCodeableConcept1 = new CodeableConcept().setText("Test Codeable Concept Field for first category"); - category.add(new Coding(CATEGORYFIRSTCODINGSYSTEM, FIRSTCATEGORYFIRSTCODINGCODE, "test-heart-rate display")); - category.add(new Coding("http://myalternatecodes.org/fhir/observation-category", "test-alt-heart-rate", "test-alt-heart-rate display")); - category.add(new Coding("http://mysecondaltcodes.org/fhir/observation-category", "test-2nd-alt-heart-rate", "test-2nd-alt-heart-rate display")); - categoryCodeableConcept1.setCoding(category); - categoryConcepts.add(categoryCodeableConcept1); - // Create three codings and second category CodeableConcept - List category2 = new ArrayList<>(); - CodeableConcept categoryCodeableConcept2 = new CodeableConcept().setText("Test Codeable Concept Field for for second category"); - category2.add(new Coding(CATEGORYFIRSTCODINGSYSTEM, "test-vital-signs", "test-vital-signs display")); - category2.add(new Coding("http://myalternatecodes.org/fhir/observation-category", "test-alt-vitals", "test-alt-vitals display")); - category2.add(new Coding("http://mysecondaltcodes.org/fhir/observation-category", "test-2nd-alt-vitals", "test-2nd-alt-vitals display")); - categoryCodeableConcept2.setCoding(category2); - categoryConcepts.add(categoryCodeableConcept2); - // Create three codings and third category CodeableConcept - List category3 = new ArrayList<>(); - CodeableConcept categoryCodeableConcept3 = new CodeableConcept().setText("Test Codeable Concept Field for third category"); - category3.add(new Coding(CATEGORYFIRSTCODINGSYSTEM, "test-vitals-panel", "test-vitals-panel display")); - category3.add(new Coding("http://myalternatecodes.org/fhir/observation-category", "test-alt-vitals-panel", "test-alt-vitals-panel display")); - category3.add(new Coding("http://mysecondaltcodes.org/fhir/observation-category", "test-2nd-alt-vitals-panel", "test-2nd-alt-vitals-panel display")); - categoryCodeableConcept3.setCoding(category3); - categoryConcepts.add(categoryCodeableConcept3); - return categoryConcepts; - } - - private CodeableConcept getObservationCode() { - // Create CodeableConcept for Code with three codings. - CodeableConcept codeableConceptField = new CodeableConcept().setText(SINGLE_OBSERVATION_CODE_TEXT); - codeableConceptField.addCoding(new Coding(CODEFIRSTCODINGSYSTEM, CODEFIRSTCODINGCODE, "test-code display")); - return codeableConceptField; - } - - @Order(1) - @Test - public void testSampleBundleInTransaction() throws IOException { - FhirContext myFhirCtx = FhirContext.forR4Cached(); - - PathMatchingResourcePatternResolver provider = new PathMatchingResourcePatternResolver(); - final Resource[] bundleResources = provider.getResources("lastntestbundle.json"); - assertEquals(1, bundleResources.length); - - AtomicInteger index = new AtomicInteger(); - - Arrays.stream(bundleResources).forEach( - resource -> { - index.incrementAndGet(); - - InputStream resIs = null; - String nextBundleString; - try { - resIs = resource.getInputStream(); - nextBundleString = IOUtils.toString(resIs, Charsets.UTF_8); - } catch (IOException e) { - return; - } finally { - try { - if (resIs != null) { - resIs.close(); - } - } catch (final IOException ioe) { - // ignore - } - } - - IParser parser = myFhirCtx.newJsonParser(); - Bundle bundle = parser.parseResource(Bundle.class, nextBundleString); - - myDao.transaction(null, bundle); - - } - ); - - elasticsearchSvc.refreshIndex("*"); - - SearchParameterMap searchParameterMap = new SearchParameterMap(); - - // execute Observation ID search - Composite Aggregation - searchParameterMap.setLastNMax(1); - List observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirCtx, 200); - - assertEquals(20, observationIdsOnly.size()); - - searchParameterMap.setLastNMax(3); - observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirCtx, 200); - - assertEquals(38, observationIdsOnly.size()); - - } - - @Order(2) - @Test - public void testIndexObservationMultiple() throws IOException { - indexMultipleObservations(); - SearchParameterMap searchParameterMap = new SearchParameterMap(); - searchParameterMap.setLastNMax(100); - List observationDocuments = elasticsearchSvc.executeLastNWithAllFieldsForTest(searchParameterMap, myFhirCtx); - assertEquals(100, observationDocuments.size()); - - // Check that all observations were indexed. - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, multiSubjectParams); - - searchParameterMap.setLastNMax(10); - - List observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirCtx, 200); - assertEquals(100, observationIdsOnly.size()); - - // Filter the results by category code. - TokenParam categoryParam = new TokenParam(CATEGORYFIRSTCODINGSYSTEM, FIRSTCATEGORYFIRSTCODINGCODE); - searchParameterMap.add(Observation.SP_CATEGORY, new TokenAndListParam().addAnd(new TokenOrListParam().addOr(categoryParam))); - - - observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirCtx, 100); - - assertEquals(50, observationIdsOnly.size()); - - } - - private void indexMultipleObservations() throws IOException { - - // Create two CodeableConcept values each for a Code with three codings. - CodeableConcept codeableConceptField1 = new CodeableConcept().setText("Test Codeable Concept Field for First Code"); - codeableConceptField1.addCoding(new Coding(CODEFIRSTCODINGSYSTEM, "test-code-1", "test-code-1 display")); - codeableConceptField1.addCoding(new Coding("http://myalternatecodes.org/fhir/observation-code", "test-alt-code-1", "test-alt-code-1 display")); - codeableConceptField1.addCoding(new Coding("http://mysecondaltcodes.org/fhir/observation-code", "test-second-alt-code-1", "test-second-alt-code-1 display")); - - CodeableConcept codeableConceptField2 = new CodeableConcept().setText("Test Codeable Concept Field for Second Code"); - codeableConceptField2.addCoding(new Coding(CODEFIRSTCODINGSYSTEM, "test-code-2", "test-code-2 display")); - codeableConceptField2.addCoding(new Coding("http://myalternatecodes.org/fhir/observation-code", "test-alt-code-2", "test-alt-code-2 display")); - codeableConceptField2.addCoding(new Coding("http://mysecondaltcodes.org/fhir/observation-code", "test-second-alt-code-2", "test-second-alt-code-2 display")); - - // Create two CodeableConcept entities for category, each with three codings. - List category1 = new ArrayList<>(); - // Create three codings and first category CodeableConcept - category1.add(new Coding(CATEGORYFIRSTCODINGSYSTEM, FIRSTCATEGORYFIRSTCODINGCODE, "test-heart-rate display")); - category1.add(new Coding("http://myalternatecodes.org/fhir/observation-category", "test-alt-heart-rate", "test-alt-heart-rate display")); - category1.add(new Coding("http://mysecondaltcodes.org/fhir/observation-category", "test-2nd-alt-heart-rate", "test-2nd-alt-heart-rate display")); - List categoryConcepts1 = new ArrayList<>(); - CodeableConcept categoryCodeableConcept1 = new CodeableConcept().setText("Test Codeable Concept Field for first category"); - categoryCodeableConcept1.setCoding(category1); - categoryConcepts1.add(categoryCodeableConcept1); - // Create three codings and second category CodeableConcept - List category2 = new ArrayList<>(); - category2.add(new Coding(CATEGORYFIRSTCODINGSYSTEM, "test-vital-signs", "test-vital-signs display")); - category2.add(new Coding("http://myalternatecodes.org/fhir/observation-category", "test-alt-vitals", "test-alt-vitals display")); - category2.add(new Coding("http://mysecondaltcodes.org/fhir/observation-category", "test-2nd-alt-vitals", "test-2nd-alt-vitals display")); - List categoryConcepts2 = new ArrayList<>(); - CodeableConcept categoryCodeableConcept2 = new CodeableConcept().setText("Test Codeable Concept Field for second category"); - categoryCodeableConcept2.setCoding(category2); - categoryConcepts2.add(categoryCodeableConcept2); - - ReferenceOrListParam subjectParams = new ReferenceOrListParam(); - for (int patientCount = 0; patientCount < 10; patientCount++) { - - String subjectId = String.valueOf(patientCount); - - ReferenceParam subjectParam = new ReferenceParam("Patient", "", subjectId); - subjectParams.addOr(subjectParam); - - for (int entryCount = 0; entryCount < 10; entryCount++) { - - Observation observation = new Observation(); - IdType observationId = new IdType("Observation", String.valueOf(entryCount + patientCount * 10), "1"); - observation.setId(observationId); - Reference subject = new Reference(subjectId); - observation.setSubject(subject); - - if (entryCount % 2 == 1) { - observation.setCategory(categoryConcepts1); - observation.setCode(codeableConceptField1); - } else { - observation.setCategory(categoryConcepts2); - observation.setCode(codeableConceptField2); - } - - Calendar observationDate = new GregorianCalendar(); - observationDate.add(Calendar.HOUR, -10 + entryCount); - Date effectiveDtm = observationDate.getTime(); - observation.setEffective(new DateTimeType(effectiveDtm)); - - testObservationPersist.indexObservation(observation); - } - - } - - multiSubjectParams = new ReferenceAndListParam().addAnd(subjectParams); - - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_INDEX); - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_CODE_INDEX); - - } - - @Order(3) - @Test - public void testIndexObservationSingle() throws IOException { - indexSingleObservation(); - SearchParameterMap searchParameterMap = new SearchParameterMap(); - searchParameterMap.setLastNMax(10); - List persistedObservationEntities = elasticsearchSvc.executeLastNWithAllFieldsForTest(searchParameterMap, myFhirCtx); - assertEquals(1, persistedObservationEntities.size()); - ObservationJson persistedObservationEntity = persistedObservationEntities.get(0); - assertEquals(SINGLE_SUBJECT_ID, persistedObservationEntity.getSubject()); - assertEquals(SINGLE_OBSERVATION_PID, persistedObservationEntity.getIdentifier()); - assertEquals(SINGLE_EFFECTIVEDTM, persistedObservationEntity.getEffectiveDtm()); - - String observationCodeNormalizedId = persistedObservationEntity.getCode_concept_id(); - - // List persistedObservationCodes = elasticsearchSvc.queryAllIndexedObservationCodesForTest(); - // assertEquals(1, persistedObservationCodes.size()); - - // Check that we can retrieve code by hash value. - String codeSystemHash = persistedObservationEntity.getCode_coding_code_system_hash(); - CodeJson persistedObservationCode = elasticsearchSvc.getObservationCodeDocument(codeSystemHash, null); - assertNotNull(persistedObservationCode); - assertEquals(observationCodeNormalizedId, persistedObservationCode.getCodeableConceptId()); - assertEquals(SINGLE_OBSERVATION_CODE_TEXT, persistedObservationCode.getCodeableConceptText()); - - // Also confirm that we can retrieve code by text value. - persistedObservationCode = elasticsearchSvc.getObservationCodeDocument(null, SINGLE_OBSERVATION_CODE_TEXT); - assertNotNull(persistedObservationCode); - - searchParameterMap = new SearchParameterMap(); - ReferenceParam subjectParam = new ReferenceParam("Patient", "", SINGLE_SUBJECT_ID); - searchParameterMap.add(Observation.SP_SUBJECT, new ReferenceAndListParam().addAnd(new ReferenceOrListParam().addOr(subjectParam))); - TokenParam categoryParam = new TokenParam(CATEGORYFIRSTCODINGSYSTEM, FIRSTCATEGORYFIRSTCODINGCODE); - searchParameterMap.add(Observation.SP_CATEGORY, new TokenAndListParam().addAnd(new TokenOrListParam().addOr(categoryParam))); - TokenParam codeParam = new TokenParam(CODEFIRSTCODINGSYSTEM, CODEFIRSTCODINGCODE); - searchParameterMap.add(Observation.SP_CODE, new TokenAndListParam().addAnd(new TokenOrListParam().addOr(codeParam))); - searchParameterMap.setLastNMax(3); - - List observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirCtx, 100); - - assertEquals(1, observationIdsOnly.size()); - assertEquals(SINGLE_OBSERVATION_PID, observationIdsOnly.get(0)); - } - - @Order(4) - @Test - public void testUpdateObservation() throws IOException { - indexSingleObservation(); - SearchParameterMap searchParameterMap = new SearchParameterMap(); - searchParameterMap.setLastNMax(10); - ObservationJson observationIndexEntity = elasticsearchSvc.executeLastNWithAllFieldsForTest(searchParameterMap, myFhirCtx).get(0); - assertEquals(SINGLE_OBSERVATION_PID, observationIndexEntity.getIdentifier()); - assertEquals(SINGLE_SUBJECT_ID, observationIndexEntity.getSubject()); - assertEquals(SINGLE_EFFECTIVEDTM, observationIndexEntity.getEffectiveDtm()); - - searchParameterMap = new SearchParameterMap(); - ReferenceParam subjectParam = new ReferenceParam("Patient", "", SINGLE_SUBJECT_ID); - searchParameterMap.add(Observation.SP_SUBJECT, new ReferenceAndListParam().addAnd(new ReferenceOrListParam().addOr(subjectParam))); - TokenParam categoryParam = new TokenParam(CATEGORYFIRSTCODINGSYSTEM, FIRSTCATEGORYFIRSTCODINGCODE); - searchParameterMap.add(Observation.SP_CATEGORY, new TokenAndListParam().addAnd(new TokenOrListParam().addOr(categoryParam))); - TokenParam codeParam = new TokenParam(CODEFIRSTCODINGSYSTEM, CODEFIRSTCODINGCODE); - searchParameterMap.add(Observation.SP_CODE, new TokenAndListParam().addAnd(new TokenOrListParam().addOr(codeParam))); - searchParameterMap.setLastNMax(10); - - List observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirCtx, 200); - assertEquals(1, observationIdsOnly.size()); - assertTrue(observationIdsOnly.contains(SINGLE_OBSERVATION_PID)); - - // Update the Observation with a new Subject and effective date: - Observation updatedObservation = new Observation(); - IdType observationId = new IdType("Observation", observationIndexEntity.getIdentifier(), "2"); - updatedObservation.setId(observationId); - Reference subjectId = new Reference("1234"); - updatedObservation.setSubject(subjectId); - DateTimeType newEffectiveDtm = new DateTimeType(new Date()); - updatedObservation.setEffective(newEffectiveDtm); - updatedObservation.setCategory(getCategoryCode()); - updatedObservation.setCode(getObservationCode()); - - testObservationPersist.indexObservation(updatedObservation); - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_INDEX); - - ObservationJson updatedObservationEntity = elasticsearchSvc.getObservationDocument(SINGLE_OBSERVATION_PID); - assertEquals("1234", updatedObservationEntity.getSubject()); - assertEquals(newEffectiveDtm.getValue(), updatedObservationEntity.getEffectiveDtm()); - - // Repeat earlier Elasticsearch query. This time, should return no matches. - observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirCtx, 200); - assertEquals(0, observationIdsOnly.size()); - - // Try again with the new patient ID. - searchParameterMap = new SearchParameterMap(); - subjectParam = new ReferenceParam("Patient", "", "1234"); - searchParameterMap.add(Observation.SP_SUBJECT, new ReferenceAndListParam().addAnd(new ReferenceOrListParam().addOr(subjectParam))); - searchParameterMap.add(Observation.SP_CATEGORY, new TokenAndListParam().addAnd(new TokenOrListParam().addOr(categoryParam))); - searchParameterMap.add(Observation.SP_CODE, new TokenAndListParam().addAnd(new TokenOrListParam().addOr(codeParam))); - searchParameterMap.setLastNMax(10); - observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirCtx, 200); - - // Should see the observation returned now. - assertEquals(1, observationIdsOnly.size()); - assertTrue(observationIdsOnly.contains(SINGLE_OBSERVATION_PID)); - - } - - -} diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/autocomplete/TokenAutocompleteElasticsearchIT.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/autocomplete/TokenAutocompleteElasticsearchIT.java index bb9573636b7..6e25869547a 100644 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/autocomplete/TokenAutocompleteElasticsearchIT.java +++ b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/autocomplete/TokenAutocompleteElasticsearchIT.java @@ -38,7 +38,7 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.util.List; import java.util.Objects; diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNElasticsearchSvcMultipleObservationsIT.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNElasticsearchSvcMultipleObservationsIT.java deleted file mode 100644 index bd32380e149..00000000000 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNElasticsearchSvcMultipleObservationsIT.java +++ /dev/null @@ -1,511 +0,0 @@ -package ca.uhn.fhir.jpa.search.lastn; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.jpa.model.config.PartitionSettings; -import ca.uhn.fhir.jpa.search.lastn.json.CodeJson; -import ca.uhn.fhir.jpa.search.lastn.json.ObservationJson; -import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; -import ca.uhn.fhir.jpa.test.config.TestElasticsearchContainerHelper; -import ca.uhn.fhir.rest.param.DateAndListParam; -import ca.uhn.fhir.rest.param.DateOrListParam; -import ca.uhn.fhir.rest.param.DateParam; -import ca.uhn.fhir.rest.param.ParamPrefixEnum; -import ca.uhn.fhir.rest.param.ReferenceAndListParam; -import ca.uhn.fhir.rest.param.ReferenceOrListParam; -import ca.uhn.fhir.rest.param.ReferenceParam; -import ca.uhn.fhir.rest.param.TokenAndListParam; -import ca.uhn.fhir.rest.param.TokenOrListParam; -import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.rest.param.TokenParamModifier; -import ca.uhn.fhir.test.utilities.docker.RequiresDocker; -import org.hl7.fhir.r4.model.Observation; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.testcontainers.elasticsearch.ElasticsearchContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.TEST_BASELINE_TIMESTAMP; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@ExtendWith({SpringExtension.class}) -@RequiresDocker -@Testcontainers -public class LastNElasticsearchSvcMultipleObservationsIT { - - @Container - public static ElasticsearchContainer elasticsearchContainer = TestElasticsearchContainerHelper.getEmbeddedElasticSearch(); - private static boolean indexLoaded = false; - private final Map>> createdPatientObservationMap = new HashMap<>(); - private final FhirContext myFhirContext = FhirContext.forR4Cached(); - private ElasticsearchSvcImpl elasticsearchSvc; - - @BeforeEach - public void before() throws IOException { - PartitionSettings partitionSettings = new PartitionSettings(); - partitionSettings.setPartitioningEnabled(false); - elasticsearchSvc = new ElasticsearchSvcImpl(partitionSettings, "http", elasticsearchContainer.getHost() + ":" + elasticsearchContainer.getMappedPort(9200), null, null); - - if (!indexLoaded) { - createMultiplePatientsAndObservations(); - indexLoaded = true; - } - } - - @AfterEach - public void after() throws IOException { - elasticsearchSvc.close(); - } - - @Test - public void testLastNAllPatientsQuery() { - - // execute Observation ID search (Composite Aggregation) last 3 observations for each patient - SearchParameterMap searchParameterMap = new SearchParameterMap(); - IntStream.range(0, 10).forEach(index -> { - ReferenceParam subjectParam = new ReferenceParam("Patient", "", String.valueOf(index)); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - }); - searchParameterMap.setLastNMax(3); - - List observations = elasticsearchSvc.executeLastNWithAllFieldsForTest(searchParameterMap, myFhirContext); - - assertEquals(60, observations.size()); - - // Observation documents should be grouped by subject, then by observation code, and then sorted by effective date/time - // within each observation code. Verify the grouping by creating a nested Map. - Map>> queriedPatientObservationMap = new HashMap<>(); - ObservationJson previousObservationJson = null; - for (ObservationJson observationJson : observations) { - assertNotNull(observationJson.getIdentifier()); - assertNotNull(observationJson.getSubject()); - assertNotNull(observationJson.getCode_concept_id()); - assertNotNull(observationJson.getEffectiveDtm()); - if (previousObservationJson == null) { - ArrayList observationDates = new ArrayList<>(); - observationDates.add(observationJson.getEffectiveDtm()); - Map> codeObservationMap = new HashMap<>(); - codeObservationMap.put(observationJson.getCode_concept_id(), observationDates); - queriedPatientObservationMap.put(observationJson.getSubject(), codeObservationMap); - } else if (observationJson.getSubject().equals(previousObservationJson.getSubject())) { - if (observationJson.getCode_concept_id().equals(previousObservationJson.getCode_concept_id())) { - queriedPatientObservationMap.get(observationJson.getSubject()).get(observationJson.getCode_concept_id()). - add(observationJson.getEffectiveDtm()); - } else { - Map> codeObservationDateMap = queriedPatientObservationMap.get(observationJson.getSubject()); - // Ensure that code concept was not already retrieved out of order for this subject/patient. - assertFalse(codeObservationDateMap.containsKey(observationJson.getCode_concept_id())); - ArrayList observationDates = new ArrayList<>(); - observationDates.add(observationJson.getEffectiveDtm()); - codeObservationDateMap.put(observationJson.getCode_concept_id(), observationDates); - } - } else { - // Ensure that subject/patient was not already retrieved out of order - assertFalse(queriedPatientObservationMap.containsKey(observationJson.getSubject())); - ArrayList observationDates = new ArrayList<>(); - observationDates.add(observationJson.getEffectiveDtm()); - Map> codeObservationMap = new HashMap<>(); - codeObservationMap.put(observationJson.getCode_concept_id(), observationDates); - queriedPatientObservationMap.put(observationJson.getSubject(), codeObservationMap); - } - previousObservationJson = observationJson; - } - - // Finally check that only the most recent effective date/time values were returned and in the correct order. - for (String subjectId : queriedPatientObservationMap.keySet()) { - Map> queriedObservationCodeMap = queriedPatientObservationMap.get(subjectId); - Map> createdObservationCodeMap = createdPatientObservationMap.get(subjectId); - for (String observationCode : queriedObservationCodeMap.keySet()) { - List queriedObservationDates = queriedObservationCodeMap.get(observationCode); - List createdObservationDates = createdObservationCodeMap.get(observationCode); - for (int dateIdx = 0; dateIdx < queriedObservationDates.size(); dateIdx++) { - assertEquals(createdObservationDates.get(dateIdx), queriedObservationDates.get(dateIdx)); - } - } - } - - } - - @Test - public void testLastNMultiPatientMultiCodeHashMultiCategoryHash() { - // Multiple Subject references - SearchParameterMap searchParameterMap = new SearchParameterMap(); - ReferenceParam subjectParam1 = new ReferenceParam("Patient", "", "3"); - ReferenceParam subjectParam2 = new ReferenceParam("Patient", "", "5"); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam1, subjectParam2)); - TokenParam categoryParam1 = new TokenParam("http://mycodes.org/fhir/observation-category", "test-heart-rate"); - TokenParam categoryParam2 = new TokenParam("http://mycodes.org/fhir/observation-category", "test-vital-signs"); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(categoryParam1, categoryParam2)); - TokenParam codeParam1 = new TokenParam("http://mycodes.org/fhir/observation-code", "test-code-1"); - TokenParam codeParam2 = new TokenParam("http://mycodes.org/fhir/observation-code", "test-code-2"); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(codeParam1, codeParam2)); - searchParameterMap.setLastNMax(100); - - List observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - - assertEquals(20, observations.size()); - - // Repeat with multiple Patient parameter - searchParameterMap = new SearchParameterMap(); - ReferenceParam patientParam1 = new ReferenceParam("Patient", "", "8"); - ReferenceParam patientParam2 = new ReferenceParam("Patient", "", "6"); - searchParameterMap.add(Observation.SP_PATIENT, buildReferenceAndListParam(patientParam1, patientParam2)); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(categoryParam1, categoryParam2)); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(codeParam1, codeParam2)); - searchParameterMap.setLastNMax(100); - - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - - assertEquals(20, observations.size()); - - } - - private ReferenceAndListParam buildReferenceAndListParam(ReferenceParam... theReference) { - ReferenceOrListParam myReferenceOrListParam = new ReferenceOrListParam(); - for (ReferenceParam referenceParam : theReference) { - myReferenceOrListParam.addOr(referenceParam); - } - return new ReferenceAndListParam().addAnd(myReferenceOrListParam); - } - - private TokenAndListParam buildTokenAndListParam(TokenParam... theToken) { - TokenOrListParam myTokenOrListParam = new TokenOrListParam(); - for (TokenParam tokenParam : theToken) { - myTokenOrListParam.addOr(tokenParam); - } - return new TokenAndListParam().addAnd(myTokenOrListParam); - } - - @Test - public void testLastNCodeCodeOnlyCategoryCodeOnly() { - // Include subject - SearchParameterMap searchParameterMap = new SearchParameterMap(); - ReferenceParam subjectParam = new ReferenceParam("Patient", "", "3"); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - TokenParam categoryParam = new TokenParam(null, "test-heart-rate"); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(categoryParam)); - TokenParam codeParam = new TokenParam(null, "test-code-1"); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(codeParam)); - searchParameterMap.setLastNMax(100); - - List observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - - assertEquals(5, observations.size()); - - } - - @Test - public void testLastNCodeSystemOnlyCategorySystemOnly() { - // Include subject and patient - SearchParameterMap searchParameterMap = new SearchParameterMap(); - ReferenceParam subjectParam = new ReferenceParam("Patient", "", "3"); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - TokenParam categoryParam = new TokenParam("http://mycodes.org/fhir/observation-category", null); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(categoryParam)); - TokenParam codeParam = new TokenParam("http://mycodes.org/fhir/observation-code", null); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(codeParam)); - searchParameterMap.setLastNMax(100); - - List observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - - assertEquals(10, observations.size()); - } - - @Test - public void testLastNCodeCodeTextCategoryTextOnly() { - SearchParameterMap searchParameterMap = new SearchParameterMap(); - ReferenceParam subjectParam = new ReferenceParam("Patient", "", "3"); - - // Check case match - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - TokenParam categoryParam = new TokenParam("Heart"); - categoryParam.setModifier(TokenParamModifier.TEXT); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(categoryParam)); - TokenParam codeParam = new TokenParam("Code1"); - codeParam.setModifier(TokenParamModifier.TEXT); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(codeParam)); - searchParameterMap.setLastNMax(100); - - List observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - - assertEquals(5, observations.size()); - - // Check case not match - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - categoryParam = new TokenParam("heart"); - categoryParam.setModifier(TokenParamModifier.TEXT); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(categoryParam)); - codeParam = new TokenParam("code1"); - codeParam.setModifier(TokenParamModifier.TEXT); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(codeParam)); - searchParameterMap.setLastNMax(100); - - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - - assertEquals(5, observations.size()); - - // Check hyphenated strings - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - categoryParam = new TokenParam("heart-rate"); - categoryParam.setModifier(TokenParamModifier.TEXT); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(categoryParam)); - codeParam = new TokenParam("code1"); - codeParam.setModifier(TokenParamModifier.TEXT); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(codeParam)); - searchParameterMap.setLastNMax(100); - - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - - assertEquals(5, observations.size()); - - // Check partial strings - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - categoryParam = new TokenParam("hear"); - categoryParam.setModifier(TokenParamModifier.TEXT); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(categoryParam)); - codeParam = new TokenParam("1-obs"); - codeParam.setModifier(TokenParamModifier.TEXT); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(codeParam)); - searchParameterMap.setLastNMax(100); - - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - - assertEquals(5, observations.size()); - - } - - @Test - public void testLastNNoMatchQueries() { - - ReferenceParam validPatientParam = new ReferenceParam("Patient", "", "9"); - TokenParam validCategoryCodeParam = new TokenParam("http://mycodes.org/fhir/observation-category", "test-heart-rate"); - TokenParam validObservationCodeParam = new TokenParam("http://mycodes.org/fhir/observation-code", "test-code-1"); - DateParam validDateParam = new DateParam(ParamPrefixEnum.EQUAL, new Date(TEST_BASELINE_TIMESTAMP - (9 * 3600 * 1000))); - - // Ensure that valid parameters are indeed valid - SearchParameterMap searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_PATIENT, buildReferenceAndListParam(validPatientParam)); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(validCategoryCodeParam)); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(validObservationCodeParam)); - searchParameterMap.add(Observation.SP_DATE, validDateParam); - searchParameterMap.setLastNMax(100); - - List observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(1, observations.size()); - - // Invalid Patient - searchParameterMap = new SearchParameterMap(); - ReferenceParam patientParam = new ReferenceParam("Patient", "", "10"); - searchParameterMap.add(Observation.SP_PATIENT, buildReferenceAndListParam(patientParam)); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(validCategoryCodeParam)); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(validObservationCodeParam)); - searchParameterMap.add(Observation.SP_DATE, validDateParam); - searchParameterMap.setLastNMax(100); - - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(0, observations.size()); - - // Invalid subject - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(patientParam)); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(validCategoryCodeParam)); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(validObservationCodeParam)); - searchParameterMap.add(Observation.SP_DATE, validDateParam); - searchParameterMap.setLastNMax(100); - - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(0, observations.size()); - - // Invalid observation code - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(validPatientParam)); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(validCategoryCodeParam)); - TokenParam codeParam = new TokenParam("http://mycodes.org/fhir/observation-code", "test-code-999"); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(codeParam)); - searchParameterMap.add(Observation.SP_DATE, validDateParam); - searchParameterMap.setLastNMax(100); - - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(0, observations.size()); - - // Invalid category code - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(validPatientParam)); - TokenParam categoryParam = new TokenParam("http://mycodes.org/fhir/observation-category", "test-not-a-category"); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(categoryParam)); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(validObservationCodeParam)); - searchParameterMap.add(Observation.SP_DATE, validDateParam); - searchParameterMap.setLastNMax(100); - - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(0, observations.size()); - - // Invalid date - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(validPatientParam)); - searchParameterMap.add(Observation.SP_CATEGORY, buildTokenAndListParam(validCategoryCodeParam)); - searchParameterMap.add(Observation.SP_CODE, buildTokenAndListParam(validObservationCodeParam)); - searchParameterMap.add(Observation.SP_DATE, new DateParam(ParamPrefixEnum.GREATERTHAN, TEST_BASELINE_TIMESTAMP)); - searchParameterMap.setLastNMax(100); - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(0, observations.size()); - - } - - @Test - public void testLastNEffectiveDates() { - Date highDate = new Date(TEST_BASELINE_TIMESTAMP - (3600 * 1000)); - Date lowDate = new Date(TEST_BASELINE_TIMESTAMP - (10 * 3600 * 1000)); - - SearchParameterMap searchParameterMap = new SearchParameterMap(); - ReferenceParam subjectParam = new ReferenceParam("Patient", "", "3"); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - DateParam dateParam = new DateParam(ParamPrefixEnum.EQUAL, lowDate); - searchParameterMap.add(Observation.SP_DATE, dateParam); - searchParameterMap.setLastNMax(100); - List observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(1, observations.size()); - - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - dateParam = new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, lowDate); - searchParameterMap.add(Observation.SP_DATE, dateParam); - searchParameterMap.setLastNMax(100); - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(10, observations.size()); - - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - dateParam = new DateParam(ParamPrefixEnum.GREATERTHAN, lowDate); - searchParameterMap.add(Observation.SP_DATE, dateParam); - searchParameterMap.setLastNMax(100); - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(9, observations.size()); - - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - dateParam = new DateParam(ParamPrefixEnum.STARTS_AFTER, lowDate); - searchParameterMap.add(Observation.SP_DATE, dateParam); - searchParameterMap.setLastNMax(100); - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(9, observations.size()); - - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - dateParam = new DateParam(ParamPrefixEnum.LESSTHAN_OR_EQUALS, highDate); - searchParameterMap.add(Observation.SP_DATE, dateParam); - searchParameterMap.setLastNMax(100); - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(10, observations.size()); - - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - dateParam = new DateParam(ParamPrefixEnum.LESSTHAN, highDate); - searchParameterMap.add(Observation.SP_DATE, dateParam); - searchParameterMap.setLastNMax(100); - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(9, observations.size()); - - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - dateParam = new DateParam(ParamPrefixEnum.ENDS_BEFORE, highDate); - searchParameterMap.add(Observation.SP_DATE, dateParam); - searchParameterMap.setLastNMax(100); - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(9, observations.size()); - - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - DateParam startDateParam = new DateParam(ParamPrefixEnum.GREATERTHAN, new Date(TEST_BASELINE_TIMESTAMP - (4 * 3600 * 1000))); - DateAndListParam dateAndListParam = new DateAndListParam(); - dateAndListParam.addAnd(new DateOrListParam().addOr(startDateParam)); - dateParam = new DateParam(ParamPrefixEnum.LESSTHAN_OR_EQUALS, highDate); - dateAndListParam.addAnd(new DateOrListParam().addOr(dateParam)); - searchParameterMap.add(Observation.SP_DATE, dateAndListParam); - searchParameterMap.setLastNMax(100); - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(3, observations.size()); - - searchParameterMap = new SearchParameterMap(); - searchParameterMap.add(Observation.SP_SUBJECT, buildReferenceAndListParam(subjectParam)); - startDateParam = new DateParam(ParamPrefixEnum.GREATERTHAN, new Date(TEST_BASELINE_TIMESTAMP - (4 * 3600 * 1000))); - searchParameterMap.add(Observation.SP_DATE, startDateParam); - dateParam = new DateParam(ParamPrefixEnum.LESSTHAN, lowDate); - searchParameterMap.add(Observation.SP_DATE, dateParam); - searchParameterMap.setLastNMax(100); - observations = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - assertEquals(0, observations.size()); - - } - - private void createMultiplePatientsAndObservations() throws IOException { - List patientIds = IntStream.range(0, 10).boxed().collect(Collectors.toList()); - List observations = LastNTestDataGenerator.createMultipleObservationJson(patientIds); - - observations.forEach(observation -> { - CodeJson codeJson = observation.getCode(); - assertTrue(elasticsearchSvc.createOrUpdateObservationCodeIndex(codeJson.getCodeableConceptId(), codeJson)); - assertTrue(elasticsearchSvc.createOrUpdateObservationIndex(observation.getIdentifier(), observation)); - - String subject = observation.getSubject(); - if (createdPatientObservationMap.containsKey(subject)) { - Map> observationCodeMap = createdPatientObservationMap.get(subject); - if (observationCodeMap.containsKey(observation.getCode_concept_id())) { - List observationDates = observationCodeMap.get(observation.getCode_concept_id()); - observationDates.add(observation.getEffectiveDtm()); - observationDates.sort(Collections.reverseOrder()); - } else { - ArrayList observationDates = new ArrayList<>(); - observationDates.add(observation.getEffectiveDtm()); - observationCodeMap.put(observation.getCode_concept_id(), observationDates); - } - } else { - ArrayList observationDates = new ArrayList<>(); - observationDates.add(observation.getEffectiveDtm()); - Map> codeObservationMap = new HashMap<>(); - codeObservationMap.put(observation.getCode_concept_id(), observationDates); - createdPatientObservationMap.put(subject, codeObservationMap); - } - }); - - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_INDEX); - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_CODE_INDEX); - - } - - @Test - public void testLastNNoParamsQuery() { - SearchParameterMap searchParameterMap = new SearchParameterMap(); - searchParameterMap.setLastNMax(1); - List observations = elasticsearchSvc.executeLastNWithAllFieldsForTest(searchParameterMap, myFhirContext); - - assertEquals(2, observations.size()); - - String observationCode1 = observations.get(0).getCode_coding_code_system_hash(); - String observationCode2 = observations.get(1).getCode_coding_code_system_hash(); - - assertNotEquals(observationCode1, observationCode2); - - } - -} diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNElasticsearchSvcSingleObservationIT.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNElasticsearchSvcSingleObservationIT.java deleted file mode 100644 index 962241e227b..00000000000 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNElasticsearchSvcSingleObservationIT.java +++ /dev/null @@ -1,262 +0,0 @@ -package ca.uhn.fhir.jpa.search.lastn; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.jpa.model.config.PartitionSettings; -import ca.uhn.fhir.jpa.model.util.CodeSystemHash; -import ca.uhn.fhir.jpa.search.lastn.json.CodeJson; -import ca.uhn.fhir.jpa.search.lastn.json.ObservationJson; -import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; -import ca.uhn.fhir.jpa.test.config.TestElasticsearchContainerHelper; -import ca.uhn.fhir.model.dstu2.resource.Observation; -import ca.uhn.fhir.rest.param.DateParam; -import ca.uhn.fhir.rest.param.ParamPrefixEnum; -import ca.uhn.fhir.rest.param.ReferenceAndListParam; -import ca.uhn.fhir.rest.param.ReferenceOrListParam; -import ca.uhn.fhir.rest.param.ReferenceParam; -import ca.uhn.fhir.rest.param.TokenAndListParam; -import ca.uhn.fhir.rest.param.TokenOrListParam; -import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.test.utilities.docker.RequiresDocker; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.testcontainers.elasticsearch.ElasticsearchContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -import java.io.IOException; -import java.util.Date; -import java.util.List; - -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.CATEGORYFIRSTCODINGSYSTEM; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.CATEGORYSECONDCODINGSYSTEM; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.CATEGORYTHIRDCODINGSYSTEM; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.CODEFIRSTCODINGCODE; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.CODEFIRSTCODINGDISPLAY; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.CODEFIRSTCODINGSYSTEM; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.FIRSTCATEGORYFIRSTCODINGCODE; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.FIRSTCATEGORYFIRSTCODINGDISPLAY; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.FIRSTCATEGORYSECONDCODINGCODE; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.FIRSTCATEGORYSECONDCODINGDISPLAY; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.FIRSTCATEGORYTEXT; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.FIRSTCATEGORYTHIRDCODINGCODE; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.FIRSTCATEGORYTHIRDCODINGDISPLAY; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.OBSERVATIONSINGLECODEID; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.OBSERVATION_CODE_CONCEPT_TEXT_1; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.SECONDCATEGORYFIRSTCODINGCODE; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.SECONDCATEGORYFIRSTCODINGDISPLAY; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.SECONDCATEGORYSECONDCODINGCODE; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.SECONDCATEGORYSECONDCODINGDISPLAY; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.SECONDCATEGORYTEXT; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.SECONDCATEGORYTHIRDCODINGCODE; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.SECONDCATEGORYTHIRDCODINGDISPLAY; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.SINGLE_OBSERVATION_RESOURCE_PID; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.SINGLE_OBSERVATION_SUBJECT_ID; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.TEST_BASELINE_TIMESTAMP; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.THIRDCATEGORYFIRSTCODINGCODE; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.THIRDCATEGORYFIRSTCODINGDISPLAY; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.THIRDCATEGORYSECONDCODINGCODE; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.THIRDCATEGORYSECONDCODINGDISPLAY; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.THIRDCATEGORYTEXT; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.THIRDCATEGORYTHIRDCODINGCODE; -import static ca.uhn.fhir.jpa.search.lastn.LastNTestDataGenerator.THIRDCATEGORYTHIRDCODINGDISPLAY; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@ExtendWith(SpringExtension.class) -@RequiresDocker -@Testcontainers -public class LastNElasticsearchSvcSingleObservationIT { - - private final FhirContext myFhirContext = FhirContext.forR4Cached(); - - ElasticsearchSvcImpl elasticsearchSvc; - - @Container - public static ElasticsearchContainer elasticsearchContainer = TestElasticsearchContainerHelper.getEmbeddedElasticSearch(); - - - @BeforeEach - public void before() { - PartitionSettings partitionSettings = new PartitionSettings(); - partitionSettings.setPartitioningEnabled(false); - elasticsearchSvc = new ElasticsearchSvcImpl(partitionSettings, "http", elasticsearchContainer.getHost() + ":" + elasticsearchContainer.getMappedPort(9200), "", ""); - } - - @AfterEach - public void after() throws IOException { - elasticsearchSvc.deleteAllDocumentsForTest(ElasticsearchSvcImpl.OBSERVATION_INDEX); - elasticsearchSvc.deleteAllDocumentsForTest(ElasticsearchSvcImpl.OBSERVATION_CODE_INDEX); - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_INDEX); - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_CODE_INDEX); - } - - @Test - public void testSingleObservationQuery() throws IOException { - - // Create test observation - ObservationJson indexedObservation = LastNTestDataGenerator.createSingleObservationJson(); - assertTrue(elasticsearchSvc.createOrUpdateObservationIndex(SINGLE_OBSERVATION_RESOURCE_PID, indexedObservation)); - assertTrue(elasticsearchSvc.createOrUpdateObservationCodeIndex(OBSERVATIONSINGLECODEID, indexedObservation.getCode())); - - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_INDEX); - elasticsearchSvc.refreshIndex(ElasticsearchSvcImpl.OBSERVATION_CODE_INDEX); - - SearchParameterMap searchParameterMap = new SearchParameterMap(); - ReferenceParam subjectParam = new ReferenceParam("Patient", "", SINGLE_OBSERVATION_SUBJECT_ID); - searchParameterMap.add(Observation.SP_SUBJECT, new ReferenceAndListParam().addAnd(new ReferenceOrListParam().addOr(subjectParam))); - TokenParam categoryParam = new TokenParam(CATEGORYFIRSTCODINGSYSTEM, FIRSTCATEGORYFIRSTCODINGCODE); - searchParameterMap.add(Observation.SP_CATEGORY, new TokenAndListParam().addAnd(new TokenOrListParam().addOr(categoryParam))); - TokenParam codeParam = new TokenParam(CODEFIRSTCODINGSYSTEM, CODEFIRSTCODINGCODE); - searchParameterMap.add(Observation.SP_CODE, new TokenAndListParam().addAnd(new TokenOrListParam().addOr(codeParam))); - searchParameterMap.add(Observation.SP_DATE, new DateParam(ParamPrefixEnum.EQUAL, new Date(TEST_BASELINE_TIMESTAMP))); - - searchParameterMap.setLastNMax(3); - - // execute Observation ID search - List observationIdsOnly = elasticsearchSvc.executeLastN(searchParameterMap, myFhirContext, 100); - - assertEquals(1, observationIdsOnly.size()); - assertEquals(SINGLE_OBSERVATION_RESOURCE_PID, observationIdsOnly.get(0)); - - // execute Observation search for all search fields - List observations = elasticsearchSvc.executeLastNWithAllFieldsForTest(searchParameterMap, myFhirContext); - - validateFullObservationSearch(observations); - } - - private void validateFullObservationSearch(List observations) throws IOException { - - assertEquals(1, observations.size()); - ObservationJson observation = observations.get(0); - assertEquals(SINGLE_OBSERVATION_RESOURCE_PID, observation.getIdentifier()); - - assertEquals(SINGLE_OBSERVATION_SUBJECT_ID, observation.getSubject()); - assertEquals(SINGLE_OBSERVATION_RESOURCE_PID, observation.getIdentifier()); - assertEquals(new Date(TEST_BASELINE_TIMESTAMP), observation.getEffectiveDtm()); - assertEquals(OBSERVATIONSINGLECODEID, observation.getCode_concept_id()); - - List category_concept_text_values = observation.getCategory_concept_text(); - assertEquals(3, category_concept_text_values.size()); - assertEquals(FIRSTCATEGORYTEXT, category_concept_text_values.get(0)); - assertEquals(SECONDCATEGORYTEXT, category_concept_text_values.get(1)); - assertEquals(THIRDCATEGORYTEXT, category_concept_text_values.get(2)); - - List> category_codings_systems = observation.getCategory_coding_system(); - assertEquals(3, category_codings_systems.size()); - List category_coding_systems = category_codings_systems.get(0); - assertEquals(3, category_coding_systems.size()); - assertEquals(CATEGORYFIRSTCODINGSYSTEM, category_coding_systems.get(0)); - assertEquals(CATEGORYSECONDCODINGSYSTEM, category_coding_systems.get(1)); - assertEquals(CATEGORYTHIRDCODINGSYSTEM, category_coding_systems.get(2)); - category_coding_systems = category_codings_systems.get(1); - assertEquals(3, category_coding_systems.size()); - assertEquals(CATEGORYFIRSTCODINGSYSTEM, category_coding_systems.get(0)); - assertEquals(CATEGORYSECONDCODINGSYSTEM, category_coding_systems.get(1)); - assertEquals(CATEGORYTHIRDCODINGSYSTEM, category_coding_systems.get(2)); - category_coding_systems = category_codings_systems.get(2); - assertEquals(3, category_coding_systems.size()); - assertEquals(CATEGORYFIRSTCODINGSYSTEM, category_coding_systems.get(0)); - assertEquals(CATEGORYSECONDCODINGSYSTEM, category_coding_systems.get(1)); - assertEquals(CATEGORYTHIRDCODINGSYSTEM, category_coding_systems.get(2)); - - List> category_codings_codes = observation.getCategory_coding_code(); - assertEquals(3, category_codings_codes.size()); - List category_coding_codes = category_codings_codes.get(0); - assertEquals(3, category_coding_codes.size()); - assertEquals(FIRSTCATEGORYFIRSTCODINGCODE, category_coding_codes.get(0)); - assertEquals(FIRSTCATEGORYSECONDCODINGCODE, category_coding_codes.get(1)); - assertEquals(FIRSTCATEGORYTHIRDCODINGCODE, category_coding_codes.get(2)); - category_coding_codes = category_codings_codes.get(1); - assertEquals(3, category_coding_codes.size()); - assertEquals(SECONDCATEGORYFIRSTCODINGCODE, category_coding_codes.get(0)); - assertEquals(SECONDCATEGORYSECONDCODINGCODE, category_coding_codes.get(1)); - assertEquals(SECONDCATEGORYTHIRDCODINGCODE, category_coding_codes.get(2)); - category_coding_codes = category_codings_codes.get(2); - assertEquals(3, category_coding_codes.size()); - assertEquals(THIRDCATEGORYFIRSTCODINGCODE, category_coding_codes.get(0)); - assertEquals(THIRDCATEGORYSECONDCODINGCODE, category_coding_codes.get(1)); - assertEquals(THIRDCATEGORYTHIRDCODINGCODE, category_coding_codes.get(2)); - - List> category_codings_displays = observation.getCategory_coding_display(); - assertEquals(3, category_codings_displays.size()); - List category_coding_displays = category_codings_displays.get(0); - assertEquals(FIRSTCATEGORYFIRSTCODINGDISPLAY, category_coding_displays.get(0)); - assertEquals(FIRSTCATEGORYSECONDCODINGDISPLAY, category_coding_displays.get(1)); - assertEquals(FIRSTCATEGORYTHIRDCODINGDISPLAY, category_coding_displays.get(2)); - category_coding_displays = category_codings_displays.get(1); - assertEquals(3, category_coding_displays.size()); - assertEquals(SECONDCATEGORYFIRSTCODINGDISPLAY, category_coding_displays.get(0)); - assertEquals(SECONDCATEGORYSECONDCODINGDISPLAY, category_coding_displays.get(1)); - assertEquals(SECONDCATEGORYTHIRDCODINGDISPLAY, category_coding_displays.get(2)); - category_coding_displays = category_codings_displays.get(2); - assertEquals(3, category_coding_displays.size()); - assertEquals(THIRDCATEGORYFIRSTCODINGDISPLAY, category_coding_displays.get(0)); - assertEquals(THIRDCATEGORYSECONDCODINGDISPLAY, category_coding_displays.get(1)); - assertEquals(THIRDCATEGORYTHIRDCODINGDISPLAY, category_coding_displays.get(2)); - - List> category_codings_code_system_hashes = observation.getCategory_coding_code_system_hash(); - assertEquals(3, category_codings_code_system_hashes.size()); - List category_coding_code_system_hashes = category_codings_code_system_hashes.get(0); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CATEGORYFIRSTCODINGSYSTEM, FIRSTCATEGORYFIRSTCODINGCODE)), category_coding_code_system_hashes.get(0)); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CATEGORYSECONDCODINGSYSTEM, FIRSTCATEGORYSECONDCODINGCODE)), category_coding_code_system_hashes.get(1)); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CATEGORYTHIRDCODINGSYSTEM, FIRSTCATEGORYTHIRDCODINGCODE)), category_coding_code_system_hashes.get(2)); - category_coding_code_system_hashes = category_codings_code_system_hashes.get(1); - assertEquals(3, category_coding_code_system_hashes.size()); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CATEGORYFIRSTCODINGSYSTEM, SECONDCATEGORYFIRSTCODINGCODE)), category_coding_code_system_hashes.get(0)); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CATEGORYSECONDCODINGSYSTEM, SECONDCATEGORYSECONDCODINGCODE)), category_coding_code_system_hashes.get(1)); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CATEGORYTHIRDCODINGSYSTEM, SECONDCATEGORYTHIRDCODINGCODE)), category_coding_code_system_hashes.get(2)); - category_coding_code_system_hashes = category_codings_code_system_hashes.get(2); - assertEquals(3, category_coding_code_system_hashes.size()); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CATEGORYFIRSTCODINGSYSTEM, THIRDCATEGORYFIRSTCODINGCODE)), category_coding_code_system_hashes.get(0)); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CATEGORYSECONDCODINGSYSTEM, THIRDCATEGORYSECONDCODINGCODE)), category_coding_code_system_hashes.get(1)); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CATEGORYTHIRDCODINGSYSTEM, THIRDCATEGORYTHIRDCODINGCODE)), category_coding_code_system_hashes.get(2)); - - String code_concept_text_values = observation.getCode_concept_text(); - assertEquals(OBSERVATION_CODE_CONCEPT_TEXT_1, code_concept_text_values); - - String code_coding_systems = observation.getCode_coding_system(); - assertEquals(CODEFIRSTCODINGSYSTEM, code_coding_systems); - - String code_coding_codes = observation.getCode_coding_code(); - assertEquals(CODEFIRSTCODINGCODE, code_coding_codes); - - String code_coding_display = observation.getCode_coding_display(); - assertEquals(CODEFIRSTCODINGDISPLAY, code_coding_display); - - String code_coding_code_system_hash = observation.getCode_coding_code_system_hash(); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CODEFIRSTCODINGSYSTEM, CODEFIRSTCODINGCODE)), code_coding_code_system_hash); - - // Retrieve all Observation codes - List codes = elasticsearchSvc.queryAllIndexedObservationCodesForTest(); - assertEquals(1, codes.size()); - CodeJson persistedObservationCode = codes.get(0); - - String persistedCodeConceptID = persistedObservationCode.getCodeableConceptId(); - assertEquals(OBSERVATIONSINGLECODEID, persistedCodeConceptID); - String persistedCodeConceptText = persistedObservationCode.getCodeableConceptText(); - assertEquals(OBSERVATION_CODE_CONCEPT_TEXT_1, persistedCodeConceptText); - - List persistedCodeCodingSystems = persistedObservationCode.getCoding_system(); - assertEquals(1, persistedCodeCodingSystems.size()); - assertEquals(CODEFIRSTCODINGSYSTEM, persistedCodeCodingSystems.get(0)); - - List persistedCodeCodingCodes = persistedObservationCode.getCoding_code(); - assertEquals(1, persistedCodeCodingCodes.size()); - assertEquals(CODEFIRSTCODINGCODE, persistedCodeCodingCodes.get(0)); - - List persistedCodeCodingDisplays = persistedObservationCode.getCoding_display(); - assertEquals(1, persistedCodeCodingDisplays.size()); - assertEquals(CODEFIRSTCODINGDISPLAY, persistedCodeCodingDisplays.get(0)); - - List persistedCodeCodingCodeSystemHashes = persistedObservationCode.getCoding_code_system_hash(); - assertEquals(1, persistedCodeCodingCodeSystemHashes.size()); - assertEquals(String.valueOf(CodeSystemHash.hashCodeSystem(CODEFIRSTCODINGSYSTEM, CODEFIRSTCODINGCODE)), persistedCodeCodingCodeSystemHashes.get(0)); - - - } - -} - diff --git a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNTestDataGenerator.java b/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNTestDataGenerator.java deleted file mode 100644 index ca7b3172d1b..00000000000 --- a/hapi-fhir-jpaserver-elastic-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/lastn/LastNTestDataGenerator.java +++ /dev/null @@ -1,144 +0,0 @@ -package ca.uhn.fhir.jpa.search.lastn; - -import ca.uhn.fhir.jpa.search.lastn.json.CodeJson; -import ca.uhn.fhir.jpa.search.lastn.json.ObservationJson; - -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class LastNTestDataGenerator { - - public static final long TEST_BASELINE_TIMESTAMP = new Date().toInstant().toEpochMilli(); - - public static final String SINGLE_OBSERVATION_RESOURCE_PID = "123"; - public static final String SINGLE_OBSERVATION_SUBJECT_ID = "Patient/4567"; - - public static final String FIRSTCATEGORYTEXT = "Test Codeable Concept Field for first category"; - public static final String CATEGORYFIRSTCODINGSYSTEM = "http://mycodes.org/fhir/observation-category"; - public static final String CATEGORYSECONDCODINGSYSTEM = "http://myalternatecodes.org/fhir/observation-category"; - public static final String CATEGORYTHIRDCODINGSYSTEM = "http://mysecondaltcodes.org/fhir/observation-category"; - public static final String FIRSTCATEGORYFIRSTCODINGCODE = "test-heart-rate"; - public static final String FIRSTCATEGORYFIRSTCODINGDISPLAY = "Test Heart Rate"; - public static final String FIRSTCATEGORYSECONDCODINGCODE = "test-alt-heart-rate"; - public static final String FIRSTCATEGORYSECONDCODINGDISPLAY = "Test HeartRate"; - public static final String FIRSTCATEGORYTHIRDCODINGCODE = "test-2nd-alt-heart-rate"; - public static final String FIRSTCATEGORYTHIRDCODINGDISPLAY = "Test Heart-Rate"; - public static final String SECONDCATEGORYTEXT = "Test Codeable Concept Field for for second category"; - public static final String SECONDCATEGORYFIRSTCODINGCODE = "test-vital-signs"; - public static final String SECONDCATEGORYFIRSTCODINGDISPLAY = "Test Vital Signs"; - public static final String SECONDCATEGORYSECONDCODINGCODE = "test-alt-vitals"; - public static final String SECONDCATEGORYSECONDCODINGDISPLAY = "Test Vital-Signs"; - public static final String SECONDCATEGORYTHIRDCODINGCODE = "test-2nd-alt-vitals"; - public static final String SECONDCATEGORYTHIRDCODINGDISPLAY = "Test Vitals"; - public static final String THIRDCATEGORYTEXT = "Test Codeable Concept Field for third category"; - public static final String THIRDCATEGORYFIRSTCODINGCODE = "test-vital-panel"; - public static final String THIRDCATEGORYFIRSTCODINGDISPLAY = "test-vitals-panel display"; - public static final String THIRDCATEGORYSECONDCODINGCODE = "test-alt-vitals-panel"; - public static final String THIRDCATEGORYSECONDCODINGDISPLAY = "test-alt-vitals display"; - public static final String THIRDCATEGORYTHIRDCODINGCODE = "test-2nd-alt-vitals-panel"; - public static final String THIRDCATEGORYTHIRDCODINGDISPLAY = "test-2nd-alt-vitals-panel display"; - public static final String OBSERVATIONSINGLECODEID = UUID.randomUUID().toString(); - public static final String OBSERVATION_CODE_CONCEPT_TEXT_1 = "Test Codeable Concept Field for First Code"; - public static final String OBSERVATION_CODE_CONCEPT_TEXT_2 = "Test Codeable Concept Field for Second Code"; - public static final String CODEFIRSTCODINGSYSTEM = "http://mycodes.org/fhir/observation-code"; - public static final String CODEFIRSTCODINGCODE = "test-code-1"; - public static final String CODEFIRSTCODINGDISPLAY = "1-Observation Code1"; - public static final String CODE_SECOND_CODING_SYSTEM = "http://mycodes.org/fhir/observation-code"; - public static final String CODE_SECOND_CODING_CODE = "test-code-2"; - public static final String CODE_SECOND_CODING_DISPLAY = "2-Observation Code2"; - - public static ObservationJson createSingleObservationJson() { - ObservationJson indexedObservation = new ObservationJson(); - indexedObservation.setIdentifier(SINGLE_OBSERVATION_RESOURCE_PID); - indexedObservation.setSubject(SINGLE_OBSERVATION_SUBJECT_ID); - indexedObservation.setEffectiveDtm(new Date(TEST_BASELINE_TIMESTAMP)); - - indexedObservation.setCategories(createCategoryCodeableConcepts()); - - // Create CodeableConcept for Code - CodeJson codeableConceptField = new CodeJson(); - codeableConceptField.setCodeableConceptId(OBSERVATIONSINGLECODEID); - codeableConceptField.setCodeableConceptText(OBSERVATION_CODE_CONCEPT_TEXT_1); - codeableConceptField.addCoding(CODEFIRSTCODINGSYSTEM, CODEFIRSTCODINGCODE, CODEFIRSTCODINGDISPLAY); - - indexedObservation.setCode(codeableConceptField); - - return indexedObservation; - } - - private static List createCategoryCodeableConcepts() { - CodeJson categoryCodeableConcept1 = new CodeJson(); - categoryCodeableConcept1.setCodeableConceptText(FIRSTCATEGORYTEXT); - categoryCodeableConcept1.addCoding(CATEGORYFIRSTCODINGSYSTEM, FIRSTCATEGORYFIRSTCODINGCODE, FIRSTCATEGORYFIRSTCODINGDISPLAY); - categoryCodeableConcept1.addCoding(CATEGORYSECONDCODINGSYSTEM, FIRSTCATEGORYSECONDCODINGCODE, FIRSTCATEGORYSECONDCODINGDISPLAY); - categoryCodeableConcept1.addCoding(CATEGORYTHIRDCODINGSYSTEM, FIRSTCATEGORYTHIRDCODINGCODE, FIRSTCATEGORYTHIRDCODINGDISPLAY); - - CodeJson categoryCodeableConcept2 = new CodeJson(); - categoryCodeableConcept2.setCodeableConceptText(SECONDCATEGORYTEXT); - categoryCodeableConcept2.addCoding(CATEGORYFIRSTCODINGSYSTEM, SECONDCATEGORYFIRSTCODINGCODE, SECONDCATEGORYFIRSTCODINGDISPLAY); - categoryCodeableConcept2.addCoding(CATEGORYSECONDCODINGSYSTEM, SECONDCATEGORYSECONDCODINGCODE, SECONDCATEGORYSECONDCODINGDISPLAY); - categoryCodeableConcept2.addCoding(CATEGORYTHIRDCODINGSYSTEM, SECONDCATEGORYTHIRDCODINGCODE, SECONDCATEGORYTHIRDCODINGDISPLAY); - - CodeJson categoryCodeableConcept3 = new CodeJson(); - categoryCodeableConcept3.setCodeableConceptText(THIRDCATEGORYTEXT); - categoryCodeableConcept3.addCoding(CATEGORYFIRSTCODINGSYSTEM, THIRDCATEGORYFIRSTCODINGCODE, THIRDCATEGORYFIRSTCODINGDISPLAY); - categoryCodeableConcept3.addCoding(CATEGORYSECONDCODINGSYSTEM, THIRDCATEGORYSECONDCODINGCODE, THIRDCATEGORYSECONDCODINGDISPLAY); - categoryCodeableConcept3.addCoding(CATEGORYTHIRDCODINGSYSTEM, THIRDCATEGORYTHIRDCODINGCODE, THIRDCATEGORYTHIRDCODINGDISPLAY); - - return Arrays.asList(categoryCodeableConcept1, categoryCodeableConcept2, categoryCodeableConcept3); - } - - public static List createMultipleObservationJson(List thePatientIds) { - - // CodeableConcept 1 - with 3 codings - String codeableConceptId1 = UUID.randomUUID().toString(); - CodeJson codeJson1 = new CodeJson(); - codeJson1.setCodeableConceptId(codeableConceptId1); - codeJson1.setCodeableConceptText(OBSERVATION_CODE_CONCEPT_TEXT_1); - codeJson1.addCoding(CODEFIRSTCODINGSYSTEM, CODEFIRSTCODINGCODE, CODEFIRSTCODINGDISPLAY); - - // CodeableConcept 2 - with 3 codings - String codeableConceptId2 = UUID.randomUUID().toString(); - CodeJson codeJson2 = new CodeJson(); - codeJson2.setCodeableConceptId(codeableConceptId2); - codeJson2.setCodeableConceptText(OBSERVATION_CODE_CONCEPT_TEXT_2); - codeJson2.addCoding(CODE_SECOND_CODING_SYSTEM, CODE_SECOND_CODING_CODE, CODE_SECOND_CODING_DISPLAY); - - List categoryCodeableConcepts = createCategoryCodeableConcepts(); - // CategoryCodeableConcept 1 - with 3 codings - List categoryConcepts1 = Collections.singletonList(categoryCodeableConcepts.get(0)); - - // CateogryCodeableConcept 2 - with 3 codings - List categoryConcepts2 = Collections.singletonList(categoryCodeableConcepts.get(1)); - - // Pair CodeableConcept 1 + CategoryCodeableConcept 1 for odd numbered observation - // Pair CodeableConcept 2 + CategoryCodeableConcept 2 for even numbered observation - - // For each patient - create 10 observations - return thePatientIds.stream() - .flatMap(patientId -> IntStream.range(0, 10) - .mapToObj(index -> { - ObservationJson observationJson = new ObservationJson(); - String identifier = String.valueOf((index + patientId * 10L)); - observationJson.setIdentifier(identifier); - observationJson.setSubject(String.valueOf(patientId)); - if (index % 2 == 1) { - observationJson.setCategories(categoryConcepts1); - observationJson.setCode(codeJson1); - } else { - observationJson.setCategories(categoryConcepts2); - observationJson.setCode(codeJson2); - } - Date effectiveDtm = new Date(TEST_BASELINE_TIMESTAMP - ((10L - index) * 3600L * 1000L)); - observationJson.setEffectiveDtm(effectiveDtm); - return observationJson; - })) - .collect(Collectors.toList()); - } - -} diff --git a/hapi-fhir-jpaserver-hfql/pom.xml b/hapi-fhir-jpaserver-hfql/pom.xml index 1d71e2ac1e7..736c8753f00 100644 --- a/hapi-fhir-jpaserver-hfql/pom.xml +++ b/hapi-fhir-jpaserver-hfql/pom.xml @@ -3,7 +3,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -20,8 +20,8 @@ - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided diff --git a/hapi-fhir-jpaserver-hfql/src/main/java/ca/uhn/fhir/jpa/fql/jdbc/RemoteHfqlExecutionResult.java b/hapi-fhir-jpaserver-hfql/src/main/java/ca/uhn/fhir/jpa/fql/jdbc/RemoteHfqlExecutionResult.java index 5b2c65b31b7..9fee362d699 100644 --- a/hapi-fhir-jpaserver-hfql/src/main/java/ca/uhn/fhir/jpa/fql/jdbc/RemoteHfqlExecutionResult.java +++ b/hapi-fhir-jpaserver-hfql/src/main/java/ca/uhn/fhir/jpa/fql/jdbc/RemoteHfqlExecutionResult.java @@ -32,6 +32,7 @@ import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.util.IoUtil; import ca.uhn.fhir.util.JsonUtil; import ca.uhn.fhir.util.ValidateUtil; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.lang3.Validate; @@ -56,7 +57,6 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import javax.servlet.http.HttpServletResponse; import static ca.uhn.fhir.jpa.fql.util.HfqlConstants.PROTOCOL_VERSION; import static org.apache.commons.lang3.StringUtils.defaultIfBlank; diff --git a/hapi-fhir-jpaserver-hfql/src/main/java/ca/uhn/fhir/jpa/fql/provider/HfqlRestProvider.java b/hapi-fhir-jpaserver-hfql/src/main/java/ca/uhn/fhir/jpa/fql/provider/HfqlRestProvider.java index adb3d2d8335..805707e3621 100644 --- a/hapi-fhir-jpaserver-hfql/src/main/java/ca/uhn/fhir/jpa/fql/provider/HfqlRestProvider.java +++ b/hapi-fhir-jpaserver-hfql/src/main/java/ca/uhn/fhir/jpa/fql/provider/HfqlRestProvider.java @@ -30,6 +30,8 @@ import ca.uhn.fhir.util.DatatypeUtil; import ca.uhn.fhir.util.JsonUtil; import ca.uhn.fhir.util.ValidateUtil; import ca.uhn.fhir.util.VersionUtil; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.csv.CSVPrinter; import org.hl7.fhir.instance.model.api.IPrimitiveType; import org.springframework.beans.factory.annotation.Autowired; @@ -37,8 +39,6 @@ import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.io.OutputStreamWriter; import javax.annotation.Nullable; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; import static ca.uhn.fhir.jpa.fql.jdbc.HfqlRestClient.CSV_FORMAT; import static ca.uhn.fhir.rest.api.Constants.CHARSET_UTF8_CTSUFFIX; diff --git a/hapi-fhir-jpaserver-ips/pom.xml b/hapi-fhir-jpaserver-ips/pom.xml index 5c28e18021a..2f75ba5a60f 100644 --- a/hapi-fhir-jpaserver-ips/pom.xml +++ b/hapi-fhir-jpaserver-ips/pom.xml @@ -3,7 +3,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -21,8 +21,8 @@ - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided diff --git a/hapi-fhir-jpaserver-ips/src/main/java/ca/uhn/fhir/jpa/ips/api/SectionRegistry.java b/hapi-fhir-jpaserver-ips/src/main/java/ca/uhn/fhir/jpa/ips/api/SectionRegistry.java index a085d1b6ea3..fa16b55e2fc 100644 --- a/hapi-fhir-jpaserver-ips/src/main/java/ca/uhn/fhir/jpa/ips/api/SectionRegistry.java +++ b/hapi-fhir-jpaserver-ips/src/main/java/ca/uhn/fhir/jpa/ips/api/SectionRegistry.java @@ -19,6 +19,7 @@ */ package ca.uhn.fhir.jpa.ips.api; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; @@ -36,7 +37,6 @@ import java.util.Collections; import java.util.List; import java.util.function.Consumer; import javax.annotation.Nullable; -import javax.annotation.PostConstruct; /** * This class is the registry for sections for the IPS document. It can be extended diff --git a/hapi-fhir-jpaserver-mdm/pom.xml b/hapi-fhir-jpaserver-mdm/pom.xml index 2fb8fa175ad..dd2a1fba351 100644 --- a/hapi-fhir-jpaserver-mdm/pom.xml +++ b/hapi-fhir-jpaserver-mdm/pom.xml @@ -6,7 +6,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -61,8 +61,8 @@ test - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api test diff --git a/hapi-fhir-jpaserver-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/broker/MdmQueueConsumerLoader.java b/hapi-fhir-jpaserver-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/broker/MdmQueueConsumerLoader.java index 1acf874d65d..23ca40079fd 100644 --- a/hapi-fhir-jpaserver-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/broker/MdmQueueConsumerLoader.java +++ b/hapi-fhir-jpaserver-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/broker/MdmQueueConsumerLoader.java @@ -26,11 +26,10 @@ import ca.uhn.fhir.jpa.subscription.model.ResourceModifiedJsonMessage; import ca.uhn.fhir.mdm.api.IMdmSettings; import ca.uhn.fhir.mdm.log.Logs; import com.google.common.annotations.VisibleForTesting; +import jakarta.annotation.PreDestroy; import org.slf4j.Logger; import org.springframework.stereotype.Service; -import javax.annotation.PreDestroy; - @Service public class MdmQueueConsumerLoader { private static final Logger ourLog = Logs.getMdmTroubleshootingLog(); diff --git a/hapi-fhir-jpaserver-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/svc/MdmControllerSvcImpl.java b/hapi-fhir-jpaserver-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/svc/MdmControllerSvcImpl.java index 6ea10e08c9f..a9ddf8b322a 100644 --- a/hapi-fhir-jpaserver-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/svc/MdmControllerSvcImpl.java +++ b/hapi-fhir-jpaserver-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/svc/MdmControllerSvcImpl.java @@ -28,6 +28,7 @@ import ca.uhn.fhir.interceptor.api.Pointcut; import ca.uhn.fhir.interceptor.model.ReadPartitionIdRequestDetails; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.batch.models.Batch2JobStartResponse; +import ca.uhn.fhir.jpa.dao.tx.HapiTransactionService; import ca.uhn.fhir.jpa.partition.IRequestPartitionHelperSvc; import ca.uhn.fhir.mdm.api.IGoldenResourceMergerSvc; import ca.uhn.fhir.mdm.api.IMdmControllerSvc; @@ -103,6 +104,9 @@ public class MdmControllerSvcImpl implements IMdmControllerSvc { @Autowired IInterceptorBroadcaster myInterceptorBroadcaster; + @Autowired + private HapiTransactionService myTxService; + public MdmControllerSvcImpl() {} @Override @@ -194,7 +198,9 @@ public class MdmControllerSvcImpl implements IMdmControllerSvc { @Override public List queryLinkHistory( MdmHistorySearchParameters theMdmHistorySearchParameters, RequestDetails theRequestDetails) { - return myMdmLinkQuerySvc.queryLinkHistory(theMdmHistorySearchParameters); + return myTxService + .withRequest(theRequestDetails) + .execute(() -> myMdmLinkQuerySvc.queryLinkHistory(theMdmHistorySearchParameters)); } @Override diff --git a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/dao/MdmMetricSvcJpaIT.java b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/dao/MdmMetricSvcJpaIT.java index 77a186cc549..7953cc7316a 100644 --- a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/dao/MdmMetricSvcJpaIT.java +++ b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/dao/MdmMetricSvcJpaIT.java @@ -19,6 +19,7 @@ import ca.uhn.fhir.mdm.model.MdmMetrics; import ca.uhn.fhir.mdm.util.MdmResourceUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.persistence.EntityManagerFactory; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.BeforeEach; @@ -30,7 +31,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; -import javax.persistence.EntityManagerFactory; import java.util.List; import static org.junit.jupiter.api.Assertions.fail; @@ -78,6 +78,7 @@ public class MdmMetricSvcJpaIT extends BaseMdmR4Test implements IMdmMetricSvcTes @Autowired private IMdmMetricSvc mySvc; + @Override @BeforeEach public void before() throws Exception { super.before(); diff --git a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/helper/BaseMdmHelper.java b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/helper/BaseMdmHelper.java index dd185421e9f..4a4089ef08e 100644 --- a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/helper/BaseMdmHelper.java +++ b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/helper/BaseMdmHelper.java @@ -19,7 +19,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.function.Supplier; import static org.awaitility.Awaitility.await; diff --git a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmSearchExpandingInterceptorIT.java b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmSearchExpandingInterceptorIT.java index 31125dd941c..5b1150bc1ca 100644 --- a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmSearchExpandingInterceptorIT.java +++ b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmSearchExpandingInterceptorIT.java @@ -30,7 +30,7 @@ import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmStorageInterceptorIT.java b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmStorageInterceptorIT.java index f7e8615c22d..953a7574618 100644 --- a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmStorageInterceptorIT.java +++ b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmStorageInterceptorIT.java @@ -172,8 +172,12 @@ public class MdmStorageInterceptorIT extends BaseMdmR4Test { assertLinksMatchResult(MdmMatchResultEnum.MATCH, MdmMatchResultEnum.POSSIBLE_MATCH, MdmMatchResultEnum.POSSIBLE_MATCH); + logAllTokenIndexes(); + // When - myPatientDao.delete(paulPatient.getIdElement()); + myPatientDao.delete(paulPatient.getIdElement(), new SystemRequestDetails()); + + logAllTokenIndexes(); // Then List resources = myPatientDao.search(new SearchParameterMap(), SystemRequestDetails.forAllPartitions()).getAllResources(); diff --git a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/BaseProviderR4Test.java b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/BaseProviderR4Test.java index 5fa7ce7d19d..8b46fe10d87 100644 --- a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/BaseProviderR4Test.java +++ b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/BaseProviderR4Test.java @@ -54,8 +54,10 @@ public abstract class BaseProviderR4Test extends BaseMdmR4Test { myMdmResourceMatcherSvc.setMdmRulesJson(myMdmSettings.getMdmRules()); } + @Override @BeforeEach public void before() throws Exception { + super.before(); myMdmProvider = new MdmProviderDstu3Plus(myFhirContext, myMdmControllerSvc, myMdmHelper, diff --git a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/MdmOperationPointcutsIT.java b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/MdmOperationPointcutsIT.java index e9f69df9592..76d6b6d065f 100644 --- a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/MdmOperationPointcutsIT.java +++ b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/MdmOperationPointcutsIT.java @@ -7,6 +7,7 @@ import ca.uhn.fhir.interceptor.api.IInterceptorService; import ca.uhn.fhir.interceptor.api.Pointcut; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.batch.models.Batch2JobStartResponse; +import ca.uhn.fhir.jpa.dao.expunge.ExpungeEverythingService; import ca.uhn.fhir.jpa.entity.MdmLink; import ca.uhn.fhir.jpa.mdm.helper.MdmLinkHelper; import ca.uhn.fhir.jpa.mdm.helper.testmodels.MDMState; @@ -14,6 +15,7 @@ import ca.uhn.fhir.jpa.model.dao.JpaPid; import ca.uhn.fhir.mdm.api.IMdmSubmitSvc; import ca.uhn.fhir.mdm.api.MdmLinkSourceEnum; import ca.uhn.fhir.mdm.api.MdmMatchResultEnum; +import ca.uhn.fhir.mdm.interceptor.MdmStorageInterceptor; import ca.uhn.fhir.mdm.model.mdmevents.MdmClearEvent; import ca.uhn.fhir.mdm.model.mdmevents.MdmHistoryEvent; import ca.uhn.fhir.mdm.model.mdmevents.MdmLinkEvent; @@ -119,10 +121,18 @@ public class MdmOperationPointcutsIT extends BaseProviderR4Test { @SpyBean private IMdmSubmitSvc myMdmSubmitSvc; + private MdmLinkHistoryProviderDstu3Plus myLinkHistoryProvider; private final List myInterceptors = new ArrayList<>(); + @Override + @AfterEach + public void afterPurgeDatabase() { + super.afterPurgeDatabase(); + } + + @Override @BeforeEach public void before() throws Exception { super.before(); @@ -134,6 +144,7 @@ public class MdmOperationPointcutsIT extends BaseProviderR4Test { ); } + @Override @AfterEach public void after() throws IOException { super.after(); @@ -141,8 +152,6 @@ public class MdmOperationPointcutsIT extends BaseProviderR4Test { myInterceptors.clear(); } - @Nested - class MdmProviderDstu3PlusTest { @Test public void mergeGoldenResources_withInterceptor_firesHook() { // setup @@ -521,7 +530,7 @@ public class MdmOperationPointcutsIT extends BaseProviderR4Test { } } } - } + private String createUrl(String theResourceType, StringType theCriteria) { String url = theResourceType; @@ -531,8 +540,6 @@ public class MdmOperationPointcutsIT extends BaseProviderR4Test { return url; } - @Nested - class MdmLinkHistoryProviderDstu3PlusTest { @ParameterizedTest @EnumSource(LinkHistoryParameters.class) @@ -597,6 +604,6 @@ public class MdmOperationPointcutsIT extends BaseProviderR4Test { assertTrue(called.get()); assertFalse(retval.isEmpty()); } - } + } diff --git a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/MdmProviderCrossPartitionR4Test.java b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/MdmProviderCrossPartitionR4Test.java index 8a899634fda..90001543085 100644 --- a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/MdmProviderCrossPartitionR4Test.java +++ b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/provider/MdmProviderCrossPartitionR4Test.java @@ -37,7 +37,8 @@ public class MdmProviderCrossPartitionR4Test extends BaseProviderR4Test{ private static final String PARTITION_GOLDEN_RESOURCE = "PARTITION-GOLDEN"; - @BeforeEach + @Override + @BeforeEach public void before() throws Exception { super.before(); diff --git a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/svc/MdmMatchLinkSvcTest.java b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/svc/MdmMatchLinkSvcTest.java index 967ccf4969c..57b19c41294 100644 --- a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/svc/MdmMatchLinkSvcTest.java +++ b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/jpa/mdm/svc/MdmMatchLinkSvcTest.java @@ -119,7 +119,6 @@ public class MdmMatchLinkSvcTest { assertLinksMatchVector((Long) null); } - @Test @RepeatedTest(20) public void testUpdatingAResourceToMatchACurrentlyUnmatchedResource_resultsInUpdatedLinksForBoth() { // setup diff --git a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/mdm/batch2/clear/MdmLinkSlowDeletionSandboxIT.java b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/mdm/batch2/clear/MdmLinkSlowDeletionSandboxIT.java index da5734f574a..5cba1958901 100644 --- a/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/mdm/batch2/clear/MdmLinkSlowDeletionSandboxIT.java +++ b/hapi-fhir-jpaserver-mdm/src/test/java/ca/uhn/fhir/mdm/batch2/clear/MdmLinkSlowDeletionSandboxIT.java @@ -9,7 +9,7 @@ import ca.uhn.fhir.mdm.api.MdmMatchResultEnum; import ca.uhn.fhir.rest.api.server.SystemRequestDetails; import ca.uhn.fhir.util.StopWatch; import org.apache.commons.dbcp2.BasicDataSource; -import org.hibernate.dialect.PostgreSQL9Dialect; +import org.hibernate.dialect.PostgreSQLDialect; import org.hl7.fhir.r4.model.Coding; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.Disabled; @@ -115,9 +115,7 @@ public class MdmLinkSlowDeletionSandboxIT extends BaseJpaR4Test { @Override public String getHibernateDialect() { - return PostgreSQL9Dialect.class.getName(); - -// return Oracle12cDialect.class.getName(); + return PostgreSQLDialect.class.getName(); } @Override diff --git a/hapi-fhir-jpaserver-model/pom.xml b/hapi-fhir-jpaserver-model/pom.xml index e161b491e6b..8860e76228d 100644 --- a/hapi-fhir-jpaserver-model/pom.xml +++ b/hapi-fhir-jpaserver-model/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -81,19 +81,19 @@ ${project.version} - org.hibernate + org.hibernate.orm hibernate-core org.hibernate.search - hibernate-search-mapper-orm + hibernate-search-mapper-orm-orm6 org.hibernate.search hibernate-search-backend-elasticsearch - org.hibernate + org.hibernate.orm hibernate-envers diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirCockroachDialect.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirCockroachDialect.java new file mode 100644 index 00000000000..e38ff5d7878 --- /dev/null +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirCockroachDialect.java @@ -0,0 +1,42 @@ +/*- + * #%L + * HAPI FHIR JPA Model + * %% + * Copyright (C) 2014 - 2023 Smile CDR, Inc. + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package ca.uhn.fhir.jpa.model.dialect; + +import org.hibernate.dialect.CockroachDialect; +import org.hibernate.dialect.DatabaseVersion; + +/** + * Dialect for CockroachDB database. + * Minimum version: 21.1 + */ +public class HapiFhirCockroachDialect extends CockroachDialect { + + public HapiFhirCockroachDialect() { + super(DatabaseVersion.make(21, 1)); + } + + /** + * @see HapiFhirH2Dialect#supportsColumnCheck() for an explanation of why we disable this + */ + @Override + public boolean supportsColumnCheck() { + return false; + } +} diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirDerbyDialect.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirDerbyDialect.java new file mode 100644 index 00000000000..b4e8f589f30 --- /dev/null +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirDerbyDialect.java @@ -0,0 +1,42 @@ +/*- + * #%L + * HAPI FHIR JPA Model + * %% + * Copyright (C) 2014 - 2023 Smile CDR, Inc. + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package ca.uhn.fhir.jpa.model.dialect; + +import org.hibernate.dialect.DatabaseVersion; +import org.hibernate.dialect.DerbyDialect; + +/** + * Dialect for Oracle database. + * Minimum version: 10.14.2 + */ +public class HapiFhirDerbyDialect extends DerbyDialect { + + public HapiFhirDerbyDialect() { + super(DatabaseVersion.make(10, 14, 2)); + } + + /** + * @see HapiFhirH2Dialect#supportsColumnCheck() for an explanation of why we disable this + */ + @Override + public boolean supportsColumnCheck() { + return false; + } +} diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirH2Dialect.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirH2Dialect.java index 074bf229726..5cdf1eaad26 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirH2Dialect.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirH2Dialect.java @@ -19,12 +19,13 @@ */ package ca.uhn.fhir.jpa.model.dialect; +import ca.uhn.fhir.jpa.model.entity.ResourceTable; +import org.hibernate.dialect.DatabaseVersion; import org.hibernate.dialect.H2Dialect; -import java.sql.Types; - /** - * HAPI FHIR dialect for H2 database + * Dialect for H2 database. + * Minimum version: 2.2.220 */ public class HapiFhirH2Dialect extends H2Dialect { @@ -32,25 +33,33 @@ public class HapiFhirH2Dialect extends H2Dialect { * Constructor */ public HapiFhirH2Dialect() { - super(); - - /* - * These mappings are already defined in the super() constructor, but they - * will only happen if the dialect can connect to the database and - * determine that it's a recent enough version of H2 to support this. This - * means that the Maven plugin that does schema generation doesn't add it. - * So this dialect forces the use of the right defs. - */ - registerColumnType(Types.LONGVARCHAR, "character varying"); - registerColumnType(Types.BINARY, "binary($l)"); + super(DatabaseVersion.make(2, 2, 220)); } /** - * Workaround until this bug is fixed: - * https://hibernate.atlassian.net/browse/HHH-15002 + * As of Hibernate 6, generated schemas include a column level check constraint that enforces valid values + * for columns that back an Enum type. For example, the column definition for {@link ResourceTable#getFhirVersion()} + * would look like: + *
    +	 *  RES_VERSION varchar(7) check (RES_VERSION in ('DSTU2','DSTU2_HL7ORG','DSTU2_1','DSTU3','R4','R4B','R5')),
    +	 * 
    + *

    + * This is a nice addition since it enforces the values that the Enum allows, but it's problematic for us because these + * constraints are invisible to the JDBC metadata API on most databases, which means that our schema migration + * checker isn't able to catch problems if we add a value to an Enum and don't add a corresponding database + * migration. Rather than risk having inconsistent behaviour between annotated and migrated schemas, we just + * disable these checks on all of our dialects. + *

    + * See this discussion from the author of SchemaCrawler discussing this limitation: + * https://stackoverflow.com/questions/63346650/schemacrawler-java-api-retrieve-check-column-constraints. + * With this change in place, the definition above becomes simply: + *

    +	 *  RES_VERSION varchar(7),
    +	 * 
    + *

    */ @Override - public String toBooleanValueString(boolean bool) { - return bool ? "true" : "false"; + public boolean supportsColumnCheck() { + return false; } } diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirMariaDBDialect.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirMariaDBDialect.java new file mode 100644 index 00000000000..0a121b8f3f5 --- /dev/null +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirMariaDBDialect.java @@ -0,0 +1,42 @@ +/*- + * #%L + * HAPI FHIR JPA Model + * %% + * Copyright (C) 2014 - 2023 Smile CDR, Inc. + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package ca.uhn.fhir.jpa.model.dialect; + +import org.hibernate.dialect.DatabaseVersion; +import org.hibernate.dialect.MariaDBDialect; + +/** + * Dialect for MySQL database. + * Minimum version: 10.11.5 + */ +public class HapiFhirMariaDBDialect extends MariaDBDialect { + + public HapiFhirMariaDBDialect() { + super(DatabaseVersion.make(10, 11, 5)); + } + + /** + * @see HapiFhirH2Dialect#supportsColumnCheck() for an explanation of why we disable this + */ + @Override + public boolean supportsColumnCheck() { + return false; + } +} diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirMySQLDialect.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirMySQLDialect.java new file mode 100644 index 00000000000..8bdbf26ba4c --- /dev/null +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirMySQLDialect.java @@ -0,0 +1,42 @@ +/*- + * #%L + * HAPI FHIR JPA Model + * %% + * Copyright (C) 2014 - 2023 Smile CDR, Inc. + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package ca.uhn.fhir.jpa.model.dialect; + +import org.hibernate.dialect.DatabaseVersion; +import org.hibernate.dialect.MySQLDialect; + +/** + * Dialect for MySQL database. + * Minimum version: 5.7 + */ +public class HapiFhirMySQLDialect extends MySQLDialect { + + public HapiFhirMySQLDialect() { + super(DatabaseVersion.make(5, 7)); + } + + /** + * @see HapiFhirH2Dialect#supportsColumnCheck() for an explanation of why we disable this + */ + @Override + public boolean supportsColumnCheck() { + return false; + } +} diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirOracleDialect.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirOracleDialect.java new file mode 100644 index 00000000000..ec1095e3765 --- /dev/null +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirOracleDialect.java @@ -0,0 +1,42 @@ +/*- + * #%L + * HAPI FHIR JPA Model + * %% + * Copyright (C) 2014 - 2023 Smile CDR, Inc. + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package ca.uhn.fhir.jpa.model.dialect; + +import org.hibernate.dialect.DatabaseVersion; +import org.hibernate.dialect.OracleDialect; + +/** + * Dialect for Oracle database. + * Minimum version: 12.2 (Oracle 12c R2) + */ +public class HapiFhirOracleDialect extends OracleDialect { + + public HapiFhirOracleDialect() { + super(DatabaseVersion.make(12, 2)); + } + + /** + * @see HapiFhirH2Dialect#supportsColumnCheck() for an explanation of why we disable this + */ + @Override + public boolean supportsColumnCheck() { + return false; + } +} diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirPostgres94Dialect.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirPostgres94Dialect.java index 57f42b5322a..da3a48025ad 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirPostgres94Dialect.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirPostgres94Dialect.java @@ -19,17 +19,21 @@ */ package ca.uhn.fhir.jpa.model.dialect; -import org.hibernate.dialect.PostgreSQL94Dialect; - -import java.sql.Types; +import org.hibernate.dialect.PostgreSQLDialect; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * This dialect is recommended when using HAPI FHIR JPA on Postgresql database. + * + * @deprecated Use {@link HapiFhirPostgresDialect} instead */ -public class HapiFhirPostgres94Dialect extends PostgreSQL94Dialect { +public class HapiFhirPostgres94Dialect extends PostgreSQLDialect { + private static final Logger ourLog = LoggerFactory.getLogger(HapiFhirPostgres94Dialect.class); public HapiFhirPostgres94Dialect() { super(); - registerColumnType(Types.CLOB, "oid"); + ourLog.warn("The " + getClass() + " dialect is deprecated and will be removed in a future release. Use " + + HapiFhirPostgresDialect.class.getName() + " instead"); } } diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirPostgresDialect.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirPostgresDialect.java new file mode 100644 index 00000000000..c0a3435b7a1 --- /dev/null +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirPostgresDialect.java @@ -0,0 +1,38 @@ +/*- + * #%L + * HAPI FHIR JPA Model + * %% + * Copyright (C) 2014 - 2023 Smile CDR, Inc. + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package ca.uhn.fhir.jpa.model.dialect; + +import org.hibernate.dialect.DatabaseVersion; +import org.hibernate.dialect.PostgreSQLDialect; + +public class HapiFhirPostgresDialect extends PostgreSQLDialect { + + public HapiFhirPostgresDialect() { + super(DatabaseVersion.make(10, 0, 0)); + } + + /** + * @see HapiFhirH2Dialect#supportsColumnCheck() for an explanation of why we disable this + */ + @Override + public boolean supportsColumnCheck() { + return false; + } +} diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirSQLServerDialect.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirSQLServerDialect.java new file mode 100644 index 00000000000..606d91b4dea --- /dev/null +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiFhirSQLServerDialect.java @@ -0,0 +1,42 @@ +/*- + * #%L + * HAPI FHIR JPA Model + * %% + * Copyright (C) 2014 - 2023 Smile CDR, Inc. + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package ca.uhn.fhir.jpa.model.dialect; + +import org.hibernate.dialect.DatabaseVersion; +import org.hibernate.dialect.SQLServerDialect; + +/** + * Dialect for MS SQL Server database. + * Minimum version: 12.0 (SQL Server 2014 and Azure SQL Database) + */ +public class HapiFhirSQLServerDialect extends SQLServerDialect { + + public HapiFhirSQLServerDialect() { + super(DatabaseVersion.make(11)); + } + + /** + * @see HapiFhirH2Dialect#supportsColumnCheck() for an explanation of why we disable this + */ + @Override + public boolean supportsColumnCheck() { + return false; + } +} diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiSequenceStyleGenerator.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiSequenceStyleGenerator.java index 9e373c05e5d..cbdaa8a8aac 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiSequenceStyleGenerator.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/dialect/HapiSequenceStyleGenerator.java @@ -20,16 +20,19 @@ package ca.uhn.fhir.jpa.model.dialect; import ca.uhn.fhir.jpa.model.entity.StorageSettings; -import ca.uhn.fhir.util.ReflectionUtil; +import ca.uhn.fhir.jpa.util.ISequenceValueMassager; import org.apache.commons.lang3.Validate; import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.boot.model.relational.Database; +import org.hibernate.boot.model.relational.ExportableProducer; import org.hibernate.boot.model.relational.SqlStringGenerationContext; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.id.BulkInsertionCapableIdentifierGenerator; import org.hibernate.id.IdentifierGenerator; +import org.hibernate.id.OptimizableGenerator; import org.hibernate.id.PersistentIdentifierGenerator; +import org.hibernate.id.enhanced.Optimizer; import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.id.enhanced.StandardOptimizerDescriptor; import org.hibernate.service.ServiceRegistry; @@ -45,7 +48,8 @@ import java.util.Properties; */ @SuppressWarnings("unused") public class HapiSequenceStyleGenerator - implements IdentifierGenerator, PersistentIdentifierGenerator, BulkInsertionCapableIdentifierGenerator { + implements PersistentIdentifierGenerator, BulkInsertionCapableIdentifierGenerator, ExportableProducer { + public static final String ID_MASSAGER_TYPE_KEY = "hapi_fhir.sequence_generator_massager"; private final SequenceStyleGenerator myGen = new SequenceStyleGenerator(); @Autowired @@ -68,7 +72,7 @@ public class HapiSequenceStyleGenerator @Override public Serializable generate(SharedSessionContractImplementor theSession, Object theObject) throws HibernateException { - Long retVal = myIdMassager.generate(myGeneratorName); + Long retVal = myIdMassager != null ? myIdMassager.generate(myGeneratorName) : null; if (retVal == null) { Long next = (Long) myGen.generate(theSession, theObject); retVal = myIdMassager.massage(myGeneratorName, next); @@ -80,10 +84,9 @@ public class HapiSequenceStyleGenerator public void configure(Type theType, Properties theParams, ServiceRegistry theServiceRegistry) throws MappingException { - // Instantiate the ID massager - // StorageSettings should only be null when running in the DDL generation maven plugin - if (myStorageSettings != null) { - myIdMassager = ReflectionUtil.newInstance(myStorageSettings.getSequenceValueMassagerClass()); + myIdMassager = theServiceRegistry.getService(ISequenceValueMassager.class); + if (myIdMassager == null) { + myIdMassager = new ISequenceValueMassager.NoopSequenceValueMassager(); } // Create a HAPI FHIR sequence style generator @@ -91,9 +94,10 @@ public class HapiSequenceStyleGenerator Validate.notBlank(myGeneratorName, "No generator name found"); Properties props = new Properties(theParams); - props.put(SequenceStyleGenerator.OPT_PARAM, StandardOptimizerDescriptor.POOLED.getExternalName()); - props.put(SequenceStyleGenerator.INITIAL_PARAM, "1"); - props.put(SequenceStyleGenerator.INCREMENT_PARAM, "50"); + props.put(OptimizableGenerator.OPT_PARAM, StandardOptimizerDescriptor.POOLED.getExternalName()); + props.put(OptimizableGenerator.INITIAL_PARAM, "1"); + props.put(OptimizableGenerator.INCREMENT_PARAM, "50"); + props.put(GENERATOR_NAME, myGeneratorName); myGen.configure(theType, props, theServiceRegistry); @@ -114,4 +118,9 @@ public class HapiSequenceStyleGenerator public boolean supportsJdbcBatchInserts() { return myGen.supportsJdbcBatchInserts(); } + + @Override + public Optimizer getOptimizer() { + return myGen.getOptimizer(); + } } diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/AuditableBasePartitionable.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/AuditableBasePartitionable.java index 473235d6e8d..8601fba3c21 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/AuditableBasePartitionable.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/AuditableBasePartitionable.java @@ -20,14 +20,14 @@ package ca.uhn.fhir.jpa.model.entity; * #L% */ +import jakarta.persistence.Column; +import jakarta.persistence.Embedded; +import jakarta.persistence.MappedSuperclass; import org.hibernate.envers.Audited; import org.hibernate.envers.NotAudited; import java.io.Serializable; import javax.annotation.Nullable; -import javax.persistence.Column; -import javax.persistence.Embedded; -import javax.persistence.MappedSuperclass; /** * This is a copy of (@link {@link BasePartitionable} used ONLY for entities that are audited by Hibernate Envers. diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseHasResource.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseHasResource.java index 245abc493d9..646742cac02 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseHasResource.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseHasResource.java @@ -23,17 +23,17 @@ import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.jpa.model.cross.IBasePersistedResource; import ca.uhn.fhir.jpa.model.dao.JpaPid; import ca.uhn.fhir.model.primitive.InstantDt; +import jakarta.persistence.Column; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.Transient; import org.hibernate.annotations.OptimisticLock; import java.util.Collection; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.MappedSuperclass; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; @MappedSuperclass public abstract class BaseHasResource extends BasePartitionable diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BasePartitionable.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BasePartitionable.java index 0c3fe7ceed0..60f1d7962e5 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BasePartitionable.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BasePartitionable.java @@ -19,11 +19,12 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Embedded; +import jakarta.persistence.MappedSuperclass; + import java.io.Serializable; import javax.annotation.Nullable; -import javax.persistence.Column; -import javax.persistence.Embedded; -import javax.persistence.MappedSuperclass; /** * This is the base class for entities with partitioning that does NOT include Hibernate Envers logging. diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndex.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndex.java index 9107f06862a..54a99aa9ccb 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndex.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndex.java @@ -19,10 +19,10 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.MappedSuperclass; import org.apache.commons.lang3.ObjectUtils; import java.io.Serializable; -import javax.persistence.MappedSuperclass; @MappedSuperclass public abstract class BaseResourceIndex extends BasePartitionable implements Serializable { diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndexedSearchParam.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndexedSearchParam.java index bdb31c75c8d..edcd363081a 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndexedSearchParam.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndexedSearchParam.java @@ -31,17 +31,17 @@ import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.Transient; import org.apache.commons.lang3.StringUtils; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.GenericField; import java.util.Date; import java.util.List; -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; @MappedSuperclass public abstract class BaseResourceIndexedSearchParam extends BaseResourceIndex { diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndexedSearchParamQuantity.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndexedSearchParamQuantity.java index ac1d27332b0..3850a31c010 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndexedSearchParamQuantity.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseResourceIndexedSearchParamQuantity.java @@ -21,12 +21,11 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.model.config.PartitionSettings; +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField; -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; - @MappedSuperclass public abstract class BaseResourceIndexedSearchParamQuantity extends BaseResourceIndexedSearchParam { diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseTag.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseTag.java index bc4405d2d1a..27db242c506 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseTag.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BaseTag.java @@ -19,11 +19,12 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.Column; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.MappedSuperclass; + import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.MappedSuperclass; @MappedSuperclass public abstract class BaseTag extends BasePartitionable implements Serializable { diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BinaryStorageEntity.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BinaryStorageEntity.java index d44d8e446f5..f2f9742b607 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BinaryStorageEntity.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/BinaryStorageEntity.java @@ -19,15 +19,16 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Lob; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; + import java.sql.Blob; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; @Entity @Table(name = "HFJ_BINARY_STORAGE_BLOB") diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ForcedId.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ForcedId.java index c0aab1eb5b7..c77c5bf87ba 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ForcedId.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ForcedId.java @@ -19,24 +19,23 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.hibernate.annotations.ColumnDefault; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; - @Entity() @Table( name = ForcedId.HFJ_FORCED_ID, @@ -44,6 +43,7 @@ import javax.persistence.UniqueConstraint; @UniqueConstraint( name = "IDX_FORCEDID_RESID", columnNames = {"RESOURCE_PID"}), + /* * This index is called IDX_FORCEDID_TYPE_FID and guarantees * uniqueness of RESOURCE_TYPE,FORCED_ID. This doesn't make sense diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageEntity.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageEntity.java index 0c637ff84d5..acc24f6db0f 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageEntity.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageEntity.java @@ -19,23 +19,23 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.UniqueConstraint; +import jakarta.persistence.Version; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.Date; import java.util.List; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.UniqueConstraint; -import javax.persistence.Version; @Entity() @Table( diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageVersionEntity.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageVersionEntity.java index 00eee555884..a102576c0f9 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageVersionEntity.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageVersionEntity.java @@ -21,29 +21,28 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.util.StringUtil; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.Version; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.util.Date; import java.util.List; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Version; @Entity() @Table( @@ -77,7 +76,7 @@ public class NpmPackageVersionEntity { @JoinColumn(name = "PACKAGE_PID", nullable = false, foreignKey = @ForeignKey(name = "FK_NPM_PKV_PKG")) private NpmPackageEntity myPackage; - @OneToOne + @ManyToOne @JoinColumn( name = "BINARY_RES_ID", referencedColumnName = "RES_ID", diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageVersionResourceEntity.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageVersionResourceEntity.java index d9d9f0d8b5a..04428a7ceda 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageVersionResourceEntity.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/NpmPackageVersionResourceEntity.java @@ -20,32 +20,30 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.context.FhirVersionEnum; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.Version; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Version; @Entity() @Table( name = "NPM_PACKAGE_VER_RES", - uniqueConstraints = {}, indexes = { @Index(name = "IDX_PACKVERRES_URL", columnList = "CANONICAL_URL"), @Index(name = "FK_NPM_PACKVERRES_PACKVER", columnList = "PACKVER_PID"), @@ -67,7 +65,7 @@ public class NpmPackageVersionResourceEntity { nullable = false) private NpmPackageVersionEntity myPackageVersion; - @OneToOne + @ManyToOne @JoinColumn( name = "BINARY_RES_ID", referencedColumnName = "RES_ID", diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/PartitionablePartitionId.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/PartitionablePartitionId.java index 30c8660c1f7..e1a9026e9f7 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/PartitionablePartitionId.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/PartitionablePartitionId.java @@ -21,14 +21,14 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.model.config.PartitionSettings; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.time.LocalDate; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.persistence.Column; -import javax.persistence.Embeddable; @Embeddable public class PartitionablePartitionId implements Cloneable { diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/PersistedResourceModifiedMessageEntityPK.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/PersistedResourceModifiedMessageEntityPK.java index 4cf7fa42516..a0fbf87d22a 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/PersistedResourceModifiedMessageEntityPK.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/PersistedResourceModifiedMessageEntityPK.java @@ -20,10 +20,11 @@ package ca.uhn.fhir.jpa.model.entity; * #L% */ +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; + import java.io.Serializable; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Embeddable; @Embeddable public class PersistedResourceModifiedMessageEntityPK implements IPersistedResourceModifiedMessagePK, Serializable { diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryProvenanceEntity.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryProvenanceEntity.java index 754ab9b613c..66fd55a9a85 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryProvenanceEntity.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryProvenanceEntity.java @@ -20,21 +20,20 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.rest.api.Constants; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.MapsId; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.MapsId; -import javax.persistence.OneToOne; -import javax.persistence.Table; - import static ca.uhn.fhir.jpa.model.entity.ResourceHistoryTable.SOURCE_URI_LENGTH; @Table( diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryTable.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryTable.java index ce53e3bb841..7e951765439 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryTable.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryTable.java @@ -20,17 +20,18 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.jpa.model.dao.JpaPid; -import ca.uhn.fhir.jpa.model.util.JpaConstants; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.rest.api.Constants; +import jakarta.persistence.*; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; +import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.annotations.OptimisticLock; +import org.hibernate.type.SqlTypes; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; -import javax.persistence.*; @Entity @Table( @@ -91,7 +92,7 @@ public class ResourceHistoryTable extends BaseHasResource implements Serializabl private byte[] myResource; @Column(name = "RES_TEXT_VC", length = RES_TEXT_VC_MAX_LENGTH, nullable = true) - @org.hibernate.annotations.Type(type = JpaConstants.ORG_HIBERNATE_TYPE_TEXT_TYPE) + @JdbcTypeCode(SqlTypes.LONG32VARCHAR) @OptimisticLock(excluded = true) private String myResourceTextVc; diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryTag.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryTag.java index 21eb200e8aa..d77cf7c5538 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryTag.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceHistoryTag.java @@ -19,20 +19,21 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.Entity; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; + import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.Entity; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; @Embeddable @Entity diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedComboStringUnique.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedComboStringUnique.java index 1b386c23afb..898efaba2bc 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedComboStringUnique.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedComboStringUnique.java @@ -19,6 +19,7 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.*; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; @@ -27,8 +28,6 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.hl7.fhir.instance.model.api.IIdType; -import javax.persistence.*; - @Entity() @Table( name = "HFJ_IDX_CMP_STRING_UNIQ", diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedComboTokenNonUnique.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedComboTokenNonUnique.java index d4f96c2f7d0..75d6947c870 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedComboTokenNonUnique.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedComboTokenNonUnique.java @@ -21,25 +21,24 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.model.config.PartitionSettings; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.hl7.fhir.instance.model.api.IIdType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Transient; - import static ca.uhn.fhir.jpa.model.entity.BaseResourceIndexedSearchParam.hash; @Entity diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamCoords.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamCoords.java index dbad03ccc81..505b36de92e 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamCoords.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamCoords.java @@ -21,25 +21,24 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.jpa.model.config.PartitionSettings; import ca.uhn.fhir.model.api.IQueryParameterType; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - @Embeddable @Entity @Table( diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamDate.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamDate.java index 01fcab6f275..4afac4201df 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamDate.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamDate.java @@ -26,6 +26,22 @@ import ca.uhn.fhir.model.primitive.InstantDt; import ca.uhn.fhir.rest.param.DateParam; import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.util.DateUtils; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.Transient; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; @@ -37,22 +53,6 @@ import org.hl7.fhir.r4.model.DateTimeType; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; @Embeddable @Entity diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamNumber.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamNumber.java index e98508339ce..60c327ab767 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamNumber.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamNumber.java @@ -22,27 +22,29 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.jpa.model.config.PartitionSettings; import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.rest.param.NumberParam; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; +import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ScaledNumberField; +import org.hibernate.type.SqlTypes; import java.math.BigDecimal; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; @Embeddable @Entity @@ -57,8 +59,9 @@ public class ResourceIndexedSearchParamNumber extends BaseResourceIndexedSearchP private static final long serialVersionUID = 1L; - @Column(name = "SP_VALUE", nullable = true) + @Column(name = "SP_VALUE", nullable = true, precision = 19, scale = 2) @ScaledNumberField + @JdbcTypeCode(SqlTypes.DECIMAL) public BigDecimal myValue; @Id diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamQuantity.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamQuantity.java index 80841720449..7b988a19224 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamQuantity.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamQuantity.java @@ -22,6 +22,19 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.jpa.model.config.PartitionSettings; import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.rest.param.QuantityParam; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -29,19 +42,6 @@ import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ScaledNumb import java.math.BigDecimal; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamQuantityNormalized.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamQuantityNormalized.java index 2a7ca219558..7ba74219b4f 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamQuantityNormalized.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamQuantityNormalized.java @@ -23,6 +23,19 @@ import ca.uhn.fhir.jpa.model.config.PartitionSettings; import ca.uhn.fhir.jpa.model.util.UcumServiceUtil; import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.rest.param.QuantityParam; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -31,19 +44,6 @@ import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ScaledNumb import java.math.BigDecimal; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamString.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamString.java index 870c367a418..b5320e48cb0 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamString.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamString.java @@ -25,24 +25,23 @@ import ca.uhn.fhir.jpa.model.config.PartitionSettings; import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.util.StringUtil; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.Entity; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.Entity; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - import static org.apache.commons.lang3.StringUtils.defaultString; // @formatter:off diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamToken.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamToken.java index 098f167a909..d8c44831239 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamToken.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamToken.java @@ -24,6 +24,20 @@ import ca.uhn.fhir.jpa.model.config.PartitionSettings; import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.param.TokenParam; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.PrePersist; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; @@ -31,21 +45,6 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField; -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.PrePersist; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - import static org.apache.commons.lang3.StringUtils.defaultString; import static org.apache.commons.lang3.StringUtils.trim; @@ -299,6 +298,7 @@ public class ResourceIndexedSearchParamToken extends BaseResourceIndexedSearchPa @Override public String toString() { ToStringBuilder b = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE); + b.append("id", getId()); if (getPartitionId() != null) { b.append("partitionId", getPartitionId().getPartitionId()); } @@ -424,11 +424,11 @@ public class ResourceIndexedSearchParamToken extends BaseResourceIndexedSearchPa return this; } - @PrePersist /** * We truncate the fields at the last moment because the tables have limited size. * We don't truncate earlier in the flow because the index hashes MUST be calculated on the full string. */ + @PrePersist public void truncateFieldsForDB() { mySystem = StringUtils.truncate(mySystem, MAX_LENGTH); myValue = StringUtils.truncate(myValue, MAX_LENGTH); diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamUri.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamUri.java index f2a2d8fe33c..aac0e778d12 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamUri.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceIndexedSearchParamUri.java @@ -23,26 +23,25 @@ import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.model.config.PartitionSettings; import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.rest.param.UriParam; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField; -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - import static org.apache.commons.lang3.StringUtils.defaultString; @Embeddable diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceLink.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceLink.java index 8877dd90dbb..24ced82e9c4 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceLink.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceLink.java @@ -19,6 +19,21 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.Transient; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; @@ -27,21 +42,6 @@ import org.hl7.fhir.instance.model.api.IIdType; import java.util.Date; import javax.annotation.Nullable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; @Entity @Table( diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceModifiedEntity.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceModifiedEntity.java index 11ec35ff436..c7529a45270 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceModifiedEntity.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceModifiedEntity.java @@ -20,14 +20,15 @@ package ca.uhn.fhir.jpa.model.entity; * #L% */ +import jakarta.persistence.Column; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; + import java.io.Serializable; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; /** * This class describes how a resourceModifiedMessage is stored for later processing in the event where diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceSearchUrlEntity.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceSearchUrlEntity.java index 681d20222f8..33b99846d2f 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceSearchUrlEntity.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceSearchUrlEntity.java @@ -19,14 +19,15 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; + import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; @Entity @Table( diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceTable.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceTable.java index bf1ca3b56ac..f51159ec306 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceTable.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceTable.java @@ -28,6 +28,24 @@ import ca.uhn.fhir.jpa.model.search.SearchParamTextPropertyBinder; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.rest.api.Constants; import com.google.common.annotations.VisibleForTesting; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.NamedEntityGraph; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OneToOne; +import jakarta.persistence.PostPersist; +import jakarta.persistence.PrePersist; +import jakarta.persistence.PreUpdate; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.UniqueConstraint; +import jakarta.persistence.Version; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.hibernate.Session; @@ -57,24 +75,6 @@ import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.NamedEntityGraph; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.PostPersist; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.UniqueConstraint; -import javax.persistence.Version; import static ca.uhn.fhir.jpa.model.entity.ResourceTable.IDX_RES_TYPE_FHIR_ID; @@ -148,7 +148,7 @@ public class ResourceTable extends BaseHasResource implements Serializable, IBas private boolean myHasLinks; @Id - @GenericGenerator(name = "SEQ_RESOURCE_ID", strategy = "ca.uhn.fhir.jpa.model.dialect.HapiSequenceStyleGenerator") + @GenericGenerator(name = "SEQ_RESOURCE_ID", type = ca.uhn.fhir.jpa.model.dialect.HapiSequenceStyleGenerator.class) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_RESOURCE_ID") @Column(name = "RES_ID") @GenericField(projectable = Projectable.YES) diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceTag.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceTag.java index ba7f24a91ae..6c50caca82c 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceTag.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/ResourceTag.java @@ -19,25 +19,24 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; - @Entity @Table( name = "HFJ_RES_TAG", diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/SearchParamPresentEntity.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/SearchParamPresentEntity.java index b4ceebd9235..cd23d54ffe1 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/SearchParamPresentEntity.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/SearchParamPresentEntity.java @@ -21,6 +21,7 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.model.config.PartitionSettings; +import jakarta.persistence.*; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; @@ -28,7 +29,6 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.io.Serializable; -import javax.persistence.*; @Entity @Table( diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/StorageSettings.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/StorageSettings.java index cf543b41520..fcb5c355d0e 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/StorageSettings.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/StorageSettings.java @@ -21,7 +21,7 @@ package ca.uhn.fhir.jpa.model.entity; import ca.uhn.fhir.context.ParserOptions; import ca.uhn.fhir.i18n.Msg; -import ca.uhn.fhir.jpa.model.dialect.ISequenceValueMassager; +import ca.uhn.fhir.jpa.util.ISequenceValueMassager; import ca.uhn.fhir.model.api.TemporalPrecisionEnum; import ca.uhn.fhir.rest.server.interceptor.ResponseTerminologyTranslationSvc; import ca.uhn.fhir.util.HapiExtensions; diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/TagDefinition.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/TagDefinition.java index 111c1c83e04..5f4ae0260b7 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/TagDefinition.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/entity/TagDefinition.java @@ -19,27 +19,29 @@ */ package ca.uhn.fhir.jpa.model.entity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.OneToMany; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; import java.io.Serializable; import java.util.Collection; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.OneToMany; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Transient; @Entity @Table( @@ -82,6 +84,7 @@ public class TagDefinition implements Serializable { @Column(name = "TAG_TYPE", nullable = false) @Enumerated(EnumType.ORDINAL) + @JdbcTypeCode(SqlTypes.INTEGER) private TagTypeEnum myTagType; @Column(name = "TAG_VERSION", length = 30) diff --git a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/util/JpaConstants.java b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/util/JpaConstants.java index 333a962df0d..60fc4b7b68d 100644 --- a/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/util/JpaConstants.java +++ b/hapi-fhir-jpaserver-model/src/main/java/ca/uhn/fhir/jpa/model/util/JpaConstants.java @@ -294,7 +294,6 @@ public class JpaConstants { */ public static final String SUMMARY_OPERATION_URL = "http://hl7.org/fhir/uv/ips/OperationDefinition/summary"; - public static final String ORG_HIBERNATE_TYPE_TEXT_TYPE = "org.hibernate.type.TextType"; public static final String BULK_META_EXTENSION_EXPORT_IDENTIFIER = "https://hapifhir.org/NamingSystem/bulk-export-identifier"; public static final String BULK_META_EXTENSION_JOB_ID = "https://hapifhir.org/NamingSystem/bulk-export-job-id"; diff --git a/hapi-fhir-jpaserver-searchparam/pom.xml b/hapi-fhir-jpaserver-searchparam/pom.xml index 051a3069018..7668f21ed10 100755 --- a/hapi-fhir-jpaserver-searchparam/pom.xml +++ b/hapi-fhir-jpaserver-searchparam/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -13,7 +13,7 @@ hapi-fhir-jpaserver-searchparam jar - HAPI FHIR Search Parameters + HAPI FHIR JPA - Search Parameters @@ -125,7 +125,7 @@ org.hibernate.search - hibernate-search-mapper-orm + hibernate-search-mapper-orm-orm6 org.jscience @@ -160,8 +160,8 @@ test - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api test diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/interceptor/model/ReadPartitionIdRequestDetails.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/interceptor/model/ReadPartitionIdRequestDetails.java index 4f80dd9bbc2..c7884f8ad60 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/interceptor/model/ReadPartitionIdRequestDetails.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/interceptor/model/ReadPartitionIdRequestDetails.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeEvent.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeEvent.java index 2ab2483c29f..8490bcabd03 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeEvent.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeEvent.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListener.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListener.java index 0f6b2a61a44..3e6c8b5e96d 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListener.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListener.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerCache.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerCache.java index a3c7cddcea9..d44b20ce2d3 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerCache.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerCache.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerCacheRefresher.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerCacheRefresher.java index 5cba0d76dd0..7afd92d97e0 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerCacheRefresher.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerCacheRefresher.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerRegistry.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerRegistry.java index fa6ba39cf72..e2144a84ddf 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerRegistry.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceChangeListenerRegistry.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceVersionSvc.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceVersionSvc.java index 56c554c1ab8..d7297b2e453 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceVersionSvc.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/IResourceVersionSvc.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeEvent.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeEvent.java index 47c39e0262a..2193b4c7f54 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeEvent.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeEvent.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCache.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCache.java index 1efec3226db..a3eb41953ed 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCache.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCache.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCacheFactory.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCacheFactory.java index 92e8f725db1..4f412bd5a6d 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCacheFactory.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCacheFactory.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCacheRefresherImpl.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCacheRefresherImpl.java index 131b5a6851d..09cf5b1de53 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCacheRefresherImpl.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerCacheRefresherImpl.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerRegistryImpl.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerRegistryImpl.java index 8b30b1af72d..bdd8ab4d164 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerRegistryImpl.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerRegistryImpl.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerRegistryInterceptor.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerRegistryInterceptor.java index feec3df43ae..eba4a21f3ca 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerRegistryInterceptor.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeListenerRegistryInterceptor.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% @@ -23,6 +23,7 @@ import ca.uhn.fhir.IHapiBootOrder; import ca.uhn.fhir.interceptor.api.Hook; import ca.uhn.fhir.interceptor.api.IInterceptorService; import ca.uhn.fhir.interceptor.api.Pointcut; +import jakarta.annotation.PreDestroy; import org.hl7.fhir.instance.model.api.IBaseResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.ContextRefreshedEvent; @@ -30,8 +31,6 @@ import org.springframework.context.event.EventListener; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Service; -import javax.annotation.PreDestroy; - /** * This interceptor watches all resource changes on the server and compares them to the {@link IResourceChangeListenerCache} * entries. If the resource matches the resource type and search parameter map of that entry, then the corresponding cache diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeResult.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeResult.java index c5ca4cffa6d..ca30c7decc1 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeResult.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceChangeResult.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourcePersistentIdMap.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourcePersistentIdMap.java index 071dc8f1f20..ac01d8c0b54 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourcePersistentIdMap.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourcePersistentIdMap.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceVersionCache.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceVersionCache.java index 6b54a10a5ab..ec741ff7ab2 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceVersionCache.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceVersionCache.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceVersionMap.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceVersionMap.java index 81b7b4f580f..225db5831c1 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceVersionMap.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/cache/ResourceVersionMap.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/partition/IRequestPartitionHelperSvc.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/partition/IRequestPartitionHelperSvc.java index ea03d2cb32d..c2bfd3a67f1 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/partition/IRequestPartitionHelperSvc.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/partition/IRequestPartitionHelperSvc.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/MatchUrlService.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/MatchUrlService.java index f1d5a4a66b3..fcc2cc5e89b 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/MatchUrlService.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/MatchUrlService.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/ResourceMetaParams.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/ResourceMetaParams.java index 0114fba0b7a..78e0b475351 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/ResourceMetaParams.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/ResourceMetaParams.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/ResourceSearch.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/ResourceSearch.java index e37924741bf..9801b1468b1 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/ResourceSearch.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/ResourceSearch.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/SearchParamConstants.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/SearchParamConstants.java index 9478efdab78..4aa0a28bbc0 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/SearchParamConstants.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/SearchParamConstants.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/SearchParameterMap.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/SearchParameterMap.java index 0d5784a5818..c3d1ffa1ae1 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/SearchParameterMap.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/SearchParameterMap.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/config/NicknameServiceConfig.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/config/NicknameServiceConfig.java index 8aca1889e20..4ac537f3c2f 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/config/NicknameServiceConfig.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/config/NicknameServiceConfig.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/config/SearchParamConfig.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/config/SearchParamConfig.java index f1522621382..aa6c5233b40 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/config/SearchParamConfig.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/config/SearchParamConfig.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/BaseSearchParamExtractor.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/BaseSearchParamExtractor.java index 8ed714eb385..fdaf1eeafa1 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/BaseSearchParamExtractor.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/BaseSearchParamExtractor.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% @@ -49,6 +49,7 @@ import ca.uhn.fhir.util.UrlUtil; import ca.uhn.fhir.util.bundle.BundleEntryParts; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Sets; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; @@ -82,7 +83,6 @@ import java.util.TreeSet; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.annotation.PostConstruct; import javax.measure.quantity.Quantity; import javax.measure.unit.NonSI; import javax.measure.unit.Unit; diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/CrossPartitionReferenceDetails.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/CrossPartitionReferenceDetails.java index e7f9c352a24..643d26cef7b 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/CrossPartitionReferenceDetails.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/CrossPartitionReferenceDetails.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/GeopointNormalizer.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/GeopointNormalizer.java index 4d691e07b56..d5bc0957fab 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/GeopointNormalizer.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/GeopointNormalizer.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/IResourceLinkResolver.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/IResourceLinkResolver.java index dee9d778828..fad69f1ffef 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/IResourceLinkResolver.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/IResourceLinkResolver.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ISearchParamExtractor.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ISearchParamExtractor.java index fe137364848..29e3eb7b2e2 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ISearchParamExtractor.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ISearchParamExtractor.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/LogicalReferenceHelper.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/LogicalReferenceHelper.java index db6bf9bff5e..63f5e14f47d 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/LogicalReferenceHelper.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/LogicalReferenceHelper.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/PathAndRef.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/PathAndRef.java index a649c0601e1..027fb363c57 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/PathAndRef.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/PathAndRef.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ResourceIndexedSearchParamComposite.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ResourceIndexedSearchParamComposite.java index dfd41f27635..2ca11dd124f 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ResourceIndexedSearchParamComposite.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ResourceIndexedSearchParamComposite.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ResourceIndexedSearchParams.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ResourceIndexedSearchParams.java index 3af3d4c2986..29b0baeef31 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ResourceIndexedSearchParams.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/ResourceIndexedSearchParams.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorDstu2.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorDstu2.java index 66d1bb1a047..983638e9e31 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorDstu2.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorDstu2.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorDstu3.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorDstu3.java index a7e94c3ef19..f1e87737f5b 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorDstu3.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorDstu3.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% @@ -24,6 +24,7 @@ import ca.uhn.fhir.jpa.model.config.PartitionSettings; import ca.uhn.fhir.jpa.model.entity.StorageSettings; import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import com.google.common.annotations.VisibleForTesting; +import jakarta.annotation.PostConstruct; import org.hl7.fhir.dstu3.context.IWorkerContext; import org.hl7.fhir.dstu3.hapi.ctx.HapiWorkerContext; import org.hl7.fhir.dstu3.model.Base; @@ -32,7 +33,6 @@ import org.hl7.fhir.instance.model.api.IBase; import java.util.ArrayList; import java.util.List; -import javax.annotation.PostConstruct; public class SearchParamExtractorDstu3 extends BaseSearchParamExtractor implements ISearchParamExtractor { diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR4.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR4.java index 6b22d38b625..bc82a49e0ca 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR4.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR4.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% @@ -26,6 +26,7 @@ import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import ca.uhn.fhir.sl.cache.Cache; import ca.uhn.fhir.sl.cache.CacheFactory; import com.google.common.annotations.VisibleForTesting; +import jakarta.annotation.PostConstruct; import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.exceptions.PathEngineException; import org.hl7.fhir.instance.model.api.IBase; @@ -46,7 +47,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; -import javax.annotation.PostConstruct; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR4B.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR4B.java index 6ff518529a4..4add6601f1f 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR4B.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR4B.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% @@ -26,6 +26,7 @@ import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import ca.uhn.fhir.sl.cache.Cache; import ca.uhn.fhir.sl.cache.CacheFactory; import com.google.common.annotations.VisibleForTesting; +import jakarta.annotation.PostConstruct; import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.exceptions.PathEngineException; import org.hl7.fhir.instance.model.api.IBase; @@ -46,7 +47,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; -import javax.annotation.PostConstruct; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR5.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR5.java index 05ae9608475..44625b53a97 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR5.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorR5.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% @@ -25,6 +25,7 @@ import ca.uhn.fhir.jpa.model.entity.StorageSettings; import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import ca.uhn.fhir.sl.cache.Cache; import ca.uhn.fhir.sl.cache.CacheFactory; +import jakarta.annotation.PostConstruct; import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.exceptions.PathEngineException; import org.hl7.fhir.instance.model.api.IBase; @@ -45,7 +46,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; -import javax.annotation.PostConstruct; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorService.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorService.java index 01e288499c4..b8fddf42ea2 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorService.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/SearchParamExtractorService.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/StringTrimmingTrimmerMatcher.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/StringTrimmingTrimmerMatcher.java index f091bdf3c1d..cc40da8191e 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/StringTrimmingTrimmerMatcher.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/extractor/StringTrimmingTrimmerMatcher.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/AuthorizationSearchParamMatcher.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/AuthorizationSearchParamMatcher.java index 25366064cfd..b8fb38ebaca 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/AuthorizationSearchParamMatcher.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/AuthorizationSearchParamMatcher.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/InMemoryMatchResult.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/InMemoryMatchResult.java index 06cc6c57715..c7cf4e0fe07 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/InMemoryMatchResult.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/InMemoryMatchResult.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/InMemoryResourceMatcher.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/InMemoryResourceMatcher.java index 829b369867e..4b3c145fb36 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/InMemoryResourceMatcher.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/InMemoryResourceMatcher.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/IndexedSearchParamExtractor.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/IndexedSearchParamExtractor.java index 3deafea8642..64767055e00 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/IndexedSearchParamExtractor.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/IndexedSearchParamExtractor.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/SearchParamMatcher.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/SearchParamMatcher.java index 75367cca4bc..1f73d8bf1e0 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/SearchParamMatcher.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/matcher/SearchParamMatcher.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/nickname/NicknameInterceptor.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/nickname/NicknameInterceptor.java index 3dcf5fec1e4..11081c200c7 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/nickname/NicknameInterceptor.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/nickname/NicknameInterceptor.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/provider/SearchableHashMapResourceProvider.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/provider/SearchableHashMapResourceProvider.java index 41aed01c271..b5f8b513d94 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/provider/SearchableHashMapResourceProvider.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/provider/SearchableHashMapResourceProvider.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ISearchParamProvider.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ISearchParamProvider.java index ac050c36b9c..de4fb681c85 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ISearchParamProvider.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ISearchParamProvider.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ISearchParamRegistryController.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ISearchParamRegistryController.java index 35c9d14c4c2..c113b118b20 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ISearchParamRegistryController.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ISearchParamRegistryController.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/JpaSearchParamCache.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/JpaSearchParamCache.java index d1866bfcb3a..b6d88cafefc 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/JpaSearchParamCache.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/JpaSearchParamCache.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ReadOnlySearchParamCache.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ReadOnlySearchParamCache.java index a9c86f1fa8a..7bacb9317ae 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ReadOnlySearchParamCache.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/ReadOnlySearchParamCache.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/RuntimeSearchParamCache.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/RuntimeSearchParamCache.java index f0d4b49d379..939a654c860 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/RuntimeSearchParamCache.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/RuntimeSearchParamCache.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/SearchParamRegistryImpl.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/SearchParamRegistryImpl.java index d8bd1b6b55d..1fb3fa28831 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/SearchParamRegistryImpl.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/SearchParamRegistryImpl.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% @@ -42,6 +42,8 @@ import ca.uhn.fhir.util.SearchParameterUtil; import ca.uhn.fhir.util.StopWatch; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Sets; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -59,8 +61,6 @@ import java.util.Optional; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/SearchParameterCanonicalizer.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/SearchParameterCanonicalizer.java index f8b086965ca..cb2aa5ae87d 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/SearchParameterCanonicalizer.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/registry/SearchParameterCanonicalizer.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/retry/Retrier.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/retry/Retrier.java index 9e6d8b204e9..40016c6c5ce 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/retry/Retrier.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/retry/Retrier.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/Dstu3DistanceHelper.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/Dstu3DistanceHelper.java index a1041a1b738..77514845a41 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/Dstu3DistanceHelper.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/Dstu3DistanceHelper.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/JpaParamUtil.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/JpaParamUtil.java index f7713bb924d..66bdb32cd8e 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/JpaParamUtil.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/JpaParamUtil.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/LastNParameterHelper.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/LastNParameterHelper.java index caff223b6ea..4b86a7228af 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/LastNParameterHelper.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/LastNParameterHelper.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/RuntimeSearchParamHelper.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/RuntimeSearchParamHelper.java index 5601d73a6e7..312079b585a 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/RuntimeSearchParamHelper.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/RuntimeSearchParamHelper.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/SearchParameterHelper.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/SearchParameterHelper.java index ea566709e54..55e80e9d3ef 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/SearchParameterHelper.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/SearchParameterHelper.java @@ -1,6 +1,6 @@ /*- * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/SourceParam.java b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/SourceParam.java index 4ec77935492..7b183ff7657 100644 --- a/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/SourceParam.java +++ b/hapi-fhir-jpaserver-searchparam/src/main/java/ca/uhn/fhir/jpa/searchparam/util/SourceParam.java @@ -1,6 +1,6 @@ /* * #%L - * HAPI FHIR Search Parameters + * HAPI FHIR JPA - Search Parameters * %% * Copyright (C) 2014 - 2023 Smile CDR, Inc. * %% diff --git a/hapi-fhir-jpaserver-subscription/pom.xml b/hapi-fhir-jpaserver-subscription/pom.xml index 9b119ecea50..03f4d2159b5 100644 --- a/hapi-fhir-jpaserver-subscription/pom.xml +++ b/hapi-fhir-jpaserver-subscription/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -55,7 +55,7 @@ org.thymeleaf - thymeleaf-spring5 + thymeleaf-spring6 org.springframework @@ -66,8 +66,8 @@ spring-context-support - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided @@ -93,11 +93,6 @@ jetty-server test - - org.eclipse.jetty - jetty-servlet - test - org.springframework.boot spring-boot-starter-test diff --git a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/deliver/email/EmailDetails.java b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/deliver/email/EmailDetails.java index 40fd11b611c..f7ceb37b2ec 100644 --- a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/deliver/email/EmailDetails.java +++ b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/deliver/email/EmailDetails.java @@ -26,8 +26,8 @@ import org.hl7.fhir.instance.model.api.IIdType; import org.simplejavamail.api.email.Email; import org.simplejavamail.email.EmailBuilder; import org.thymeleaf.context.Context; -import org.thymeleaf.spring5.SpringTemplateEngine; -import org.thymeleaf.spring5.dialect.SpringStandardDialect; +import org.thymeleaf.spring6.SpringTemplateEngine; +import org.thymeleaf.spring6.dialect.SpringStandardDialect; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.StringTemplateResolver; diff --git a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/deliver/websocket/SubscriptionWebsocketHandler.java b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/deliver/websocket/SubscriptionWebsocketHandler.java index 706d01ee16d..982ba3d9082 100644 --- a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/deliver/websocket/SubscriptionWebsocketHandler.java +++ b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/deliver/websocket/SubscriptionWebsocketHandler.java @@ -24,6 +24,8 @@ import ca.uhn.fhir.jpa.subscription.channel.subscription.SubscriptionChannelRegi import ca.uhn.fhir.jpa.subscription.channel.subscription.SubscriptionChannelWithHandlers; import ca.uhn.fhir.jpa.subscription.match.registry.ActiveSubscription; import ca.uhn.fhir.jpa.subscription.model.ResourceDeliveryMessage; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.r4.model.IdType; import org.slf4j.Logger; @@ -39,8 +41,6 @@ import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.io.IOException; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; public class SubscriptionWebsocketHandler extends TextWebSocketHandler implements WebSocketHandler { private static Logger ourLog = LoggerFactory.getLogger(SubscriptionWebsocketHandler.class); diff --git a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/matcher/subscriber/MatchingQueueSubscriberLoader.java b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/matcher/subscriber/MatchingQueueSubscriberLoader.java index b16b1874cd3..14fade327b2 100644 --- a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/matcher/subscriber/MatchingQueueSubscriberLoader.java +++ b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/matcher/subscriber/MatchingQueueSubscriberLoader.java @@ -27,6 +27,7 @@ import ca.uhn.fhir.jpa.subscription.channel.api.IChannelReceiver; import ca.uhn.fhir.jpa.subscription.channel.subscription.SubscriptionChannelFactory; import ca.uhn.fhir.jpa.topic.SubscriptionTopicMatchingSubscriber; import ca.uhn.fhir.jpa.topic.SubscriptionTopicRegisteringSubscriber; +import jakarta.annotation.PreDestroy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -34,8 +35,6 @@ import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.core.annotation.Order; -import javax.annotation.PreDestroy; - import static ca.uhn.fhir.jpa.subscription.match.matcher.subscriber.SubscriptionMatchingSubscriber.SUBSCRIPTION_MATCHING_CHANNEL_NAME; public class MatchingQueueSubscriberLoader { diff --git a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/registry/SubscriptionRegistry.java b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/registry/SubscriptionRegistry.java index e791afa51e8..1a7742b13e4 100644 --- a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/registry/SubscriptionRegistry.java +++ b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/match/registry/SubscriptionRegistry.java @@ -27,6 +27,7 @@ import ca.uhn.fhir.jpa.subscription.channel.subscription.SubscriptionChannelRegi import ca.uhn.fhir.jpa.subscription.model.CanonicalSubscription; import ca.uhn.fhir.jpa.subscription.model.ChannelRetryConfiguration; import ca.uhn.fhir.util.HapiExtensions; +import jakarta.annotation.PreDestroy; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; @@ -39,7 +40,6 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; -import javax.annotation.PreDestroy; /** * Cache of active subscriptions. When a new subscription is added to the cache, a new Spring Channel is created diff --git a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/submit/interceptor/SubscriptionSubmitInterceptorLoader.java b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/submit/interceptor/SubscriptionSubmitInterceptorLoader.java index 2f72cb60509..c905a4960b6 100644 --- a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/submit/interceptor/SubscriptionSubmitInterceptorLoader.java +++ b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/submit/interceptor/SubscriptionSubmitInterceptorLoader.java @@ -23,13 +23,13 @@ import ca.uhn.fhir.interceptor.api.IInterceptorService; import ca.uhn.fhir.jpa.model.entity.StorageSettings; import ca.uhn.fhir.jpa.topic.SubscriptionTopicValidatingInterceptor; import com.google.common.annotations.VisibleForTesting; +import jakarta.annotation.PostConstruct; import org.hl7.fhir.dstu2.model.Subscription; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.Set; -import javax.annotation.PostConstruct; public class SubscriptionSubmitInterceptorLoader { private static final Logger ourLog = LoggerFactory.getLogger(SubscriptionSubmitInterceptorLoader.class); diff --git a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/triggering/SubscriptionTriggeringSvcImpl.java b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/triggering/SubscriptionTriggeringSvcImpl.java index 55563d08c71..c32a2fadb6d 100644 --- a/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/triggering/SubscriptionTriggeringSvcImpl.java +++ b/hapi-fhir-jpaserver-subscription/src/main/java/ca/uhn/fhir/jpa/subscription/triggering/SubscriptionTriggeringSvcImpl.java @@ -52,6 +52,7 @@ import ca.uhn.fhir.util.StopWatch; import ca.uhn.fhir.util.UrlUtil; import ca.uhn.fhir.util.ValidateUtil; import com.google.common.collect.Lists; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.concurrent.BasicThreadFactory; @@ -80,7 +81,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import javax.annotation.Nullable; -import javax.annotation.PostConstruct; import static ca.uhn.fhir.rest.server.provider.ProviderConstants.SUBSCRIPTION_TRIGGERING_PARAM_RESOURCE_ID; import static java.util.Objects.isNull; diff --git a/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/channel/subscription/BroadcastingSubscribableChannelWrapperTest.java b/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/channel/subscription/BroadcastingSubscribableChannelWrapperTest.java index 4c29d2b86ad..f78878cb75f 100644 --- a/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/channel/subscription/BroadcastingSubscribableChannelWrapperTest.java +++ b/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/channel/subscription/BroadcastingSubscribableChannelWrapperTest.java @@ -27,7 +27,7 @@ class BroadcastingSubscribableChannelWrapperTest { try { svc.send(new ResourceModifiedJsonMessage(new ResourceModifiedMessage())); } catch (MessageDeliveryException e) { - assertThat(e.getMessage(), containsString("Channel has zero subscribers")); + assertThat(e.getCause().getMessage(), containsString("Channel has zero subscribers")); } } diff --git a/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/match/deliver/BaseSubscriptionDeliverySubscriberTest.java b/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/match/deliver/BaseSubscriptionDeliverySubscriberTest.java index 16789be59d3..5153c161776 100644 --- a/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/match/deliver/BaseSubscriptionDeliverySubscriberTest.java +++ b/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/match/deliver/BaseSubscriptionDeliverySubscriberTest.java @@ -79,7 +79,7 @@ public class BaseSubscriptionDeliverySubscriberTest { private SubscriptionDeliveringRestHookSubscriber mySubscriber; private SubscriptionDeliveringMessageSubscriber myMessageSubscriber; private SubscriptionDeliveringEmailSubscriber myEmailSubscriber; - private final FhirContext myCtx = FhirContext.forR4(); + private final FhirContext myCtx = FhirContext.forR4Cached(); @Mock private IInterceptorBroadcaster myInterceptorBroadcaster; @@ -187,7 +187,7 @@ public class BaseSubscriptionDeliverySubscriberTest { mySubscriber.handleMessage(new ResourceDeliveryJsonMessage(payload)); fail(); } catch (MessagingException e) { - assertEquals(Msg.code(2) + "Failure handling subscription payload for subscription: Subscription/123; nested exception is ca.uhn.fhir.rest.server.exceptions.InternalErrorException: FOO", e.getMessage()); + assertEquals(Msg.code(2) + "Failure handling subscription payload for subscription: Subscription/123", e.getMessage()); } verify(myGenericClient, times(1)).update(); diff --git a/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/module/SubscriptionTestConfig.java b/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/module/SubscriptionTestConfig.java index e46ba54cf6f..0912e517285 100644 --- a/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/module/SubscriptionTestConfig.java +++ b/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/module/SubscriptionTestConfig.java @@ -46,7 +46,7 @@ public class SubscriptionTestConfig { private IChannelNamer myChannelNamer; @Primary - @Bean(autowire = Autowire.BY_NAME, name = "myJpaValidationSupportChain") + @Bean(name = "myJpaValidationSupportChain") public IValidationSupport validationSupportChainR4() { return myFhirContext.getValidationSupport(); } diff --git a/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/module/standalone/BaseBlockingQueueSubscribableChannelDstu3Test.java b/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/module/standalone/BaseBlockingQueueSubscribableChannelDstu3Test.java index b081bbdb37f..c1d003c11c7 100644 --- a/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/module/standalone/BaseBlockingQueueSubscribableChannelDstu3Test.java +++ b/hapi-fhir-jpaserver-subscription/src/test/java/ca/uhn/fhir/jpa/subscription/module/standalone/BaseBlockingQueueSubscribableChannelDstu3Test.java @@ -32,8 +32,8 @@ import ca.uhn.test.concurrency.IPointcutLatch; import ca.uhn.test.concurrency.PointcutLatch; import com.google.common.collect.Lists; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Coding; import org.hl7.fhir.dstu3.model.IdType; @@ -51,7 +51,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.SubscribableChannel; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Collections; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-dstu2/pom.xml b/hapi-fhir-jpaserver-test-dstu2/pom.xml index 177675ad5a5..773adc6b312 100644 --- a/hapi-fhir-jpaserver-test-dstu2/pom.xml +++ b/hapi-fhir-jpaserver-test-dstu2/pom.xml @@ -6,7 +6,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2SystemTest.java b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2SystemTest.java index ae3d1ff799a..599a774b85f 100644 --- a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2SystemTest.java +++ b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2SystemTest.java @@ -6,9 +6,9 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import org.junit.jupiter.api.BeforeEach; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; import java.util.Enumeration; import static org.mockito.Mockito.mock; diff --git a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java index 15aa0f38c91..108a573859f 100644 --- a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java +++ b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java @@ -72,7 +72,7 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionTemplate; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.util.ArrayList; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchFtTest.java b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchFtTest.java index 57c472b280d..e5c828100a2 100644 --- a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchFtTest.java +++ b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchFtTest.java @@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchNoFtTest.java b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchNoFtTest.java index 12bfe63c89d..13537d4a6a0 100644 --- a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchNoFtTest.java +++ b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchNoFtTest.java @@ -82,7 +82,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; diff --git a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SubscriptionsDstu2Test.java b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SubscriptionsDstu2Test.java index a428d1fb818..3bbca30528c 100644 --- a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SubscriptionsDstu2Test.java +++ b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SubscriptionsDstu2Test.java @@ -8,8 +8,8 @@ import ca.uhn.fhir.model.dstu2.valueset.SubscriptionStatusEnum; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; +import org.eclipse.jetty.websocket.api.annotations.OnWebSocketOpen; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; @@ -190,7 +190,7 @@ public class SubscriptionsDstu2Test extends BaseResourceProviderDstu2Test { /** * Basic Echo Client Socket */ - @WebSocket(maxTextMessageSize = 64 * 1024) + @WebSocket() public class SimpleEchoSocket extends BaseSocket { @SuppressWarnings("unused") @@ -200,14 +200,14 @@ public class SubscriptionsDstu2Test extends BaseResourceProviderDstu2Test { mySubsId = theSubsId; } - @OnWebSocketConnect + @OnWebSocketOpen public void onConnect(Session session) { ourLog.info("Got connect: {}", session); this.session = session; try { String sending = "bind " + mySubsId; ourLog.info("Sending: {}", sending); - session.getRemote().sendString(sending); + session.sendText(sending, null); } catch (Throwable t) { ourLog.error("Failure", t); } @@ -229,7 +229,7 @@ public class SubscriptionsDstu2Test extends BaseResourceProviderDstu2Test { /** * Basic Echo Client Socket */ - @WebSocket(maxTextMessageSize = 64 * 1024) + @WebSocket() public class DynamicEchoSocket extends BaseSocket { private List myReceived = new ArrayList(); @@ -243,14 +243,14 @@ public class SubscriptionsDstu2Test extends BaseResourceProviderDstu2Test { myEncoding = theEncoding; } - @OnWebSocketConnect + @OnWebSocketOpen public void onConnect(Session session) { ourLog.info("Got connect: {}", session); this.session = session; try { String sending = "bind " + myCriteria; ourLog.info("Sending: {}", sending); - session.getRemote().sendString(sending); + session.sendText(sending, null); } catch (Throwable t) { ourLog.error("Failure", t); } diff --git a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderDstu2Test.java b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderDstu2Test.java index 615309cca5a..1771c4de9d3 100644 --- a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderDstu2Test.java +++ b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderDstu2Test.java @@ -37,8 +37,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.IdType; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; diff --git a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderTransactionSearchDstu2Test.java b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderTransactionSearchDstu2Test.java index 1a3509cd3f4..6e53d143310 100644 --- a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderTransactionSearchDstu2Test.java +++ b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderTransactionSearchDstu2Test.java @@ -18,8 +18,8 @@ import ca.uhn.fhir.rest.client.interceptor.SimpleRequestHeaderInterceptor; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.test.utilities.JettyUtil; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestDstu2Test.java b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestDstu2Test.java index 429a6cc69db..563b2627355 100644 --- a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestDstu2Test.java +++ b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestDstu2Test.java @@ -24,8 +24,8 @@ import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import ca.uhn.fhir.test.utilities.JettyUtil; import com.google.common.collect.Lists; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.junit.jupiter.api.AfterAll; diff --git a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsDstu2Test.java b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsDstu2Test.java index 6f993478058..454743f20d2 100644 --- a/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsDstu2Test.java +++ b/hapi-fhir-jpaserver-test-dstu2/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsDstu2Test.java @@ -23,8 +23,8 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.test.utilities.JettyUtil; import com.google.common.collect.Lists; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; diff --git a/hapi-fhir-jpaserver-test-dstu3/pom.xml b/hapi-fhir-jpaserver-test-dstu3/pom.xml index 83dde3e9706..3af365157a4 100644 --- a/hapi-fhir-jpaserver-test-dstu3/pom.xml +++ b/hapi-fhir-jpaserver-test-dstu3/pom.xml @@ -6,7 +6,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/BaseJpaDstu3SystemTest.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/BaseJpaDstu3SystemTest.java index f9835681abc..65f79eba0d0 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/BaseJpaDstu3SystemTest.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/BaseJpaDstu3SystemTest.java @@ -7,9 +7,9 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import org.junit.jupiter.api.BeforeEach; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; import java.util.Enumeration; import static org.mockito.Mockito.mock; diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3SearchFtTest.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3SearchFtTest.java index a20b849cacf..04c59ac49b9 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3SearchFtTest.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3SearchFtTest.java @@ -22,7 +22,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3SearchNoFtTest.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3SearchNoFtTest.java index db98eb767bd..83123192373 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3SearchNoFtTest.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirResourceDaoDstu3SearchNoFtTest.java @@ -106,7 +106,7 @@ import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirSystemDaoDstu3Test.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirSystemDaoDstu3Test.java index 7cda01d5905..2da47c1baed 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirSystemDaoDstu3Test.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/FhirSystemDaoDstu3Test.java @@ -2350,7 +2350,7 @@ public class FhirSystemDaoDstu3Test extends BaseJpaDstu3SystemTest { try { mySystemDao.transaction(mySrd, b); } catch (ResourceVersionConflictException e) { - assertEquals(Msg.code(550) + Msg.code(550) + Msg.code(989) + "Trying to update Patient/P1/_history/2 but this is not the current version", e.getMessage()); + assertEquals(Msg.code(550) + Msg.code(989) + "Trying to update Patient/P1/_history/2 but this is not the current version", e.getMessage()); } b = new Bundle(); diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/packages/IgInstallerDstu3Test.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/packages/IgInstallerDstu3Test.java index 37e0a8ad6b8..e6c00f876bb 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/packages/IgInstallerDstu3Test.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/packages/IgInstallerDstu3Test.java @@ -10,9 +10,10 @@ import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import ca.uhn.fhir.test.utilities.JettyUtil; import ca.uhn.fhir.test.utilities.ProxyUtil; +import ca.uhn.fhir.test.utilities.server.HttpServletExtension; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseBinary; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Patient; @@ -21,6 +22,7 @@ import org.hl7.fhir.utilities.npm.PackageServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -47,36 +49,29 @@ public class IgInstallerDstu3Test extends BaseJpaDstu3Test { @Autowired @Qualifier(PackageUtils.LOADER_WITH_CACHE) private IHapiPackageCacheManager myPackageCacheManager; - private Server myServer; - private FakeNpmServlet myFakeNpmServlet; @Autowired private INpmPackageVersionDao myPackageVersionDao; - private int myPort; + private FakeNpmServlet myFakeNpmServlet = new FakeNpmServlet(); + @RegisterExtension + public HttpServletExtension myServer = new HttpServletExtension() + .withServlet(myFakeNpmServlet); + + @Override @BeforeEach public void before() throws Exception { super.before(); JpaPackageCache jpaPackageCache = ProxyUtil.getSingletonTarget(myPackageCacheManager, JpaPackageCache.class); - - myServer = new Server(0); - ServletHandler proxyHandler = new ServletHandler(); - myFakeNpmServlet = new FakeNpmServlet(); - ServletHolder servletHolder = new ServletHolder(myFakeNpmServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - myServer.setHandler(proxyHandler); - myServer.start(); - - myPort = JettyUtil.getPortForStartedServer(myServer); + jpaPackageCache.getPackageServers().clear(); - jpaPackageCache.addPackageServer(new PackageServer("http://localhost:" + myPort)); + jpaPackageCache.addPackageServer(new PackageServer(myServer.getBaseUrl())); myFakeNpmServlet.getResponses().clear(); } @AfterEach public void after() throws Exception { - JettyUtil.closeServer(myServer); myStorageSettings.setAllowExternalReferences(new JpaStorageSettings().isAllowExternalReferences()); } @@ -156,7 +151,7 @@ public class IgInstallerDstu3Test extends BaseJpaDstu3Test { igInstaller.install(new PackageInstallationSpec() .setName("nictiz.fhir.nl.stu3.questionnaires") .setVersion("1.0.2") - .setPackageUrl("http://localhost:" + myPort + "/foo.tgz") + .setPackageUrl(myServer.getBaseUrl() + "/foo.tgz") ); runInTransaction(() -> { @@ -240,7 +235,7 @@ public class IgInstallerDstu3Test extends BaseJpaDstu3Test { igInstaller.install(new PackageInstallationSpec() .setName("blah") .setVersion("1.0.2") - .setPackageUrl("http://localhost:" + myPort + "/foo.tgz") + .setPackageUrl(myServer.getBaseUrl() + "/foo.tgz") ); fail(); } catch (InvalidRequestException e) { @@ -255,11 +250,11 @@ public class IgInstallerDstu3Test extends BaseJpaDstu3Test { igInstaller.install(new PackageInstallationSpec() .setName("blah") .setVersion("1.0.2") - .setPackageUrl("http://localhost:" + myPort + "/foo.tgz") + .setPackageUrl(myServer.getBaseUrl() + "/foo.tgz") ); fail(); } catch (ResourceNotFoundException e) { - assertEquals(Msg.code(1303) + "Received HTTP 404 from URL: http://localhost:" + myPort + "/foo.tgz", e.getMessage()); + assertEquals(Msg.code(1303) + "Received HTTP 404 from URL: " + myServer.getBaseUrl() + "/foo.tgz", e.getMessage()); } } diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/packages/NpmDstu3Test.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/packages/NpmDstu3Test.java index bee28e90161..0f293238783 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/packages/NpmDstu3Test.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/packages/NpmDstu3Test.java @@ -1,35 +1,24 @@ package ca.uhn.fhir.jpa.packages; import ca.uhn.fhir.jpa.test.BaseJpaDstu3Test; -import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.ValidationModeEnum; -import ca.uhn.fhir.test.utilities.JettyUtil; import ca.uhn.fhir.test.utilities.ProxyUtil; +import ca.uhn.fhir.test.utilities.server.HttpServletExtension; import ca.uhn.fhir.util.ClasspathUtil; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.CodeSystem; import org.hl7.fhir.dstu3.model.Condition; import org.hl7.fhir.dstu3.model.OperationOutcome; import org.hl7.fhir.dstu3.model.StructureDefinition; import org.hl7.fhir.dstu3.model.ValueSet; import org.hl7.fhir.utilities.npm.PackageServer; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -44,43 +33,34 @@ public class NpmDstu3Test extends BaseJpaDstu3Test { @Autowired private NpmJpaValidationSupport myNpmJpaValidationSupport; - private Server myServer; - private final Map myResponses = new HashMap<>(); + private ca.uhn.fhir.jpa.packages.FakeNpmServlet myFakeNpmServlet = new ca.uhn.fhir.jpa.packages.FakeNpmServlet(); + @RegisterExtension + public HttpServletExtension myServer = new HttpServletExtension() + .withServlet(myFakeNpmServlet); + @Override @BeforeEach public void before() throws Exception { + super.before(); JpaPackageCache jpaPackageCache = ProxyUtil.getSingletonTarget(myPackageCacheManager, JpaPackageCache.class); - myServer = new Server(0); - ServletHandler proxyHandler = new ServletHandler(); - FakeNpmServlet fakeNpmServlet = new FakeNpmServlet(); - ServletHolder servletHolder = new ServletHolder(fakeNpmServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - myServer.setHandler(proxyHandler); - myServer.start(); - - int port = JettyUtil.getPortForStartedServer(myServer); jpaPackageCache.getPackageServers().clear(); - jpaPackageCache.addPackageServer(new PackageServer("http://localhost:" + port)); + jpaPackageCache.addPackageServer(new PackageServer(myServer.getBaseUrl())); - myResponses.clear(); + myFakeNpmServlet.getResponses().clear(); } - @AfterEach - public void after() throws Exception { - JettyUtil.closeServer(myServer); - } @Test public void installDstu3Package() throws Exception { byte[] bytes = ClasspathUtil.loadResourceAsByteArray("/packages/basisprofil.de.tar.gz"); - myResponses.put("/basisprofil.de/0.2.40", bytes); + myFakeNpmServlet.getResponses().put("/basisprofil.de/0.2.40", bytes); PackageInstallationSpec spec = new PackageInstallationSpec().setName("basisprofil.de").setVersion("0.2.40").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY); igInstaller.install(spec); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); StructureDefinition sd = (StructureDefinition) myNpmJpaValidationSupport.fetchStructureDefinition("http://fhir.de/StructureDefinition/condition-de-basis/0.2"); assertEquals("http://fhir.de/StructureDefinition/condition-de-basis/0.2", sd.getUrl()); @@ -104,25 +84,4 @@ public class NpmDstu3Test extends BaseJpaDstu3Test { containsString("Condition.subject: minimum required = 1, but only found 0 (from http://fhir.de/StructureDefinition/condition-de-basis/0.2")); } - - private class FakeNpmServlet extends HttpServlet { - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - String requestUrl = req.getRequestURI(); - if (myResponses.containsKey(requestUrl)) { - ourLog.info("Responding to request: {}", requestUrl); - - resp.setStatus(200); - resp.setHeader(Constants.HEADER_CONTENT_TYPE, "application/gzip"); - resp.getOutputStream().write(myResponses.get(requestUrl)); - resp.getOutputStream().close(); - } else { - ourLog.warn("Unknown request: {}", requestUrl); - - resp.sendError(404); - } - - } - } } diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/SubscriptionsDstu3Test.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/SubscriptionsDstu3Test.java index 95c777537f6..c716da163e4 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/SubscriptionsDstu3Test.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/SubscriptionsDstu3Test.java @@ -5,8 +5,8 @@ import ca.uhn.fhir.jpa.util.SubscriptionsRequireManualActivationInterceptorDstu3 import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; +import org.eclipse.jetty.websocket.api.annotations.OnWebSocketOpen; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.hl7.fhir.dstu3.model.Subscription; import org.hl7.fhir.dstu3.model.Subscription.SubscriptionChannelType; @@ -179,7 +179,7 @@ public class SubscriptionsDstu3Test extends BaseResourceProviderDstu3Test { /** * Basic Echo Client Socket */ - @WebSocket(maxTextMessageSize = 64 * 1024) + @WebSocket public class DynamicEchoSocket extends BaseSocket { private String myCriteria; @@ -193,14 +193,14 @@ public class SubscriptionsDstu3Test extends BaseResourceProviderDstu3Test { myEncoding = theEncoding; } - @OnWebSocketConnect + @OnWebSocketOpen public void onConnect(Session session) { ourLog.info("Got connect: {}", session); this.session = session; try { String sending = "bind " + myCriteria; ourLog.info("Sending: {}", sending); - session.getRemote().sendString(sending); + session.sendText(sending, null); } catch (Throwable t) { ourLog.error("Failure", t); } @@ -227,7 +227,7 @@ public class SubscriptionsDstu3Test extends BaseResourceProviderDstu3Test { /** * Basic Echo Client Socket */ - @WebSocket(maxTextMessageSize = 64 * 1024) + @WebSocket public class SimpleEchoSocket extends BaseSocket { @SuppressWarnings("unused") @@ -237,14 +237,14 @@ public class SubscriptionsDstu3Test extends BaseResourceProviderDstu3Test { mySubsId = theSubsId; } - @OnWebSocketConnect + @OnWebSocketOpen public void onConnect(Session session) { ourLog.info("Got connect: {}", session); this.session = session; try { String sending = "bind " + mySubsId; ourLog.info("Sending: {}", sending); - session.getRemote().sendString(sending); + session.sendText(sending, null); } catch (Throwable t) { ourLog.error("Failure", t); } diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/SystemProviderTransactionSearchDstu3Test.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/SystemProviderTransactionSearchDstu3Test.java index 75f5a7301d7..93e904b44a7 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/SystemProviderTransactionSearchDstu3Test.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/SystemProviderTransactionSearchDstu3Test.java @@ -16,8 +16,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.Binary; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent; diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestDstu3Test.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestDstu3Test.java index 43e66e09e3b..730cb5c13fb 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestDstu3Test.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestDstu3Test.java @@ -26,8 +26,8 @@ import ca.uhn.fhir.util.HapiExtensions; import ca.uhn.fhir.util.MetaUtil; import com.google.common.collect.Lists; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.BooleanType; import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Coding; @@ -52,7 +52,7 @@ import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Nonnull; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Collections; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsDstu3Test.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsDstu3Test.java index a4d4f22eff2..83a439228fc 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsDstu3Test.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsDstu3Test.java @@ -15,8 +15,8 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.test.utilities.JettyUtil; import com.google.common.collect.Lists; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Coding; import org.hl7.fhir.dstu3.model.IdType; diff --git a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/SubscriptionTriggeringDstu3Test.java b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/SubscriptionTriggeringDstu3Test.java index 16961762a24..29eab34b330 100644 --- a/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/SubscriptionTriggeringDstu3Test.java +++ b/hapi-fhir-jpaserver-test-dstu3/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/SubscriptionTriggeringDstu3Test.java @@ -23,8 +23,8 @@ import ca.uhn.fhir.test.utilities.JettyUtil; import ca.uhn.fhir.test.utilities.ProxyUtil; import com.google.common.collect.Lists; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Coding; import org.hl7.fhir.dstu3.model.IdType; @@ -48,7 +48,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; diff --git a/hapi-fhir-jpaserver-test-r4/pom.xml b/hapi-fhir-jpaserver-test-r4/pom.xml index 79a1bddbeaa..f284432c58c 100644 --- a/hapi-fhir-jpaserver-test-r4/pom.xml +++ b/hapi-fhir-jpaserver-test-r4/pom.xml @@ -6,7 +6,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -55,7 +55,12 @@ javax.json-api test - + + jakarta.servlet + jakarta.servlet-api + test + + @@ -78,10 +83,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - org.apache.maven.plugins maven-checkstyle-plugin diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/batch2/Batch2JobMaintenanceIT.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/batch2/Batch2JobMaintenanceIT.java index 6c847de3250..bb7797a39fa 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/batch2/Batch2JobMaintenanceIT.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/batch2/Batch2JobMaintenanceIT.java @@ -32,7 +32,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import javax.annotation.Nonnull; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/binstore/BinaryAccessProviderTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/binstore/BinaryAccessProviderTest.java index 6b69c725c0b..3e4062c5c67 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/binstore/BinaryAccessProviderTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/binstore/BinaryAccessProviderTest.java @@ -26,9 +26,9 @@ import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.Date; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/bulk/imprt2/ConsumeFilesStepR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/bulk/imprt2/ConsumeFilesStepR4Test.java index c005497f6af..d9208ba6ab2 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/bulk/imprt2/ConsumeFilesStepR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/bulk/imprt2/ConsumeFilesStepR4Test.java @@ -190,8 +190,8 @@ public class ConsumeFilesStepR4Test extends BasePartitioningR4Test { assertEquals(1, myCaptureQueriesListener.logSelectQueries().size()); assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), - either(containsString("resourceta0_.RES_TYPE='Patient' and resourceta0_.FHIR_ID='B' and (resourceta0_.PARTITION_ID is null) or resourceta0_.RES_TYPE='Patient' and resourceta0_.FHIR_ID='A' and (resourceta0_.PARTITION_ID is null)")) - .or(containsString("resourceta0_.RES_TYPE='Patient' and resourceta0_.FHIR_ID='A' and (resourceta0_.PARTITION_ID is null) or resourceta0_.RES_TYPE='Patient' and resourceta0_.FHIR_ID='B' and (resourceta0_.PARTITION_ID is null)"))); + either(containsString("rt1_0.RES_TYPE='Patient' and rt1_0.FHIR_ID='B' and rt1_0.PARTITION_ID is null or rt1_0.RES_TYPE='Patient' and rt1_0.FHIR_ID='A' and rt1_0.PARTITION_ID is null")) + .or(containsString("rt1_0.RES_TYPE='Patient' and rt1_0.FHIR_ID='A' and rt1_0.PARTITION_ID is null or rt1_0.RES_TYPE='Patient' and rt1_0.FHIR_ID='B' and rt1_0.PARTITION_ID is null"))); assertEquals(52, myCaptureQueriesListener.countInsertQueriesForCurrentThread()); assertEquals(0, myCaptureQueriesListener.countUpdateQueriesForCurrentThread()); assertEquals(0, myCaptureQueriesListener.countDeleteQueriesForCurrentThread()); diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirDaoTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirDaoTest.java index c05ea3cacf1..371091d3d62 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirDaoTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirDaoTest.java @@ -30,15 +30,15 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionSynchronizationManager; import javax.annotation.Nullable; -import javax.persistence.EntityExistsException; -import javax.persistence.EntityManager; -import javax.persistence.NoResultException; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.EntityExistsException; +import jakarta.persistence.EntityManager; +import jakarta.persistence.NoResultException; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Path; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirResourceDaoTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirResourceDaoTest.java index 98fea30536f..7fdd962e5c0 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirResourceDaoTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/BaseHapiFhirResourceDaoTest.java @@ -44,9 +44,7 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ApplicationContext; -import javax.persistence.EntityManager; -import java.util.ArrayList; -import java.util.Collection; +import jakarta.persistence.EntityManager; import java.util.List; import java.util.stream.Stream; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/TransactionProcessorTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/TransactionProcessorTest.java index 6bc21dff961..18237f46d50 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/TransactionProcessorTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/TransactionProcessorTest.java @@ -38,8 +38,8 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.PlatformTransactionManager; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/expunge/ResourceTableFKProviderTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/expunge/ResourceTableFKProviderTest.java index c62a069d4c8..558555ad570 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/expunge/ResourceTableFKProviderTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/expunge/ResourceTableFKProviderTest.java @@ -6,9 +6,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; import javax.sql.DataSource; import java.sql.Connection; import java.sql.DatabaseMetaData; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/BaseJpaR4SystemTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/BaseJpaR4SystemTest.java index 438667dfbb3..404cc2a639d 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/BaseJpaR4SystemTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/BaseJpaR4SystemTest.java @@ -5,8 +5,8 @@ import ca.uhn.fhir.jpa.test.BaseJpaR4Test; import ca.uhn.fhir.rest.server.RestfulServer; import org.junit.jupiter.api.BeforeEach; -import javax.servlet.ServletConfig; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.http.HttpServletRequest; import java.util.Enumeration; import static org.mockito.Mockito.mock; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4QueryCountTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4QueryCountTest.java index 457ba5e943d..77d17e0e3f0 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4QueryCountTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4QueryCountTest.java @@ -26,6 +26,8 @@ import ca.uhn.fhir.jpa.model.util.JpaConstants; import ca.uhn.fhir.jpa.provider.BaseResourceProviderR4Test; import ca.uhn.fhir.jpa.search.PersistedJpaSearchFirstPageBundleProvider; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; +import ca.uhn.fhir.jpa.searchparam.submit.interceptor.SearchParamValidatingInterceptor; +import ca.uhn.fhir.jpa.subscription.submit.interceptor.SubscriptionValidatingInterceptor; import ca.uhn.fhir.jpa.subscription.submit.svc.ResourceModifiedSubmitterSvc; import ca.uhn.fhir.jpa.subscription.triggering.ISubscriptionTriggeringSvc; import ca.uhn.fhir.jpa.subscription.triggering.SubscriptionTriggeringSvcImpl; @@ -117,6 +119,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.contains; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -592,7 +595,7 @@ public class FhirResourceDaoR4QueryCountTest extends BaseResourceProviderR4Test fail(myFhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(e.getOperationOutcome())); } myCaptureQueriesListener.logSelectQueriesForCurrentThread(); - assertEquals(11, myCaptureQueriesListener.getSelectQueriesForCurrentThread().size()); + assertEquals(12, myCaptureQueriesListener.getSelectQueriesForCurrentThread().size()); assertEquals(0, myCaptureQueriesListener.getUpdateQueriesForCurrentThread().size()); assertEquals(0, myCaptureQueriesListener.getInsertQueriesForCurrentThread().size()); assertEquals(0, myCaptureQueriesListener.getDeleteQueriesForCurrentThread().size()); @@ -1329,7 +1332,7 @@ public class FhirResourceDaoR4QueryCountTest extends BaseResourceProviderR4Test myCaptureQueriesListener.logSelectQueries(); assertEquals(2, myCaptureQueriesListener.countSelectQueries()); assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("SELECT t0.RES_ID FROM HFJ_SPIDX_TOKEN t0")); - assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("limit '6'")); + assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("fetch first '6'")); assertEquals(0, myCaptureQueriesListener.countInsertQueries()); assertEquals(0, myCaptureQueriesListener.countUpdateQueries()); assertEquals(0, myCaptureQueriesListener.countDeleteQueries()); @@ -1345,7 +1348,7 @@ public class FhirResourceDaoR4QueryCountTest extends BaseResourceProviderR4Test myCaptureQueriesListener.logSelectQueries(); assertEquals(2, myCaptureQueriesListener.countSelectQueries()); assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("SELECT t0.RES_ID FROM HFJ_SPIDX_TOKEN t0")); - assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("limit '6'")); + assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("fetch next '6'")); assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("offset '5'")); assertEquals(0, myCaptureQueriesListener.countInsertQueries()); assertEquals(0, myCaptureQueriesListener.countUpdateQueries()); @@ -2405,9 +2408,9 @@ public class FhirResourceDaoR4QueryCountTest extends BaseResourceProviderR4Test assertEquals(0, myCaptureQueriesListener.countDeleteQueries()); // Make sure the match URL query uses a small limit - String matchUrlQuery = myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, true); - assertThat(matchUrlQuery, containsString("HASH_SYS_AND_VALUE='-4132452001562191669'")); - assertThat(matchUrlQuery, containsString("limit '2'")); + String matchUrlQuery = myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false); + assertThat(matchUrlQuery, containsString("rispt1_0.HASH_SYS_AND_VALUE='-4132452001562191669'")); + assertThat(matchUrlQuery, containsString("fetch first '2'")); runInTransaction(() -> { List types = myResourceTableDao.findAll().stream().map(t -> t.getResourceType()).collect(Collectors.toList()); @@ -3206,7 +3209,7 @@ public class FhirResourceDaoR4QueryCountTest extends BaseResourceProviderR4Test assertEquals(7, expansion.getExpansion().getContains().size()); assertEquals(1, expansion.getExpansion().getContains().stream().filter(t -> t.getCode().equals("A")).findFirst().orElseThrow(() -> new IllegalArgumentException()).getDesignation().size()); myCaptureQueriesListener.logSelectQueriesForCurrentThread(); - assertEquals(5, myCaptureQueriesListener.countSelectQueries()); + assertEquals(6, myCaptureQueriesListener.countSelectQueries(), ()->"\n *" + myCaptureQueriesListener.getSelectQueries().stream().map(t->t.getSql(true, false)).collect(Collectors.joining("\n * "))); assertEquals(0, myCaptureQueriesListener.countDeleteQueries()); assertEquals(0, myCaptureQueriesListener.countUpdateQueries()); assertEquals(0, myCaptureQueriesListener.countInsertQueries()); @@ -3249,7 +3252,7 @@ public class FhirResourceDaoR4QueryCountTest extends BaseResourceProviderR4Test assertEquals(7, expansion.getExpansion().getContains().size()); assertEquals(1, expansion.getExpansion().getContains().stream().filter(t -> t.getCode().equals("A")).findFirst().orElseThrow(() -> new IllegalArgumentException()).getDesignation().size()); myCaptureQueriesListener.logSelectQueriesForCurrentThread(); - assertEquals(5, myCaptureQueriesListener.countSelectQueries()); + assertEquals(6, myCaptureQueriesListener.countSelectQueries()); assertEquals(0, myCaptureQueriesListener.countDeleteQueries()); assertEquals(0, myCaptureQueriesListener.countUpdateQueries()); assertEquals(0, myCaptureQueriesListener.countInsertQueries()); diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchFtTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchFtTest.java index 0c26341ce74..a80c8002e3f 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchFtTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchFtTest.java @@ -24,7 +24,7 @@ import org.hl7.fhir.r4.model.StringType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchNoFtTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchNoFtTest.java index 826f6ffad95..2d668f24e5d 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchNoFtTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchNoFtTest.java @@ -151,7 +151,7 @@ import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; @@ -3859,33 +3859,6 @@ public class FhirResourceDaoR4SearchNoFtTest extends BaseJpaR4Test { assertEquals(2, countMatches(searchQuery.toUpperCase(), "RES_UPDATED"), searchQuery); } - @Disabled - @Test - public void testSearchWithContext() { - - - String url = "Procedure?_count=300&_format=json&_include%3Arecurse=*&category=CANN&encounter.identifier=A1057852019&status%3Anot=entered-in-error"; - RuntimeResourceDefinition def = myFhirContext.getResourceDefinition("Procedure"); - SearchParameterMap sp = myMatchUrlService.translateMatchUrl(url, def); - - - myCaptureQueriesListener.clear(); - sp.setLoadSynchronous(true); - myProcedureDao.search(sp); - - myCaptureQueriesListener.logSelectQueriesForCurrentThread(); -// List queries = myCaptureQueriesListener -// .getSelectQueriesForCurrentThread() -// .stream() -// .map(t -> t.getSql(true, true)) -// .collect(Collectors.toList()); -// -// String searchQuery = queries.get(0); -// assertEquals(searchQuery, 1, StringUtils.countMatches(searchQuery.toUpperCase(), "HFJ_SPIDX_TOKEN")); -// assertEquals(searchQuery, 1, StringUtils.countMatches(searchQuery.toUpperCase(), "LEFT OUTER JOIN")); -// assertEquals(searchQuery, 2, StringUtils.countMatches(searchQuery.toUpperCase(), "AND RESOURCETA0_.RES_UPDATED")); - } - @Test public void testSearchTokenParam() { Patient patient = new Patient(); @@ -4619,8 +4592,8 @@ public class FhirResourceDaoR4SearchNoFtTest extends BaseJpaR4Test { assertNull(values.size()); assertEquals(5, values.getResources(0, 1000).size()); - String sql = myCaptureQueriesListener.logSelectQueriesForCurrentThread(0); - assertEquals(1, countMatches(sql, "limit '5'"), sql); + String sql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, false); + assertEquals(1, countMatches(sql, "fetch first '5'"), sql); } @Test diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchOptimizedTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchOptimizedTest.java index 0f63fe5d3b5..1e15bc49293 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchOptimizedTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchOptimizedTest.java @@ -96,9 +96,11 @@ public class FhirResourceDaoR4SearchOptimizedTest extends BaseJpaR4Test { @Autowired private MatchUrlService myMatchUrlService; + @Override @BeforeEach - public void before() { - mySearchCoordinatorSvcImpl = (SearchCoordinatorSvcImpl) ProxyUtil.getSingletonTarget(mySearchCoordinatorSvc, SearchCoordinatorSvcImpl.class); + public void before() throws Exception { + super.before(); + mySearchCoordinatorSvcImpl = ProxyUtil.getSingletonTarget(mySearchCoordinatorSvc, SearchCoordinatorSvcImpl.class); mySearchCoordinatorSvcImpl.setLoadingThrottleForUnitTests(null); mySearchCoordinatorSvcImpl.setSyncSizeForUnitTests(QueryParameterUtils.DEFAULT_SYNC_SIZE); myCaptureQueriesListener.setCaptureQueryStackTrace(true); @@ -894,12 +896,12 @@ public class FhirResourceDaoR4SearchOptimizedTest extends BaseJpaR4Test { myCaptureQueriesListener.logSelectQueriesForCurrentThread(); String selectQuery = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, false); - assertEquals(1, StringUtils.countMatches(selectQuery.toLowerCase(), "resourceta0_.res_type='observation'"), selectQuery); - assertEquals(1, StringUtils.countMatches(selectQuery.toLowerCase(), "resourceta0_.fhir_id in ('a')"), selectQuery); + assertEquals(1, StringUtils.countMatches(selectQuery.toLowerCase(), "rt1_0.res_type='observation'"), selectQuery); + assertEquals(1, StringUtils.countMatches(selectQuery.toLowerCase(), "rt1_0.fhir_id in ('a')"), selectQuery); selectQuery = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(1).getSql(true, false); assertEquals(1, StringUtils.countMatches(selectQuery.toLowerCase(), "select t1.res_id from hfj_resource t1"), selectQuery); - assertEquals(0, StringUtils.countMatches(selectQuery.toLowerCase(), "t1.res_type = 'observation'"), selectQuery); + assertEquals(0, StringUtils.countMatches(selectQuery.toLowerCase(), "t1.res_type='observation'"), selectQuery); assertEquals(0, StringUtils.countMatches(selectQuery.toLowerCase(), "t1.res_deleted_at is null"), selectQuery); } @@ -936,8 +938,8 @@ public class FhirResourceDaoR4SearchOptimizedTest extends BaseJpaR4Test { assertEquals(1, myCaptureQueriesListener.getSelectQueriesForCurrentThread().size()); String selectQuery = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, false); - assertEquals(1, StringUtils.countMatches(selectQuery.toLowerCase(), "resourceta0_.res_type='observation'"), selectQuery); - assertEquals(1, StringUtils.countMatches(selectQuery.toLowerCase(), "resourceta0_.fhir_id in ('a')"), selectQuery); + assertEquals(1, StringUtils.countMatches(selectQuery.toLowerCase(), "rt1_0.res_type='observation'"), selectQuery); + assertEquals(1, StringUtils.countMatches(selectQuery.toLowerCase(), "rt1_0.fhir_id in ('a')"), selectQuery); } // Search by ID where at least one ID is a numeric ID @@ -1546,7 +1548,7 @@ public class FhirResourceDaoR4SearchOptimizedTest extends BaseJpaR4Test { // Forced ID resolution resultingQueryNotFormatted = queries.get(0); assertThat(resultingQueryNotFormatted, containsString("RES_TYPE='Organization'")); - assertThat(resultingQueryNotFormatted, containsString("resourceta0_.RES_TYPE='Organization' and resourceta0_.FHIR_ID='ORG1' or resourceta0_.RES_TYPE='Organization' and resourceta0_.FHIR_ID='ORG2'")); + assertThat(resultingQueryNotFormatted, containsString("rt1_0.RES_TYPE='Organization' and rt1_0.FHIR_ID='ORG1' or rt1_0.RES_TYPE='Organization' and rt1_0.FHIR_ID='ORG2'")); // The search itself resultingQueryNotFormatted = queries.get(1); diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchSqlTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchSqlTest.java index 0ccd6ae7d0e..710639e34fb 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchSqlTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4SearchSqlTest.java @@ -99,10 +99,10 @@ public class FhirResourceDaoR4SearchSqlTest extends BaseJpaR4Test { assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 INNER JOIN HFJ_RES_TAG t1 ON (t0.RES_ID = t1.RES_ID) INNER JOIN HFJ_TAG_DEF t2 ON (t1.TAG_ID = t2.TAG_ID) WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND ((t2.TAG_TYPE = ?) AND (t2.TAG_SYSTEM = ?) AND (t2.TAG_CODE = ?)))", sql); // Query 2 - Load resourece contents sql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(1).getSql(false, false); - assertThat(sql, containsString("where resourcese0_.RES_ID in (?)")); + assertThat(sql, containsString("where rsv1_0.RES_ID in (?)")); // Query 3 - Load tags and defintions sql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(2).getSql(false, false); - assertThat(sql, containsString("from HFJ_RES_TAG resourceta0_ inner join HFJ_TAG_DEF")); + assertThat(sql, containsString("from HFJ_RES_TAG rt1_0 join HFJ_TAG_DEF")); assertThat(toUnqualifiedVersionlessIds(outcome), Matchers.contains(id)); @@ -138,7 +138,7 @@ public class FhirResourceDaoR4SearchSqlTest extends BaseJpaR4Test { assertEquals("SELECT t0.RES_ID FROM HFJ_SPIDX_URI t0 WHERE (t0.HASH_URI = ?)", sql); // Query 2 - Load resourece contents sql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(1).getSql(false, false); - assertThat(sql, containsString("where resourcese0_.RES_ID in (?)")); + assertThat(sql, containsString("where rsv1_0.RES_ID in (?)")); assertThat(toUnqualifiedVersionlessIds(outcome), Matchers.contains(id)); diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4UpdateTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4UpdateTest.java index 44ae538e139..4f04779cdb8 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4UpdateTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirResourceDaoR4UpdateTest.java @@ -45,7 +45,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import javax.persistence.Id; +import jakarta.persistence.Id; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirSystemDaoR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirSystemDaoR4Test.java index 671416c2cba..988421f7cc7 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirSystemDaoR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/FhirSystemDaoR4Test.java @@ -4008,7 +4008,7 @@ public class FhirSystemDaoR4Test extends BaseJpaR4SystemTest { try { mySystemDao.transaction(mySrd, b); } catch (ResourceVersionConflictException e) { - assertEquals(Msg.code(550) + Msg.code(550) + Msg.code(989) + "Trying to update Patient/P1/_history/2 but this is not the current version", e.getMessage()); + assertEquals(Msg.code(550) + Msg.code(989) + "Trying to update Patient/P1/_history/2 but this is not the current version", e.getMessage()); } b = new Bundle(); diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/PartitioningSqlR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/PartitioningSqlR4Test.java index eabd086087b..42004dba52f 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/PartitioningSqlR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/dao/r4/PartitioningSqlR4Test.java @@ -876,7 +876,7 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { ourLog.info("Search SQL:\n{}", searchSql); // Only the read columns should be used, no criteria use partition - assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID as ")); + assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID,")); assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID")); } { @@ -888,7 +888,7 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { ourLog.info("Search SQL:\n{}", searchSql); // Only the read columns should be used, no criteria use partition - assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID as ")); + assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID,")); assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID")); } } @@ -910,7 +910,7 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { ourLog.info("Search SQL:\n{}", searchSql); // Only the read columns should be used, no criteria use partition - assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID as "), searchSql); + assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID,"), searchSql); assertEquals(1, StringUtils.countMatches(searchSql, "PARTITION_ID='1'"), searchSql); } @@ -954,7 +954,7 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { // Only the read columns should be used, but no selectors on partition ID String searchSql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, true); - assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID as "), searchSql); + assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID,"), searchSql); assertEquals(1, StringUtils.countMatches(searchSql, "PARTITION_ID in ("), searchSql); } @@ -967,7 +967,7 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { // Only the read columns should be used, but no selectors on partition ID String searchSql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, true); - assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID as "), searchSql); + assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID,"), searchSql); assertEquals(1, StringUtils.countMatches(searchSql, "PARTITION_ID is null"), searchSql); } @@ -1008,7 +1008,7 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { // Only the read columns should be used, but no selectors on partition ID String searchSql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, true); - assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID as "), searchSql); + assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID,"), searchSql); assertEquals(1, StringUtils.countMatches(searchSql, "PARTITION_ID in ("), searchSql); } @@ -1022,7 +1022,7 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { // Only the read columns should be used, but no selectors on partition ID String searchSql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, true); - assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID as "), searchSql); + assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID,"), searchSql); assertEquals(1, StringUtils.countMatches(searchSql, "PARTITION_ID is null"), searchSql); } @@ -1064,7 +1064,7 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { ourLog.info("Search SQL:\n{}", searchSql); // Only the read columns should be used, no criteria use partition - assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID as ")); + assertEquals(2, StringUtils.countMatches(searchSql, "PARTITION_ID,")); assertEquals(1, StringUtils.countMatches(searchSql, "PARTITION_ID is null")); } @@ -2827,8 +2827,8 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { ourLog.debug("Resp: {}", myFhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome)); myCaptureQueriesListener.logSelectQueriesForCurrentThread(); assertEquals(2, myCaptureQueriesListener.countSelectQueriesForCurrentThread()); - assertThat(myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, false), containsString("esourcein0_.PARTITION_ID in ('1')")); - assertThat(myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, false), containsString("HASH_SYS_AND_VALUE in ('7432183691485874662' , '-3772330830566471409'")); + assertThat(myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, false), containsString("rispt1_0.PARTITION_ID in ('1')")); + assertThat(myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, false), containsString("rispt1_0.HASH_SYS_AND_VALUE in ('7432183691485874662','-3772330830566471409','-4132452001562191669')")); myCaptureQueriesListener.logInsertQueriesForCurrentThread(); assertEquals(45, myCaptureQueriesListener.countInsertQueriesForCurrentThread()); myCaptureQueriesListener.logUpdateQueriesForCurrentThread(); @@ -2986,12 +2986,12 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { // Fetch history resource searchSql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(1).getSql(true, true); ourLog.info("SQL:{}", searchSql); - assertEquals(1, countMatches(searchSql, "PARTITION_ID in"), searchSql); + assertEquals(1, countMatches(searchSql, "rht1_0.PARTITION_ID in"), searchSql); // Fetch history resource searchSql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(2).getSql(true, true); ourLog.info("SQL:{}", searchSql); - assertEquals(1, countMatches(searchSql, "PARTITION_ID in"), searchSql.replace(" ", "").toUpperCase()); + assertEquals(1, countMatches(searchSql, "rht1_0.PARTITION_ID in"), searchSql.replace(" ", "").toUpperCase()); } @Test @@ -3103,12 +3103,12 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { ourLog.info("SQL:{}", myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, true)); String sql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, false).toUpperCase(); assertEquals(1, countMatches(sql, "COUNT("), sql); - assertEquals(1, countMatches(sql, "PARTITION_ID IN ('1')"), sql); + assertEquals(1, countMatches(sql, "RHT1_0.PARTITION_ID IN ('1')"), sql); // Fetch history sql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(1).getSql(true, false).toUpperCase(); ourLog.info("SQL:{}", sql); - assertEquals(1, countMatches(sql, "PARTITION_ID IN ('1')"), sql); + assertEquals(1, countMatches(sql, "RHT1_0.PARTITION_ID IN ('1')"), sql); } @@ -3134,7 +3134,7 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { // Count String searchSql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, true); ourLog.info("SQL:{}", searchSql); - assertEquals(1, countMatches(searchSql, "PARTITION_ID is null"), searchSql); + assertEquals(1, countMatches(searchSql, "rht1_0.PARTITION_ID is null"), searchSql); // Fetch history resource searchSql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(1).getSql(true, true); @@ -3213,12 +3213,12 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { String sql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, false).toUpperCase(); ourLog.info("SQL:{}", sql); assertEquals(1, countMatches(sql, "COUNT("), sql); - assertEquals(1, countMatches(sql, "PARTITION_ID IN ('1')"), sql); + assertEquals(1, countMatches(sql, "RHT1_0.PARTITION_ID IN ('1')"), sql); // History sql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(1).getSql(true, false).toUpperCase(); ourLog.info("SQL:{}", sql); - assertEquals(1, countMatches(sql, "PARTITION_ID IN ('1')"), sql); + assertEquals(1, countMatches(sql, "RHT1_0.PARTITION_ID IN ('1')"), sql); } @@ -3244,12 +3244,12 @@ public class PartitioningSqlR4Test extends BasePartitioningR4Test { // Resolve resource String sql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(0).getSql(true, true).toUpperCase(); - assertEquals(1, countMatches(sql, "PARTITION_ID IS NULL")); + assertEquals(1, countMatches(sql, "RHT1_0.PARTITION_ID IS NULL"), sql); assertEquals(1, countMatches(sql, "PARTITION_ID")); // Fetch history resource sql = myCaptureQueriesListener.getSelectQueriesForCurrentThread().get(1).getSql(true, true).toUpperCase(); - assertEquals(1, countMatches(sql, "PARTITION_ID IS NULL")); + assertEquals(1, countMatches(sql, "RHT1_0.PARTITION_ID IS NULL"), sql); } diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/delete/job/ReindexJobTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/delete/job/ReindexJobTest.java index 8492091e342..b53ac1ef305 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/delete/job/ReindexJobTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/delete/job/ReindexJobTest.java @@ -30,8 +30,8 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; -import javax.annotation.PostConstruct; -import javax.persistence.Query; +import jakarta.annotation.PostConstruct; +import jakarta.persistence.Query; import java.util.Date; import java.util.List; import java.util.stream.Stream; @@ -448,6 +448,9 @@ public class ReindexJobTest extends BaseJpaR4Test { @Test public void testReindex_withReindexingUponSearchParameterChangeEnabled_reindexJobCompleted() { + List jobInstances = myJobPersistence.fetchInstancesByJobDefinitionId(ReindexAppCtx.JOB_REINDEX, 10, 0); + assertEquals(0, jobInstances.size()); + // make sure the resources auto-reindex after the search parameter update is enabled myStorageSettings.setMarkResourcesForReindexingUponSearchParameterChange(true); @@ -456,7 +459,7 @@ public class ReindexJobTest extends BaseJpaR4Test { myReindexTestHelper.createCodeSearchParameter(); // check that reindex job was created - List jobInstances = myJobPersistence.fetchInstancesByJobDefinitionId(ReindexAppCtx.JOB_REINDEX, 10, 0); + jobInstances = myJobPersistence.fetchInstancesByJobDefinitionId(ReindexAppCtx.JOB_REINDEX, 10, 0); assertEquals(1, jobInstances.size()); // check that the job is completed (not stuck in QUEUED status) diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/CascadingDeleteInterceptorMultiThreadTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/CascadingDeleteInterceptorMultiThreadTest.java index 211b2456d85..e990c57ef1d 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/CascadingDeleteInterceptorMultiThreadTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/CascadingDeleteInterceptorMultiThreadTest.java @@ -30,8 +30,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Encounter; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/ForceOffsetSearchModeInterceptorTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/ForceOffsetSearchModeInterceptorTest.java index 945f6f19472..9892649972c 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/ForceOffsetSearchModeInterceptorTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/ForceOffsetSearchModeInterceptorTest.java @@ -63,7 +63,7 @@ public class ForceOffsetSearchModeInterceptorTest extends BaseResourceProviderR4 myCaptureQueriesListener.logSelectQueries(); assertEquals(2, myCaptureQueriesListener.countSelectQueries()); assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("SELECT t0.RES_ID FROM HFJ_SPIDX_TOKEN t0")); - assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("limit '6'")); + assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("fetch first '6' rows only")); assertEquals(0, myCaptureQueriesListener.countInsertQueries()); assertEquals(0, myCaptureQueriesListener.countUpdateQueries()); assertEquals(0, myCaptureQueriesListener.countDeleteQueries()); @@ -88,7 +88,7 @@ public class ForceOffsetSearchModeInterceptorTest extends BaseResourceProviderR4 myCaptureQueriesListener.logSelectQueries(); assertEquals(2, myCaptureQueriesListener.countSelectQueries()); assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("SELECT t0.RES_ID FROM HFJ_SPIDX_TOKEN t0")); - assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("limit '6'")); + assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("fetch next '6' rows only")); assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("offset '5'")); assertEquals(0, myCaptureQueriesListener.countInsertQueries()); assertEquals(0, myCaptureQueriesListener.countUpdateQueries()); @@ -149,7 +149,7 @@ public class ForceOffsetSearchModeInterceptorTest extends BaseResourceProviderR4 myCaptureQueriesListener.logSelectQueries(); assertEquals(2, myCaptureQueriesListener.countSelectQueries()); assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("SELECT t0.RES_ID FROM HFJ_SPIDX_TOKEN t0")); - assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("limit '8'")); + assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("fetch first '8' rows only")); assertEquals(0, myCaptureQueriesListener.countInsertQueries()); assertEquals(0, myCaptureQueriesListener.countUpdateQueries()); assertEquals(0, myCaptureQueriesListener.countDeleteQueries()); @@ -172,7 +172,7 @@ public class ForceOffsetSearchModeInterceptorTest extends BaseResourceProviderR4 myCaptureQueriesListener.logSelectQueries(); assertEquals(2, myCaptureQueriesListener.countSelectQueries()); assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("SELECT t0.RES_ID FROM HFJ_SPIDX_TOKEN t0")); - assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("limit '8'")); + assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(true, false), containsString("fetch next '8' rows only")); assertEquals(0, myCaptureQueriesListener.countInsertQueries()); assertEquals(0, myCaptureQueriesListener.countUpdateQueries()); assertEquals(0, myCaptureQueriesListener.countDeleteQueries()); diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/PartitioningInterceptorR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/PartitioningInterceptorR4Test.java index 8bf59f3fd96..9e80739a522 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/PartitioningInterceptorR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/PartitioningInterceptorR4Test.java @@ -39,7 +39,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/PatientIdPartitionInterceptorTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/PatientIdPartitionInterceptorTest.java index 75eb2f79d01..0e432bbcee5 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/PatientIdPartitionInterceptorTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/interceptor/PatientIdPartitionInterceptorTest.java @@ -181,8 +181,8 @@ public class PatientIdPartitionInterceptorTest extends BaseJpaR4SystemTest { assertTrue(patient.getActive()); myCaptureQueriesListener.logSelectQueries(); assertEquals(3, myCaptureQueriesListener.getSelectQueries().size()); - assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(false, false), containsString("resourceta0_.PARTITION_ID in (?)")); - assertThat(myCaptureQueriesListener.getSelectQueries().get(1).getSql(false, false), containsString("where resourceta0_.PARTITION_ID=? and resourceta0_.RES_ID=?")); + assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(false, false), containsString("rt1_0.PARTITION_ID in (?)")); + assertThat(myCaptureQueriesListener.getSelectQueries().get(1).getSql(false, false), containsString("where rt1_0.PARTITION_ID=? and rt1_0.RES_ID=?")); } @Test @@ -229,7 +229,7 @@ public class PatientIdPartitionInterceptorTest extends BaseJpaR4SystemTest { assertEquals(1, outcome.size()); myCaptureQueriesListener.logSelectQueries(); assertEquals(3, myCaptureQueriesListener.getSelectQueries().size()); - assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(false, false), containsString("resourceta0_.PARTITION_ID in (?)")); + assertThat(myCaptureQueriesListener.getSelectQueries().get(0).getSql(false, false), containsString("rt1_0.PARTITION_ID in (?)")); assertThat(myCaptureQueriesListener.getSelectQueries().get(1).getSql(false, false), containsString("t0.PARTITION_ID = ?")); } diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/NpmR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/NpmR4Test.java index 799e6133124..a6a129549e0 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/NpmR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/NpmR4Test.java @@ -26,12 +26,13 @@ import ca.uhn.fhir.rest.server.interceptor.partition.RequestTenantPartitionInter import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.test.utilities.JettyUtil; import ca.uhn.fhir.test.utilities.ProxyUtil; +import ca.uhn.fhir.test.utilities.server.HttpServletExtension; import ca.uhn.fhir.util.ClasspathUtil; import ca.uhn.fhir.util.JsonUtil; import ca.uhn.fhir.validation.ValidationResult; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.r4.model.Enumerations; @@ -51,6 +52,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.RegisterExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -90,18 +92,20 @@ public class NpmR4Test extends BaseJpaR4Test { private IHapiPackageCacheManager myPackageCacheManager; @Autowired private NpmJpaValidationSupport myNpmJpaValidationSupport; - private Server myServer; @Autowired private INpmPackageDao myPackageDao; @Autowired private INpmPackageVersionDao myPackageVersionDao; @Autowired private INpmPackageVersionResourceDao myPackageVersionResourceDao; - private FakeNpmServlet myFakeNpmServlet; @Autowired private IInterceptorService myInterceptorService; @Autowired private RequestTenantPartitionInterceptor myRequestTenantPartitionInterceptor; + private FakeNpmServlet myFakeNpmServlet = new FakeNpmServlet(); + @RegisterExtension + public HttpServletExtension myServer = new HttpServletExtension() + .withServlet(myFakeNpmServlet); @Override @BeforeEach @@ -110,17 +114,8 @@ public class NpmR4Test extends BaseJpaR4Test { JpaPackageCache jpaPackageCache = ProxyUtil.getSingletonTarget(myPackageCacheManager, JpaPackageCache.class); - myServer = new Server(0); - ServletHandler proxyHandler = new ServletHandler(); - myFakeNpmServlet = new FakeNpmServlet(); - ServletHolder servletHolder = new ServletHolder(myFakeNpmServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - myServer.setHandler(proxyHandler); - myServer.start(); - - int port = JettyUtil.getPortForStartedServer(myServer); jpaPackageCache.getPackageServers().clear(); - String url = "http://localhost:" + port; + String url = myServer.getBaseUrl(); ourLog.info("Package server is at base: {}", url); jpaPackageCache.addPackageServer(new PackageServer(url)); @@ -129,7 +124,6 @@ public class NpmR4Test extends BaseJpaR4Test { @AfterEach public void after() throws Exception { - JettyUtil.closeServer(myServer); myStorageSettings.setAllowExternalReferences(new JpaStorageSettings().isAllowExternalReferences()); myStorageSettings.setAutoCreatePlaceholderReferenceTargets(new JpaStorageSettings().isAutoCreatePlaceholderReferenceTargets()); myPartitionSettings.setPartitioningEnabled(false); @@ -219,7 +213,7 @@ public class NpmR4Test extends BaseJpaR4Test { myPackageInstallerSvc.install(spec); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); // Make sure we can fetch the package by ID and Version NpmPackage pkg = myPackageCacheManager.loadPackage("nictiz.fhir.nl.stu3.questionnaires", "1.0.2"); @@ -262,7 +256,7 @@ public class NpmR4Test extends BaseJpaR4Test { assertEquals(1, outcome.getResourcesInstalled().get("CodeSystem")); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); // Make sure we can fetch the package by ID and Version NpmPackage pkg = myPackageCacheManager.loadPackage("hl7.fhir.uv.shorthand", "0.12.0"); @@ -332,7 +326,7 @@ public class NpmR4Test extends BaseJpaR4Test { assertEquals(1, outcome.getResourcesInstalled().get("CodeSystem")); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); // Make sure we can fetch the package by ID and Version NpmPackage pkg = myPackageCacheManager.loadPackage("hl7.fhir.uv.shorthand", "0.12.0"); @@ -402,7 +396,7 @@ public class NpmR4Test extends BaseJpaR4Test { PackageInstallationSpec spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.13.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL); PackageInstallOutcomeJson outcome = myPackageInstallerSvc.install(spec); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); // Search for the installed resource runInTransaction(() -> { @@ -431,7 +425,7 @@ public class NpmR4Test extends BaseJpaR4Test { assertEquals(3, outcome.getResourcesInstalled().get("Organization")); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); // Search for the installed resources runInTransaction(() -> { @@ -471,7 +465,7 @@ public class NpmR4Test extends BaseJpaR4Test { assertEquals(3, outcome.getResourcesInstalled().get("Organization")); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); // Search for the installed resources mySrd = mock(ServletRequestDetails.class); @@ -540,7 +534,7 @@ public class NpmR4Test extends BaseJpaR4Test { assertEquals(1, outcome.getResourcesInstalled().get("ImplementationGuide")); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); // Search for the installed resources runInTransaction(() -> { @@ -621,7 +615,7 @@ public class NpmR4Test extends BaseJpaR4Test { myPackageInstallerSvc.install(spec); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); // Make sure we can fetch the package by ID and Version NpmPackage pkg = myPackageCacheManager.loadPackage("UK.Core.r4", "1.1.0"); @@ -930,7 +924,7 @@ public class NpmR4Test extends BaseJpaR4Test { assertEquals(2, outcome.getResourcesInstalled().get("StructureDefinition")); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); // Search for the installed resource runInTransaction(() -> { @@ -967,7 +961,7 @@ public class NpmR4Test extends BaseJpaR4Test { assertEquals(2, outcome.getResourcesInstalled().get("StructureDefinition")); // Be sure no further communication with the server - JettyUtil.closeServer(myServer); + myServer.stopServer(); // Search for the installed resource runInTransaction(() -> { diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/NpmSearchR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/NpmSearchR4Test.java index b8c8a28d8ca..aa06e958181 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/NpmSearchR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/NpmSearchR4Test.java @@ -36,8 +36,10 @@ public class NpmSearchR4Test extends BaseJpaR4Test { @Autowired private INpmPackageVersionResourceDao myPackageVersionResourceDao; + @Override @BeforeEach public void before() throws Exception { + super.before(); JpaPackageCache jpaPackageCache = ProxyUtil.getSingletonTarget(myPackageCacheManager, JpaPackageCache.class); jpaPackageCache.getPackageServers().clear(); } @@ -155,7 +157,7 @@ public class NpmSearchR4Test extends BaseJpaR4Test { search = myPackageCacheManager.search(searchSpec); myCaptureQueriesListener.logSelectQueriesForCurrentThread(); - ourLog.info("Search rersults:\r{}", JsonUtil.serialize(search)); + ourLog.info("Search results:\r{}", JsonUtil.serialize(search)); assertEquals(1, search.getTotal()); assertEquals("hl7.fhir.uv.shorthand", search.getObjects().get(0).getPackage().getName()); assertEquals("4.0.1", search.getObjects().get(0).getPackage().getFhirVersion().get(0)); diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/loader/PackageLoaderSvcIT.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/loader/PackageLoaderSvcIT.java index b6df9a61732..3c26a4ec46f 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/loader/PackageLoaderSvcIT.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/packages/loader/PackageLoaderSvcIT.java @@ -4,16 +4,18 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jpa.packages.FakeNpmServlet; import ca.uhn.fhir.jpa.packages.util.PackageUtils; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.HttpServletExtension; import ca.uhn.fhir.util.ClasspathUtil; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.utilities.npm.NpmPackage; import org.hl7.fhir.utilities.npm.PackageServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mockito; import org.mockito.Spy; @@ -32,40 +34,23 @@ public class PackageLoaderSvcIT { @Spy private FhirContext myFhirContext = FhirContext.forR4Cached(); + private FakeNpmServlet myFakeNpmServlet = new FakeNpmServlet(); + private PackageLoaderSvc myPackageLoaderSvc = new PackageLoaderSvc(); + private PackageResourceParsingSvc myResourceParsingSvc = new PackageResourceParsingSvc(myFhirContext); - private Server myServer; - - private FakeNpmServlet myFakeNpmServlet; - - private PackageLoaderSvc myPackageLoaderSvc; - - private PackageResourceParsingSvc myResourceParsingSvc; + @RegisterExtension + public HttpServletExtension myServer = new HttpServletExtension() + .withServlet(myFakeNpmServlet); @BeforeEach public void before() throws Exception { - myPackageLoaderSvc = new PackageLoaderSvc(); - myResourceParsingSvc = new PackageResourceParsingSvc(myFhirContext); - myServer = new Server(0); - ServletHandler proxyHandler = new ServletHandler(); - myFakeNpmServlet = new FakeNpmServlet(); - ServletHolder servletHolder = new ServletHolder(myFakeNpmServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - myServer.setHandler(proxyHandler); - myServer.start(); - - int port = JettyUtil.getPortForStartedServer(myServer); myPackageLoaderSvc.getPackageServers().clear(); - myPackageLoaderSvc.addPackageServer(new PackageServer("http://localhost:" + port)); + myPackageLoaderSvc.addPackageServer(new PackageServer(myServer.getBaseUrl())); myFakeNpmServlet.getResponses().clear(); } - @AfterEach - public void after() throws Exception { - JettyUtil.closeServer(myServer); - } - @Test public void fetchPackageFromServer_thenParseoutResources_inMemory() throws IOException { // setup diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/partition/PartitionedSubscriptionTriggeringR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/partition/PartitionedSubscriptionTriggeringR4Test.java index 1def4fbd776..cfec106c08a 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/partition/PartitionedSubscriptionTriggeringR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/partition/PartitionedSubscriptionTriggeringR4Test.java @@ -30,7 +30,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/EmptyIndexesR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/EmptyIndexesR4Test.java index 8619423aa9c..f84f607ef89 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/EmptyIndexesR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/EmptyIndexesR4Test.java @@ -15,8 +15,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.Observation; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/MultitenantServerR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/MultitenantServerR4Test.java index 139f4df1e5a..e96a313c7a4 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/MultitenantServerR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/MultitenantServerR4Test.java @@ -54,7 +54,7 @@ import org.mockito.Mock; import org.mockito.Spy; import org.springframework.mock.web.MockHttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/RemoteTerminologyServiceResourceProviderR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/RemoteTerminologyServiceResourceProviderR4Test.java index a02443b3f09..4e543edd508 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/RemoteTerminologyServiceResourceProviderR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/RemoteTerminologyServiceResourceProviderR4Test.java @@ -27,7 +27,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderCustomSearchParamR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderCustomSearchParamR4Test.java index d5ac558d272..f6b9cd4b9df 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderCustomSearchParamR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderCustomSearchParamR4Test.java @@ -401,6 +401,9 @@ public class ResourceProviderCustomSearchParamR4Test extends BaseResourceProvide fooSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE); mySearchParameterDao.create(fooSp, mySrd); + mySearchParamRegistry.forceRefresh(); + assertNotNull(mySearchParamRegistry.getActiveSearchParam("Patient", "foo")); + Patient pat = new Patient(); pat.setGender(AdministrativeGender.MALE); IIdType patId = myPatientDao.create(pat, mySrd).getId().toUnqualifiedVersionless(); @@ -547,8 +550,9 @@ public class ResourceProviderCustomSearchParamR4Test extends BaseResourceProvide ourLog.info("Found: {}", found); runInTransaction(() -> { - List currentResults = myEntityManager.createNativeQuery("select distinct resourceta0_.RES_ID as col_0_0_ from HFJ_RESOURCE resourceta0_ left outer join HFJ_SPIDX_STRING myparamsst1_ on resourceta0_.RES_ID=myparamsst1_.RES_ID where myparamsst1_.HASH_NORM_PREFIX='5901791607832193956' and (myparamsst1_.SP_VALUE_NORMALIZED like 'SECTION%') limit '500'").getResultList(); - List currentResources = myEntityManager.createNativeQuery("select resourceta0_.RES_ID as col_0_0_ from HFJ_RESOURCE resourceta0_").getResultList(); + + List currentResults = myEntityManager.createNativeQuery("select distinct r1_0.RES_ID as col_0_0_ from HFJ_RESOURCE r1_0 left outer join HFJ_SPIDX_STRING myparamsst1_ on r1_0.RES_ID=myparamsst1_.RES_ID where myparamsst1_.HASH_NORM_PREFIX='5901791607832193956' and (myparamsst1_.SP_VALUE_NORMALIZED like 'SECTION%') limit '500'").getResultList(); + List currentResources = myEntityManager.createNativeQuery("select r1_0.RES_ID as col_0_0_ from HFJ_RESOURCE r1_0").getResultList(); List searches = mySearchEntityDao.findAll(); assertEquals(1, searches.size()); diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderInterceptorR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderInterceptorR4Test.java index 2e17f8d2780..7f3a0e06819 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderInterceptorR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderInterceptorR4Test.java @@ -46,7 +46,7 @@ import org.mockito.Captor; import org.mockito.Mock; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderOnlySomeResourcesProvidedR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderOnlySomeResourcesProvidedR4Test.java index a1d3c5fd1bf..cc8a4b237ba 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderOnlySomeResourcesProvidedR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderOnlySomeResourcesProvidedR4Test.java @@ -13,8 +13,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4RemoteTerminologyTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4RemoteTerminologyTest.java index b2cfe855dbd..0198b2c7ee9 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4RemoteTerminologyTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4RemoteTerminologyTest.java @@ -32,7 +32,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4Test.java index 722cc8ae8e1..b0a5e6ed236 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4Test.java @@ -1,5 +1,6 @@ package ca.uhn.fhir.jpa.provider.r4; +import ca.uhn.fhir.context.RuntimeSearchParam; import ca.uhn.fhir.i18n.HapiLocalizer; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; @@ -369,15 +370,20 @@ public class ResourceProviderR4Test extends BaseResourceProviderR4Test { IFhirResourceDao searchParameterDao = myDaoRegistry.getResourceDao(SearchParameter.class); searchParameterDao.create(searchParameter, (RequestDetails) null); + RuntimeSearchParam sp = mySearchParamRegistry.getActiveSearchParam("Organization", "_profile"); + assertNotNull(sp); + IFhirResourceDao organizationDao = myDaoRegistry.getResourceDao(Organization.class); Organization organizationWithNoProfile = new Organization(); organizationWithNoProfile.setName("noProfile"); - organizationDao.create(organizationWithNoProfile); + organizationDao.create(organizationWithNoProfile, mySrd); + myCaptureQueriesListener.clear(); Organization organizationWithProfile = new Organization(); organizationWithProfile.setName("withProfile"); organizationWithProfile.getMeta().addProfile("http://foo"); - organizationDao.create(organizationWithProfile); + organizationDao.create(organizationWithProfile, mySrd); + myCaptureQueriesListener.logInsertQueries(); runInTransaction(() -> { List matched = myResourceIndexedSearchParamUriDao.findAll().stream() @@ -942,12 +948,14 @@ public class ResourceProviderR4Test extends BaseResourceProviderR4Test { ourLog.info("About to perform search for: {}", theUri); + myCaptureQueriesListener.clear(); try (CloseableHttpResponse response = ourHttpClient.execute(get)) { String resp = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(resp); Bundle bundle = myFhirContext.newXmlParser().parseResource(Bundle.class, resp); ids = toUnqualifiedIdValues(bundle); } + myCaptureQueriesListener.logSelectQueries(true, true); return ids; } diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4ValueSetNoVerCSNoVerTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4ValueSetNoVerCSNoVerTest.java index 7b69cc6a741..35e96b1ea41 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4ValueSetNoVerCSNoVerTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4ValueSetNoVerCSNoVerTest.java @@ -1075,7 +1075,7 @@ public class ResourceProviderR4ValueSetNoVerCSNoVerTest extends BaseResourceProv .execute(); ourLog.debug(myFhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(expansion)); assertThat(toDirectCodes(expansion.getExpansion().getContains()), containsInAnyOrder("A", "AA", "AB", "AAA")); - assertEquals(12, myCaptureQueriesListener.getSelectQueries().size()); + assertEquals(14, myCaptureQueriesListener.getSelectQueries().size(), ()->myCaptureQueriesListener.logSelectQueries().stream().map(t->t.getSql(true, false)).collect(Collectors.joining("\n * "))); assertEquals("ValueSet \"ValueSet.url[http://example.com/my_value_set]\" has not yet been pre-expanded. Performing in-memory expansion without parameters. Current status: NOT_EXPANDED | The ValueSet is waiting to be picked up and pre-expanded by a scheduled task.", expansion.getMeta().getExtensionString(EXT_VALUESET_EXPANSION_MESSAGE)); // Hierarchical @@ -1092,7 +1092,7 @@ public class ResourceProviderR4ValueSetNoVerCSNoVerTest extends BaseResourceProv assertThat(toDirectCodes(expansion.getExpansion().getContains()), containsInAnyOrder("A")); assertThat(toDirectCodes(expansion.getExpansion().getContains().get(0).getContains()), containsInAnyOrder("AA", "AB")); assertThat(toDirectCodes(expansion.getExpansion().getContains().get(0).getContains().stream().filter(t -> t.getCode().equals("AA")).findFirst().orElseThrow(() -> new IllegalArgumentException()).getContains()), containsInAnyOrder("AAA")); - assertEquals(13, myCaptureQueriesListener.getSelectQueries().size()); + assertEquals(15, myCaptureQueriesListener.getSelectQueries().size()); } @@ -1115,7 +1115,7 @@ public class ResourceProviderR4ValueSetNoVerCSNoVerTest extends BaseResourceProv .execute(); ourLog.debug(myFhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(expansion)); assertThat(toDirectCodes(expansion.getExpansion().getContains()), containsInAnyOrder("A", "AA", "AB", "AAA")); - assertEquals(8, myCaptureQueriesListener.getSelectQueries().size()); + assertEquals(10, myCaptureQueriesListener.getSelectQueries().size(), ()->myCaptureQueriesListener.logSelectQueries().stream().map(t->t.getSql(true, false)).collect(Collectors.joining("\n * "))); assertEquals("ValueSet with URL \"Unidentified ValueSet\" was expanded using an in-memory expansion", expansion.getMeta().getExtensionString(EXT_VALUESET_EXPANSION_MESSAGE)); // Hierarchical @@ -1132,7 +1132,7 @@ public class ResourceProviderR4ValueSetNoVerCSNoVerTest extends BaseResourceProv assertThat(toDirectCodes(expansion.getExpansion().getContains()), containsInAnyOrder("A")); assertThat(toDirectCodes(expansion.getExpansion().getContains().get(0).getContains()), containsInAnyOrder("AA", "AB")); assertThat(toDirectCodes(expansion.getExpansion().getContains().get(0).getContains().stream().filter(t -> t.getCode().equals("AA")).findFirst().orElseThrow(() -> new IllegalArgumentException()).getContains()), containsInAnyOrder("AAA")); - assertEquals(11, myCaptureQueriesListener.getSelectQueries().size()); + assertEquals(13, myCaptureQueriesListener.getSelectQueries().size()); } diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SubscriptionsR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SubscriptionsR4Test.java index d9a45aa3658..889027665a8 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SubscriptionsR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SubscriptionsR4Test.java @@ -6,8 +6,8 @@ import ca.uhn.fhir.jpa.util.SubscriptionsRequireManualActivationInterceptorR4; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; +import org.eclipse.jetty.websocket.api.annotations.OnWebSocketOpen; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; @@ -186,7 +186,7 @@ public class SubscriptionsR4Test extends BaseResourceProviderR4Test { /** * Basic Echo Client Socket */ - @WebSocket(maxTextMessageSize = 64 * 1024) + @WebSocket public class DynamicEchoSocket extends BaseSocket { private String myCriteria; @@ -200,14 +200,14 @@ public class SubscriptionsR4Test extends BaseResourceProviderR4Test { myEncoding = theEncoding; } - @OnWebSocketConnect + @OnWebSocketOpen public void onConnect(Session session) { ourLog.info("Got connect: {}", session); this.session = session; try { String sending = "bind " + myCriteria; ourLog.info("Sending: {}", sending); - session.getRemote().sendString(sending); + session.sendText(sending, null); } catch (Throwable t) { ourLog.error("Failure", t); } @@ -234,7 +234,7 @@ public class SubscriptionsR4Test extends BaseResourceProviderR4Test { /** * Basic Echo Client Socket */ - @WebSocket(maxTextMessageSize = 64 * 1024) + @WebSocket public class SimpleEchoSocket extends BaseSocket { @SuppressWarnings("unused") @@ -244,14 +244,14 @@ public class SubscriptionsR4Test extends BaseResourceProviderR4Test { mySubsId = theSubsId; } - @OnWebSocketConnect + @OnWebSocketOpen public void onConnect(Session session) { ourLog.info("Got connect: {}", session); this.session = session; try { String sending = "bind " + mySubsId; ourLog.info("Sending: {}", sending); - session.getRemote().sendString(sending); + session.sendText(sending, null); } catch (Throwable t) { ourLog.error("Failure", t); } diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SystemProviderR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SystemProviderR4Test.java index 13a54906716..2e7b101b234 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SystemProviderR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SystemProviderR4Test.java @@ -57,8 +57,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.common.hapi.validation.validator.FhirInstanceValidator; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.instance.model.api.IIdType; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SystemProviderTransactionSearchR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SystemProviderTransactionSearchR4Test.java index 016e3de04e6..5a293f5610a 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SystemProviderTransactionSearchR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/provider/r4/SystemProviderTransactionSearchR4Test.java @@ -20,8 +20,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; import org.hl7.fhir.r4.model.Bundle.BundleType; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/stresstest/GiantTransactionPerfTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/stresstest/GiantTransactionPerfTest.java index ef4e4b36e2b..4aceb1748cc 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/stresstest/GiantTransactionPerfTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/stresstest/GiantTransactionPerfTest.java @@ -79,20 +79,20 @@ import org.springframework.transaction.support.TransactionSynchronizationManager import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.persistence.EntityGraph; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.FlushModeType; -import javax.persistence.LockModeType; -import javax.persistence.Query; -import javax.persistence.StoredProcedureQuery; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaDelete; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.CriteriaUpdate; -import javax.persistence.metamodel.Metamodel; +import jakarta.persistence.EntityGraph; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityTransaction; +import jakarta.persistence.FlushModeType; +import jakarta.persistence.LockModeType; +import jakarta.persistence.Query; +import jakarta.persistence.StoredProcedureQuery; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaDelete; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.CriteriaUpdate; +import jakarta.persistence.metamodel.Metamodel; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -181,6 +181,7 @@ public class GiantTransactionPerfTest { myHapiTransactionService.setTransactionManager(myTransactionManager); myHapiTransactionService.setInterceptorBroadcaster(myInterceptorSvc); myHapiTransactionService.setRequestPartitionSvcForUnitTest(myRequestPartitionHelperSvc); + myHapiTransactionService.setPartitionSettingsForUnitTest(new PartitionSettings()); myTransactionProcessor = new TransactionProcessor(); myTransactionProcessor.setContext(ourFhirContext); diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR4Test.java index 1b315cdca30..cd9eeecf4b2 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR4Test.java @@ -35,7 +35,7 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.beans.factory.annotation.Autowired; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.ArrayList; import java.util.Collections; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookActivatesPreExistingSubscriptionsR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookActivatesPreExistingSubscriptionsR4Test.java index b4f22254adb..f5e504131f4 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookActivatesPreExistingSubscriptionsR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookActivatesPreExistingSubscriptionsR4Test.java @@ -13,8 +13,8 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.test.utilities.JettyUtil; import com.google.common.collect.Lists; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.CodeableConcept; import org.hl7.fhir.r4.model.Coding; @@ -30,7 +30,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsR4Test.java index 1cd12d66bce..3410c4877a7 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/subscription/resthook/RestHookTestWithInterceptorRegisteredToStorageSettingsR4Test.java @@ -15,8 +15,8 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.test.utilities.JettyUtil; import com.google.common.collect.Lists; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.CodeableConcept; import org.hl7.fhir.r4.model.Coding; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/ITermReadSvcTest.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/ITermReadSvcTest.java index 43dd37135fb..95f6f583f31 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/ITermReadSvcTest.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/ITermReadSvcTest.java @@ -49,8 +49,8 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.data.domain.Pageable; import org.springframework.test.util.ReflectionTestUtils; -import javax.persistence.EntityManager; -import javax.persistence.NonUniqueResultException; +import jakarta.persistence.EntityManager; +import jakarta.persistence.NonUniqueResultException; import javax.sql.DataSource; import java.util.Arrays; import java.util.Collections; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/TerminologySvcImplCurrentVersionR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/TerminologySvcImplCurrentVersionR4Test.java index 17cdf197835..e3d7d61c031 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/TerminologySvcImplCurrentVersionR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/TerminologySvcImplCurrentVersionR4Test.java @@ -39,8 +39,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.io.ClassPathResource; -import javax.persistence.EntityManager; -import javax.servlet.http.HttpServletResponse; +import jakarta.persistence.EntityManager; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; diff --git a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/hsearch/ReindexTerminologyHSearchR4Test.java b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/hsearch/ReindexTerminologyHSearchR4Test.java index 92a19636014..623c94d6f34 100644 --- a/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/hsearch/ReindexTerminologyHSearchR4Test.java +++ b/hapi-fhir-jpaserver-test-r4/src/test/java/ca/uhn/fhir/jpa/term/hsearch/ReindexTerminologyHSearchR4Test.java @@ -34,7 +34,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.util.ResourceUtils; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; diff --git a/hapi-fhir-jpaserver-test-r4b/pom.xml b/hapi-fhir-jpaserver-test-r4b/pom.xml index df49d1e866a..e2d784822f9 100644 --- a/hapi-fhir-jpaserver-test-r4b/pom.xml +++ b/hapi-fhir-jpaserver-test-r4b/pom.xml @@ -6,7 +6,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-jpaserver-test-r4b/src/test/java/ca/uhn/fhir/jpa/dao/r4b/BaseJpaR4BTest.java b/hapi-fhir-jpaserver-test-r4b/src/test/java/ca/uhn/fhir/jpa/dao/r4b/BaseJpaR4BTest.java index d3268b3f732..0a275e83112 100644 --- a/hapi-fhir-jpaserver-test-r4b/src/test/java/ca/uhn/fhir/jpa/dao/r4b/BaseJpaR4BTest.java +++ b/hapi-fhir-jpaserver-test-r4b/src/test/java/ca/uhn/fhir/jpa/dao/r4b/BaseJpaR4BTest.java @@ -124,7 +124,7 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.io.IOException; import java.util.List; import java.util.Optional; diff --git a/hapi-fhir-jpaserver-test-r4b/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR4BTest.java b/hapi-fhir-jpaserver-test-r4b/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR4BTest.java index bd551395c22..d645cd43e0f 100644 --- a/hapi-fhir-jpaserver-test-r4b/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR4BTest.java +++ b/hapi-fhir-jpaserver-test-r4b/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR4BTest.java @@ -35,7 +35,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Nonnull; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.ArrayList; import java.util.Collections; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-r5/pom.xml b/hapi-fhir-jpaserver-test-r5/pom.xml index 3e7ea400eca..ec884ead8bb 100644 --- a/hapi-fhir-jpaserver-test-r5/pom.xml +++ b/hapi-fhir-jpaserver-test-r5/pom.xml @@ -6,7 +6,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/dao/r5/BaseJpaR5Test.java b/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/dao/r5/BaseJpaR5Test.java index aa65349989c..1ef5161e6ab 100644 --- a/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/dao/r5/BaseJpaR5Test.java +++ b/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/dao/r5/BaseJpaR5Test.java @@ -133,7 +133,7 @@ import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; diff --git a/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/dao/r5/FhirSystemDaoTransactionR5Test.java b/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/dao/r5/FhirSystemDaoTransactionR5Test.java index fcd1bf9dc0e..308d97c70f6 100644 --- a/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/dao/r5/FhirSystemDaoTransactionR5Test.java +++ b/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/dao/r5/FhirSystemDaoTransactionR5Test.java @@ -92,7 +92,7 @@ public class FhirSystemDaoTransactionR5Test extends BaseJpaR5Test { // One select to resolve the 3 match URLs assertEquals(1, myCaptureQueriesListener.countSelectQueriesForCurrentThread()); String firstSelectQuery = myCaptureQueriesListener.getSelectQueries().get(0).getSql(false, false); - assertEquals(1, countMatches(firstSelectQuery, "HASH_SYS_AND_VALUE in (? , ? , ? , ?)"), firstSelectQuery); + assertEquals(1, countMatches(firstSelectQuery, "rispt1_0.HASH_SYS_AND_VALUE in (?,?,?,?)"), firstSelectQuery); assertEquals(23, myCaptureQueriesListener.countInsertQueriesForCurrentThread()); assertEquals(3, myCaptureQueriesListener.countUpdateQueriesForCurrentThread()); assertEquals(0, myCaptureQueriesListener.countDeleteQueriesForCurrentThread()); diff --git a/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR5Test.java b/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR5Test.java index a39f187b5ae..ea35ecdf076 100644 --- a/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR5Test.java +++ b/hapi-fhir-jpaserver-test-r5/src/test/java/ca/uhn/fhir/jpa/subscription/BaseSubscriptionsR5Test.java @@ -27,8 +27,8 @@ import ca.uhn.test.concurrency.PointcutLatch; import net.ttddyy.dsproxy.QueryCount; import net.ttddyy.dsproxy.listener.SingleQueryCountHolder; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.r5.model.Bundle; @@ -45,8 +45,8 @@ import org.junit.jupiter.api.Disabled; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Nonnull; -import javax.annotation.PostConstruct; -import javax.servlet.http.HttpServletRequest; +import jakarta.annotation.PostConstruct; +import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; diff --git a/hapi-fhir-jpaserver-test-utilities/pom.xml b/hapi-fhir-jpaserver-test-utilities/pom.xml index a1bf33ca001..8b56c9eac09 100644 --- a/hapi-fhir-jpaserver-test-utilities/pom.xml +++ b/hapi-fhir-jpaserver-test-utilities/pom.xml @@ -6,7 +6,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -85,42 +85,6 @@ org.apache.derby derby - - org.eclipse.jetty - jetty-servlets - - - org.eclipse.jetty - jetty-servlet - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-util - - - org.eclipse.jetty - jetty-webapp - - - org.eclipse.jetty.websocket - websocket-jetty-api - - - org.eclipse.jetty.websocket - websocket-core-client - - - org.eclipse.jetty.websocket - websocket-jetty-client - - - org.eclipse.jetty.websocket - websocket-jetty-server - org.springframework.boot spring-boot-test @@ -215,17 +179,21 @@ mockito-core - com.helger - ph-schematron + com.helger.schematron + ph-schematron-api - com.helger - ph-commons + com.helger.schematron + ph-schematron-xslt org.testcontainers junit-jupiter + + jakarta.websocket + jakarta.websocket-client-api + com.jayway.jsonpath diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/embedded/HapiEmbeddedDatabasesExtension.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/embedded/HapiEmbeddedDatabasesExtension.java index 4b09d4fd13c..697f6a96f7c 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/embedded/HapiEmbeddedDatabasesExtension.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/embedded/HapiEmbeddedDatabasesExtension.java @@ -20,6 +20,7 @@ package ca.uhn.fhir.jpa.embedded; import ca.uhn.fhir.jpa.migrate.DriverTypeEnum; +import ca.uhn.fhir.test.utilities.docker.DockerRequiredCondition; import ca.uhn.fhir.util.VersionEnum; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; @@ -51,20 +52,24 @@ public class HapiEmbeddedDatabasesExtension implements AfterAllCallback { private final DatabaseInitializerHelper myDatabaseInitializerHelper = new DatabaseInitializerHelper(); public HapiEmbeddedDatabasesExtension() { - myEmbeddedDatabases.add(new H2EmbeddedDatabase()); - myEmbeddedDatabases.add(new PostgresEmbeddedDatabase()); - myEmbeddedDatabases.add(new MsSqlEmbeddedDatabase()); - if (canUseOracle()) { - myEmbeddedDatabases.add(new OracleEmbeddedDatabase()); + if (DockerRequiredCondition.isDockerAvailable()) { + myEmbeddedDatabases.add(new H2EmbeddedDatabase()); + myEmbeddedDatabases.add(new PostgresEmbeddedDatabase()); + myEmbeddedDatabases.add(new MsSqlEmbeddedDatabase()); + if (canUseOracle()) { + myEmbeddedDatabases.add(new OracleEmbeddedDatabase()); + } else { + String message = + "Cannot add OracleEmbeddedDatabase. If you are using a Mac you must configure the TestContainers API to run using Colima (https://www.testcontainers.org/supported_docker_environment#using-colima)"; + ourLog.warn(message); + } } else { - String message = - "Cannot add OracleEmbeddedDatabase. If you are using a Mac you must configure the TestContainers API to run using Colima (https://www.testcontainers.org/supported_docker_environment#using-colima)"; - ourLog.warn(message); + ourLog.warn("Docker is not available! Not going to start any embedded databases."); } } @Override - public void afterAll(ExtensionContext theExtensionContext) throws Exception { + public void afterAll(ExtensionContext theExtensionContext) { for (JpaEmbeddedDatabase database : getAllEmbeddedDatabases()) { database.stop(); } diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/interceptor/ex/PartitionInterceptorReadPartitionsBasedOnScopes.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/interceptor/ex/PartitionInterceptorReadPartitionsBasedOnScopes.java index 588ffa0cb2e..256c57078a9 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/interceptor/ex/PartitionInterceptorReadPartitionsBasedOnScopes.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/interceptor/ex/PartitionInterceptorReadPartitionsBasedOnScopes.java @@ -25,9 +25,9 @@ import ca.uhn.fhir.interceptor.api.Pointcut; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; +import jakarta.servlet.http.HttpServletRequest; import java.util.Set; -import javax.servlet.http.HttpServletRequest; // This class is replicated in PartitionExamples.java -- Keep it up to date there too!! @Interceptor diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/packages/FakeNpmServlet.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/packages/FakeNpmServlet.java index 7a0e28df80c..dbc29a6d8bf 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/packages/FakeNpmServlet.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/packages/FakeNpmServlet.java @@ -20,6 +20,9 @@ package ca.uhn.fhir.jpa.packages; import ca.uhn.fhir.rest.api.Constants; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,9 +30,6 @@ import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; public class FakeNpmServlet extends HttpServlet { private static final Logger ourLog = LoggerFactory.getLogger(FakeNpmServlet.class); diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/provider/CodeSystemLookupWithPropertiesUtil.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/provider/CodeSystemLookupWithPropertiesUtil.java index feedbd05f0e..baf2b8c623f 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/provider/CodeSystemLookupWithPropertiesUtil.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/provider/CodeSystemLookupWithPropertiesUtil.java @@ -1,3 +1,22 @@ +/*- + * #%L + * HAPI FHIR JPA Server Test Utilities + * %% + * Copyright (C) 2014 - 2023 Smile CDR, Inc. + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ package ca.uhn.fhir.jpa.provider; import org.junit.jupiter.params.provider.Arguments; diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/provider/r4/BaseResourceProviderR4Test.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/provider/r4/BaseResourceProviderR4Test.java index 943fa6bbd81..7e4b86df570 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/provider/r4/BaseResourceProviderR4Test.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/provider/r4/BaseResourceProviderR4Test.java @@ -49,9 +49,9 @@ import ca.uhn.fhir.test.utilities.JettyUtil; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; import org.hl7.fhir.r4.model.Parameters; diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/subscription/NotificationServlet.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/subscription/NotificationServlet.java index 825c0edff25..780eab57d4d 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/subscription/NotificationServlet.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/subscription/NotificationServlet.java @@ -19,15 +19,16 @@ */ package ca.uhn.fhir.jpa.subscription; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicLong; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; /** * Receives subscription notification without payloads. diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/subscription/SocketImplementation.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/subscription/SocketImplementation.java index c4e67c55b92..2d52a950cd2 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/subscription/SocketImplementation.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/subscription/SocketImplementation.java @@ -20,17 +20,17 @@ package ca.uhn.fhir.jpa.subscription; import ca.uhn.fhir.rest.api.EncodingEnum; -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; -import org.eclipse.jetty.websocket.api.annotations.WebSocket; +import jakarta.websocket.ClientEndpoint; +import jakarta.websocket.OnMessage; +import jakarta.websocket.OnOpen; +import jakarta.websocket.Session; import org.slf4j.Logger; import java.util.ArrayList; import java.util.Collections; import java.util.List; -@WebSocket +@ClientEndpoint public class SocketImplementation { private static final Logger ourLog = org.slf4j.LoggerFactory.getLogger(SocketImplementation.class); @@ -53,7 +53,7 @@ public class SocketImplementation { public void keepAlive() { if (this.session != null) { try { - session.getRemote().sendString("keep alive"); + session.getBasicRemote().sendText("keep alive"); } catch (Throwable t) { ourLog.error("Failure", t); } @@ -66,14 +66,14 @@ public class SocketImplementation { * * @param session */ - @OnWebSocketConnect + @OnOpen public void onConnect(Session session) { ourLog.info("Got connect: {}", session); this.session = session; try { String sending = "bind " + myCriteria; ourLog.info("Sending: {}", sending); - session.getRemote().sendString(sending); + session.getBasicRemote().sendText(sending); ourLog.info("Connection: DONE"); } catch (Throwable t) { @@ -87,7 +87,7 @@ public class SocketImplementation { * * @param theMsg */ - @OnWebSocketMessage + @OnMessage public void onMessage(String theMsg) { ourLog.info("Got msg: " + theMsg); myMessages.add(theMsg); diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaDstu3Test.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaDstu3Test.java index a699670da89..b43ccc2172e 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaDstu3Test.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaDstu3Test.java @@ -129,7 +129,7 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionTemplate; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.util.Map; @ExtendWith(SpringExtension.class) diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaR4Test.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaR4Test.java index a0d630c9b12..68813b7c4d5 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaR4Test.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaR4Test.java @@ -20,6 +20,8 @@ package ca.uhn.fhir.jpa.test; import ca.uhn.fhir.batch2.jobs.export.BulkDataExportProvider; +import ca.uhn.fhir.batch2.jobs.reindex.ReindexAppCtx; +import ca.uhn.fhir.batch2.model.JobInstance; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.support.IValidationSupport; import ca.uhn.fhir.interceptor.api.IInterceptorService; @@ -39,6 +41,8 @@ import ca.uhn.fhir.jpa.binary.interceptor.BinaryStorageInterceptor; import ca.uhn.fhir.jpa.binary.provider.BinaryAccessProvider; import ca.uhn.fhir.jpa.bulk.export.api.IBulkDataExportJobSchedulingHelper; import ca.uhn.fhir.jpa.dao.IFulltextSearchSvc; +import ca.uhn.fhir.jpa.dao.data.IBatch2JobInstanceRepository; +import ca.uhn.fhir.jpa.dao.data.IBatch2WorkChunkRepository; import ca.uhn.fhir.jpa.dao.data.IForcedIdDao; import ca.uhn.fhir.jpa.dao.data.IMdmLinkJpaRepository; import ca.uhn.fhir.jpa.dao.data.IPartitionDao; @@ -98,6 +102,7 @@ import ca.uhn.fhir.jpa.test.config.TestR4Config; import ca.uhn.fhir.jpa.util.MemoryCacheService; import ca.uhn.fhir.jpa.util.ResourceCountCache; import ca.uhn.fhir.jpa.validation.ValidationSettings; +import ca.uhn.fhir.mdm.interceptor.MdmStorageInterceptor; import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.parser.StrictErrorHandler; import ca.uhn.fhir.rest.api.Constants; @@ -199,7 +204,7 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.PlatformTransactionManager; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -240,6 +245,10 @@ public abstract class BaseJpaR4Test extends BaseJpaTest implements ITestDataBuil protected ITermCodeSystemStorageSvc myTermCodeSystemStorageSvc; @Autowired protected ISearchDao mySearchEntityDao; + @Autowired + private IBatch2JobInstanceRepository myJobInstanceRepository; + @Autowired + private IBatch2WorkChunkRepository myWorkChunkRepository; @Autowired protected ISearchIncludeDao mySearchIncludeEntityDao; @@ -533,6 +542,10 @@ public abstract class BaseJpaR4Test extends BaseJpaTest implements ITestDataBuil private IBulkDataExportJobSchedulingHelper myBulkDataScheduleHelper; @Autowired protected IResourceSearchUrlDao myResourceSearchUrlDao; + @Autowired + private IInterceptorService myInterceptorService; + @Autowired(required = false) + private MdmStorageInterceptor myMdmStorageInterceptor; @RegisterExtension private final PreventDanglingInterceptorsExtension myPreventDanglingInterceptorsExtension = new PreventDanglingInterceptorsExtension(()-> myInterceptorRegistry); @@ -594,11 +607,28 @@ public abstract class BaseJpaR4Test extends BaseJpaTest implements ITestDataBuil @AfterEach public void afterPurgeDatabase() { - runInTransaction(() -> { - myMdmLinkHistoryDao.deleteAll(); - myMdmLinkDao.deleteAll(); - }); - purgeDatabase(myStorageSettings, mySystemDao, myResourceReindexingSvc, mySearchCoordinatorSvc, mySearchParamRegistry, myBulkDataScheduleHelper); + boolean registeredStorageInterceptor = false; + if (myMdmStorageInterceptor != null && !myInterceptorService.getAllRegisteredInterceptors().contains(myMdmStorageInterceptor)) { + myInterceptorService.registerInterceptor(myMdmStorageInterceptor); + registeredStorageInterceptor = true; + } + try { + runInTransaction(() -> { + myMdmLinkHistoryDao.deleteAll(); + myMdmLinkDao.deleteAll(); + }); + purgeDatabase(myStorageSettings, mySystemDao, myResourceReindexingSvc, mySearchCoordinatorSvc, mySearchParamRegistry, myBulkDataScheduleHelper); + + myBatch2JobHelper.cancelAllJobsAndAwaitCancellation(); + runInTransaction(() -> { + myWorkChunkRepository.deleteAll(); + myJobInstanceRepository.deleteAll(); + }); + } finally { + if (registeredStorageInterceptor) { + myInterceptorService.unregisterInterceptor(myMdmStorageInterceptor); + } + } } @BeforeEach diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaTest.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaTest.java index 9edc49122a3..4dcc9189da1 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaTest.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseJpaTest.java @@ -130,7 +130,7 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.io.IOException; import java.time.Duration; import java.time.temporal.ChronoUnit; diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseValueSetHSearchExpansionR4Test.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseValueSetHSearchExpansionR4Test.java index bc8facbfec4..fb7b241ebc5 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseValueSetHSearchExpansionR4Test.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/BaseValueSetHSearchExpansionR4Test.java @@ -76,7 +76,7 @@ import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import java.util.ArrayList; import java.util.Arrays; import java.util.List; diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestDstu2Config.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestDstu2Config.java index ad9e8ebf4ce..39ab80ce66f 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestDstu2Config.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestDstu2Config.java @@ -21,6 +21,7 @@ package ca.uhn.fhir.jpa.test.config; import ca.uhn.fhir.batch2.jobs.config.Batch2JobsConfig; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; import ca.uhn.fhir.jpa.batch2.JpaBatch2Config; import ca.uhn.fhir.jpa.config.HapiJpaConfig; import ca.uhn.fhir.jpa.config.JpaDstu2Config; @@ -57,6 +58,7 @@ import java.sql.SQLException; import java.util.Properties; import java.util.concurrent.TimeUnit; +import static ca.uhn.fhir.jpa.test.config.TestR5Config.SELECT_QUERY_INCLUSION_CRITERIA_EXCLUDING_SEQUENCE_QUERIES; import static org.junit.jupiter.api.Assertions.fail; @Configuration @@ -95,7 +97,8 @@ public class TestDstu2Config { @Bean public CircularQueueCaptureQueriesListener captureQueriesListener() { - return new CircularQueueCaptureQueriesListener(); + return new CircularQueueCaptureQueriesListener() + .setSelectQueryInclusionCriteria(SELECT_QUERY_INCLUSION_CRITERIA_EXCLUDING_SEQUENCE_QUERIES); } @Bean @@ -169,8 +172,8 @@ public class TestDstu2Config { } @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { - LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext); + public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext, JpaStorageSettings theStorageSettings) { + LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaDstu2"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestDstu3Config.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestDstu3Config.java index 08515a33a31..521aa935c90 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestDstu3Config.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestDstu3Config.java @@ -21,6 +21,7 @@ package ca.uhn.fhir.jpa.test.config; import ca.uhn.fhir.batch2.jobs.config.Batch2JobsConfig; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; import ca.uhn.fhir.jpa.batch2.JpaBatch2Config; import ca.uhn.fhir.jpa.config.HapiJpaConfig; import ca.uhn.fhir.jpa.config.PackageLoaderConfig; @@ -61,6 +62,7 @@ import java.sql.Connection; import java.util.Properties; import java.util.concurrent.TimeUnit; +import static ca.uhn.fhir.jpa.test.config.TestR5Config.SELECT_QUERY_INCLUSION_CRITERIA_EXCLUDING_SEQUENCE_QUERIES; import static org.junit.jupiter.api.Assertions.fail; @Configuration @@ -82,7 +84,8 @@ public class TestDstu3Config { @Bean public CircularQueueCaptureQueriesListener captureQueriesListener() { - return new CircularQueueCaptureQueriesListener(); + return new CircularQueueCaptureQueriesListener() + .setSelectQueryInclusionCriteria(SELECT_QUERY_INCLUSION_CRITERIA_EXCLUDING_SEQUENCE_QUERIES); } @Bean @@ -180,8 +183,8 @@ public class TestDstu3Config { } @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { - LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext); + public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext, JpaStorageSettings theStorageSettings) { + LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaDstu3"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestHSearchAddInConfig.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestHSearchAddInConfig.java index eefbc9e8139..532f8636507 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestHSearchAddInConfig.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestHSearchAddInConfig.java @@ -44,7 +44,7 @@ import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Primary; import org.testcontainers.elasticsearch.ElasticsearchContainer; -import javax.annotation.PreDestroy; +import jakarta.annotation.PreDestroy; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestHapiJpaConfig.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestHapiJpaConfig.java index 5ce4a94655d..10fb896beed 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestHapiJpaConfig.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestHapiJpaConfig.java @@ -1,3 +1,22 @@ +/*- + * #%L + * HAPI FHIR JPA Server Test Utilities + * %% + * Copyright (C) 2014 - 2023 Smile CDR, Inc. + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ package ca.uhn.fhir.jpa.test.config; import ca.uhn.fhir.jpa.config.HapiJpaConfig; diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestJPAConfig.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestJPAConfig.java index 4c334819646..716ceccd079 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestJPAConfig.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestJPAConfig.java @@ -47,7 +47,7 @@ import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Primary; import org.springframework.orm.jpa.JpaTransactionManager; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManagerFactory; @Configuration @Import({ diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR4BConfig.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR4BConfig.java index e6473f15647..0cf3d61f1a0 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR4BConfig.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR4BConfig.java @@ -21,6 +21,7 @@ package ca.uhn.fhir.jpa.test.config; import ca.uhn.fhir.batch2.jobs.config.Batch2JobsConfig; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; import ca.uhn.fhir.jpa.batch2.JpaBatch2Config; import ca.uhn.fhir.jpa.binary.api.IBinaryStorageSvc; import ca.uhn.fhir.jpa.binstore.MemoryBinaryStorageSvcImpl; @@ -64,6 +65,7 @@ import java.util.LinkedList; import java.util.Properties; import java.util.concurrent.TimeUnit; +import static ca.uhn.fhir.jpa.test.config.TestR5Config.SELECT_QUERY_INCLUSION_CRITERIA_EXCLUDING_SEQUENCE_QUERIES; import static org.junit.jupiter.api.Assertions.fail; @Configuration @@ -106,7 +108,8 @@ public class TestR4BConfig { @Bean public CircularQueueCaptureQueriesListener captureQueriesListener() { - return new CircularQueueCaptureQueriesListener(); + return new CircularQueueCaptureQueriesListener() + .setSelectQueryInclusionCriteria(SELECT_QUERY_INCLUSION_CRITERIA_EXCLUDING_SEQUENCE_QUERIES); } @Bean @@ -212,8 +215,8 @@ public class TestR4BConfig { @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { - LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext); + public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext, JpaStorageSettings theStorageSettings) { + LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaR4B"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR4Config.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR4Config.java index 98942ba4d5a..d61a4670331 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR4Config.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR4Config.java @@ -21,6 +21,7 @@ package ca.uhn.fhir.jpa.test.config; import ca.uhn.fhir.batch2.jobs.config.Batch2JobsConfig; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; import ca.uhn.fhir.jpa.batch2.JpaBatch2Config; import ca.uhn.fhir.jpa.binary.api.IBinaryStorageSvc; import ca.uhn.fhir.jpa.binstore.MemoryBinaryStorageSvcImpl; @@ -52,12 +53,20 @@ import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; import java.util.Deque; +import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.LinkedList; +import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import static ca.uhn.fhir.jpa.test.config.TestR5Config.SELECT_QUERY_INCLUSION_CRITERIA_EXCLUDING_SEQUENCE_QUERIES; import static org.junit.jupiter.api.Assertions.fail; @Configuration @@ -75,6 +84,8 @@ public class TestR4Config { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(TestR4Config.class); public static Integer ourMaxThreads; + private final AtomicInteger myBorrowedConnectionCount = new AtomicInteger(0); + private final AtomicInteger myReturnedConnectionCount = new AtomicInteger(0); static { /* @@ -95,14 +106,18 @@ public class TestR4Config { ourLog.warn("ourMaxThreads={}", ourMaxThreads); } - private final Deque myLastStackTrace = new LinkedList<>(); + private Map myConnectionRequestStackTraces = Collections.synchronizedMap(new LinkedHashMap<>()); + @Autowired TestHSearchAddInConfig.IHSearchConfigurer hibernateSearchConfigurer; private boolean myHaveDumpedThreads; + @Autowired + private JpaStorageSettings myStorageSettings; @Bean public CircularQueueCaptureQueriesListener captureQueriesListener() { - return new CircularQueueCaptureQueriesListener(); + return new CircularQueueCaptureQueriesListener() + .setSelectQueryInclusionCriteria(SELECT_QUERY_INCLUSION_CRITERIA_EXCLUDING_SEQUENCE_QUERIES); } @Bean @@ -116,6 +131,7 @@ public class TestR4Config { retVal = new ConnectionWrapper(super.getConnection()); } catch (Exception e) { ourLog.error("Exceeded maximum wait for connection (" + ourMaxThreads + " max)", e); + ourLog.info("Have {} outstanding - {} borrowed {} returned", (myBorrowedConnectionCount.get() - myReturnedConnectionCount.get()), myBorrowedConnectionCount.get(), myReturnedConnectionCount.get()); logGetConnectionStackTrace(); fail("Exceeded maximum wait for connection (" + ourMaxThreads + " max): " + e); retVal = null; @@ -124,38 +140,42 @@ public class TestR4Config { try { throw new Exception(); } catch (Exception e) { - synchronized (myLastStackTrace) { - myLastStackTrace.add(e); - while (myLastStackTrace.size() > ourMaxThreads) { - myLastStackTrace.removeFirst(); - } - } + myConnectionRequestStackTraces.put(retVal, e); } - return retVal; + myBorrowedConnectionCount.incrementAndGet(); + ConnectionWrapper finalRetVal = retVal; + return new ConnectionWrapper(finalRetVal){ + @Override + public void close() throws SQLException { + myConnectionRequestStackTraces.remove(finalRetVal); + myReturnedConnectionCount.incrementAndGet(); + super.close(); + } + }; } private void logGetConnectionStackTrace() { StringBuilder b = new StringBuilder(); - int i = 0; - synchronized (myLastStackTrace) { - for (Iterator iter = myLastStackTrace.descendingIterator(); iter.hasNext(); ) { - Exception nextStack = iter.next(); - b.append("\n\nPrevious request stack trace "); - b.append(i++); + ArrayList stackTraces = new ArrayList<>(myConnectionRequestStackTraces.values()); + + for (int i = 0; i < stackTraces.size(); i++) { + Exception nextStack = stackTraces.get(i); + b.append("\nPrevious request stack trace "); + b.append(i); + b.append(":"); + for (StackTraceElement next : nextStack.getStackTrace()) { + b.append("\n "); + b.append(next.getClassName()); + b.append("."); + b.append(next.getMethodName()); + b.append("("); + b.append(next.getFileName()); b.append(":"); - for (StackTraceElement next : nextStack.getStackTrace()) { - b.append("\n "); - b.append(next.getClassName()); - b.append("."); - b.append(next.getMethodName()); - b.append("("); - b.append(next.getFileName()); - b.append(":"); - b.append(next.getLineNumber()); - b.append(")"); - } + b.append(next.getLineNumber()); + b.append(")"); } + b.append("\n"); } ourLog.info(b.toString()); @@ -208,8 +228,8 @@ public class TestR4Config { @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { - LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext); + public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext, JpaStorageSettings theStorageSettings) { + LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaR4"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR5Config.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR5Config.java index f4d46f5d342..10ca0859722 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR5Config.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/test/config/TestR5Config.java @@ -21,6 +21,7 @@ package ca.uhn.fhir.jpa.test.config; import ca.uhn.fhir.batch2.jobs.config.Batch2JobsConfig; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; import ca.uhn.fhir.jpa.batch2.JpaBatch2Config; import ca.uhn.fhir.jpa.binary.api.IBinaryStorageSvc; import ca.uhn.fhir.jpa.binstore.MemoryBinaryStorageSvcImpl; @@ -50,7 +51,9 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import javax.sql.DataSource; import java.sql.Connection; +import java.util.Locale; import java.util.Properties; +import java.util.function.Predicate; import static org.junit.jupiter.api.Assertions.fail; @@ -68,6 +71,7 @@ import static org.junit.jupiter.api.Assertions.fail; public class TestR5Config { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(TestR5Config.class); + public static final Predicate SELECT_QUERY_INCLUSION_CRITERIA_EXCLUDING_SEQUENCE_QUERIES = CircularQueueCaptureQueriesListener.DEFAULT_SELECT_INCLUSION_CRITERIA.and(t -> !t.toLowerCase(Locale.US).startsWith("select next value")); public static Integer ourMaxThreads; static { @@ -97,7 +101,8 @@ public class TestR5Config { @Bean public CircularQueueCaptureQueriesListener captureQueriesListener() { - return new CircularQueueCaptureQueriesListener(); + return new CircularQueueCaptureQueriesListener() + .setSelectQueryInclusionCriteria(SELECT_QUERY_INCLUSION_CRITERIA_EXCLUDING_SEQUENCE_QUERIES); } @Bean @@ -173,8 +178,8 @@ public class TestR5Config { } @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { - LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext); + public LocalContainerEntityManagerFactoryBean entityManagerFactory(ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext, JpaStorageSettings theStorageSettings) { + LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory(theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaR5"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/util/WebsocketSubscriptionClient.java b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/util/WebsocketSubscriptionClient.java index 62480239d6a..7c8232108ca 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/util/WebsocketSubscriptionClient.java +++ b/hapi-fhir-jpaserver-test-utilities/src/main/java/ca/uhn/fhir/jpa/util/WebsocketSubscriptionClient.java @@ -24,9 +24,9 @@ import ca.uhn.fhir.jpa.subscription.SocketImplementation; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; -import org.eclipse.jetty.websocket.client.WebSocketClient; +import jakarta.websocket.ClientEndpoint; +import jakarta.websocket.ContainerProvider; +import jakarta.websocket.WebSocketContainer; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.slf4j.Logger; @@ -34,15 +34,14 @@ import org.slf4j.LoggerFactory; import java.net.URI; import java.util.List; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +@ClientEndpoint public class WebsocketSubscriptionClient implements AfterEachCallback { private static final Logger ourLog = LoggerFactory.getLogger(WebsocketSubscriptionClient.class); private final Supplier myServerSupplier; private final Supplier myStorageSettings; - private WebSocketClient myWebSocketClient; + private jakarta.websocket.Session mySession; private SocketImplementation mySocketImplementation; /** @@ -64,20 +63,15 @@ public class WebsocketSubscriptionClient implements AfterEachCallback { RestfulServerExtension server = myServerSupplier.get(); assert server != null; - myWebSocketClient = new WebSocketClient(); mySocketImplementation = new SocketImplementation(theSubscriptionId, EncodingEnum.JSON); try { - myWebSocketClient.start(); URI echoUri = new URI("ws://localhost:" + server.getPort() + server.getWebsocketContextPath() + myStorageSettings.get().getWebsocketContextPath()); - ClientUpgradeRequest request = new ClientUpgradeRequest(); - ourLog.info("Connecting to : {}", echoUri); - Future connection; - connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request); - Session session = connection.get(20, TimeUnit.SECONDS); - ourLog.info("Connected to WS: {}", session.isOpen()); + WebSocketContainer container = ContainerProvider.getWebSocketContainer(); + mySession = container.connectToServer(mySocketImplementation, echoUri); + ourLog.info("Connected to WS: {}", mySession.isOpen()); } catch (Exception e) { throw new InternalErrorException(e); } @@ -85,9 +79,9 @@ public class WebsocketSubscriptionClient implements AfterEachCallback { @Override public void afterEach(ExtensionContext theExtensionContext) throws Exception { - if (myWebSocketClient != null) { + if (mySession != null) { ourLog.info("Shutting down websocket client"); - myWebSocketClient.stop(); + mySession.close(); } } diff --git a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/DispatcherServletConfig.java b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/DispatcherServletConfig.java index 8fb525d7509..26ae8841f28 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/DispatcherServletConfig.java +++ b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/DispatcherServletConfig.java @@ -1,6 +1,6 @@ package ca.uhn.fhir.jpa.config; -import javax.el.ExpressionFactory; +import jakarta.el.ExpressionFactory; import org.springframework.context.annotation.Configuration; diff --git a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/HapiFhirHibernateJpaDialectTest.java b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/HapiFhirHibernateJpaDialectTest.java index aa12360a223..7a283a495b1 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/HapiFhirHibernateJpaDialectTest.java +++ b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/config/HapiFhirHibernateJpaDialectTest.java @@ -13,7 +13,7 @@ import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; -import javax.persistence.PersistenceException; +import jakarta.persistence.PersistenceException; import java.sql.SQLException; import static org.hamcrest.MatcherAssert.assertThat; @@ -57,7 +57,7 @@ public class HapiFhirHibernateJpaDialectTest { } outcome = mySvc.convertHibernateAccessException(new HibernateException("this is a message")); - assertThat(outcome.getMessage(), containsString("HibernateException: this is a message")); + assertThat(outcome.getMessage(), containsString("this is a message")); } diff --git a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/index/ResourceVersionSvcTest.java b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/index/ResourceVersionSvcTest.java index 1d55666e468..6d14d780291 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/index/ResourceVersionSvcTest.java +++ b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/index/ResourceVersionSvcTest.java @@ -21,11 +21,11 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Path; +import jakarta.persistence.criteria.Root; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; diff --git a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/embedded/HapiSchemaMigrationTest.java b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/embedded/HapiSchemaMigrationTest.java index 2783ea3439e..e6b023dd6e0 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/embedded/HapiSchemaMigrationTest.java +++ b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/embedded/HapiSchemaMigrationTest.java @@ -8,15 +8,18 @@ import ca.uhn.fhir.jpa.migrate.SchemaMigrator; import ca.uhn.fhir.jpa.migrate.dao.HapiMigrationDao; import ca.uhn.fhir.jpa.migrate.tasks.HapiFhirJpaMigrationTasks; import ca.uhn.fhir.system.HapiSystemProperties; +import ca.uhn.fhir.test.utilities.docker.RequiresDocker; import ca.uhn.fhir.util.VersionEnum; import org.apache.commons.dbcp2.BasicDataSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIf; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.testcontainers.junit.jupiter.Testcontainers; import javax.sql.DataSource; import java.sql.SQLException; @@ -30,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +@RequiresDocker public class HapiSchemaMigrationTest { private static final Logger ourLog = LoggerFactory.getLogger(HapiSchemaMigrationTest.class); diff --git a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/sched/SchedulerServiceImplIT.java b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/sched/SchedulerServiceImplTest.java similarity index 97% rename from hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/sched/SchedulerServiceImplIT.java rename to hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/sched/SchedulerServiceImplTest.java index 7d88e567953..7fc5187295b 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/sched/SchedulerServiceImplIT.java +++ b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/sched/SchedulerServiceImplTest.java @@ -36,12 +36,12 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThan; import static org.junit.jupiter.api.Assertions.fail; -@ContextConfiguration(classes = SchedulerServiceImplIT.TestConfiguration.class) +@ContextConfiguration(classes = SchedulerServiceImplTest.TestConfiguration.class) @ExtendWith(SpringExtension.class) @DirtiesContext -public class SchedulerServiceImplIT { +public class SchedulerServiceImplTest { - private static final Logger ourLog = LoggerFactory.getLogger(SchedulerServiceImplIT.class); + private static final Logger ourLog = LoggerFactory.getLogger(SchedulerServiceImplTest.class); public static final String SCHEDULED_JOB_ID = CountingJob.class.getName(); private static final AtomicInteger ourNameCounter = new AtomicInteger(); private static long ourTaskDelay; diff --git a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectMySqlTest.java b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectMySqlTest.java index af0b511a83e..3a77f72a620 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectMySqlTest.java +++ b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectMySqlTest.java @@ -1,5 +1,6 @@ package ca.uhn.fhir.jpa.search.builder.sql; +import ca.uhn.fhir.jpa.model.dialect.HapiFhirMySQLDialect; import ca.uhn.fhir.jpa.search.builder.predicate.BaseJoiningPredicateBuilder; import ca.uhn.fhir.jpa.search.builder.predicate.DatePredicateBuilder; import ca.uhn.fhir.jpa.search.builder.predicate.ResourceTablePredicateBuilder; @@ -147,6 +148,6 @@ public class SearchQueryBuilderDialectMySqlTest extends BaseSearchQueryBuilderDi @Nonnull @Override protected Dialect createDialect() { - return new org.hibernate.dialect.MySQL57Dialect(); + return new HapiFhirMySQLDialect(); } } diff --git a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectPostgresTest.java b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectPostgresTest.java index 07eca1057f3..6e0c1933963 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectPostgresTest.java +++ b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectPostgresTest.java @@ -2,12 +2,13 @@ package ca.uhn.fhir.jpa.search.builder.sql; import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; import ca.uhn.fhir.jpa.dao.predicate.SearchFilterParser; +import ca.uhn.fhir.jpa.model.dialect.HapiFhirPostgresDialect; import ca.uhn.fhir.jpa.search.builder.predicate.DatePredicateBuilder; import ca.uhn.fhir.rest.param.DateParam; import com.healthmarketscience.sqlbuilder.Condition; import org.apache.commons.lang3.StringUtils; import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.PostgreSQL10Dialect; +import org.hibernate.dialect.PostgreSQLDialect; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; @@ -45,7 +46,7 @@ public class SearchQueryBuilderDialectPostgresTest extends BaseSearchQueryBuilde logSql(generatedSql); String sql = generatedSql.getSql(); - assertEquals("SELECT t0.RES_ID FROM HFJ_SPIDX_DATE t0 WHERE ((t0.HASH_IDENTITY = ?) AND ((t0.SP_VALUE_LOW_DATE_ORDINAL >= ?) AND (t0.SP_VALUE_HIGH_DATE_ORDINAL <= ?))) limit ?", sql); + assertEquals("SELECT t0.RES_ID FROM HFJ_SPIDX_DATE t0 WHERE ((t0.HASH_IDENTITY = ?) AND ((t0.SP_VALUE_LOW_DATE_ORDINAL >= ?) AND (t0.SP_VALUE_HIGH_DATE_ORDINAL <= ?))) fetch first ? rows only", sql); assertEquals(4, StringUtils.countMatches(sql, "?")); assertEquals(4, generatedSql.getBindVariables().size()); @@ -58,6 +59,6 @@ public class SearchQueryBuilderDialectPostgresTest extends BaseSearchQueryBuilde @Nonnull @Override protected Dialect createDialect() { - return new PostgreSQL10Dialect(); + return new HapiFhirPostgresDialect(); } } diff --git a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectSqlServerTest.java b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectSqlServerTest.java index 2a6c042227b..f88e60cf7f6 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectSqlServerTest.java +++ b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderDialectSqlServerTest.java @@ -1,5 +1,6 @@ package ca.uhn.fhir.jpa.search.builder.sql; +import ca.uhn.fhir.jpa.model.dialect.HapiFhirSQLServerDialect; import ca.uhn.fhir.jpa.search.builder.predicate.ResourceTablePredicateBuilder; import org.apache.commons.lang3.StringUtils; import org.hibernate.dialect.Dialect; @@ -25,12 +26,19 @@ public class SearchQueryBuilderDialectSqlServerTest extends BaseSearchQueryBuild logSql(generatedSql); String sql = generatedSql.getSql(); - assertTrue(sql.endsWith("ORDER BY -t1.SP_VALUE_LOW DESC offset 0 rows fetch next ? rows only"), sql); + sql = massageSql(sql); + assertTrue(sql.endsWith("ORDER BY -t1.SP_VALUE_LOW DESC offset 0 rows fetch first ? rows only"), sql); assertEquals(3, StringUtils.countMatches(sql, "?")); assertEquals(3, generatedSql.getBindVariables().size()); } + @Nonnull + private static String massageSql(String sql) { + sql = sql.replace("\n", " ").replaceAll(" +", " "); + return sql; + } + @Test public void testRangeWithOffset() { SearchQueryBuilder searchQueryBuilder = createSearchQueryBuilder(); @@ -40,7 +48,8 @@ public class SearchQueryBuilderDialectSqlServerTest extends BaseSearchQueryBuild logSql(generatedSql); String sql = generatedSql.getSql(); - assertTrue(sql.endsWith("select page0_ from query where __row__ >= ? and __row__ < ?"), sql); + sql = massageSql(sql); + assertTrue(sql.endsWith("order by @@version offset ? rows fetch next ? rows only"), sql); assertEquals(3, StringUtils.countMatches(sql, "?")); assertEquals(3, generatedSql.getBindVariables().size()); @@ -55,7 +64,8 @@ public class SearchQueryBuilderDialectSqlServerTest extends BaseSearchQueryBuild logSql(generatedSql); String sql = generatedSql.getSql(); - assertTrue(sql.toUpperCase(Locale.ROOT).contains("SELECT TOP(?) T0.RES_ID FROM"), sql); + sql = massageSql(sql); + assertTrue(sql.endsWith("order by @@version offset 0 rows fetch first ? rows only"), sql); assertEquals(2, StringUtils.countMatches(sql, "?")); assertEquals(2, generatedSql.getBindVariables().size()); @@ -64,6 +74,6 @@ public class SearchQueryBuilderDialectSqlServerTest extends BaseSearchQueryBuild @Nonnull @Override protected Dialect createDialect() { - return new SQLServer2012Dialect(); + return new HapiFhirSQLServerDialect(); } } diff --git a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderTest.java b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderTest.java index 8821649c729..c0c1f0a8209 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderTest.java +++ b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/search/builder/sql/SearchQueryBuilderTest.java @@ -4,16 +4,16 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.config.HibernatePropertiesProvider; import ca.uhn.fhir.jpa.model.config.PartitionSettings; +import ca.uhn.fhir.jpa.model.dialect.HapiFhirMariaDBDialect; +import ca.uhn.fhir.jpa.model.dialect.HapiFhirOracleDialect; import ca.uhn.fhir.jpa.model.entity.StorageSettings; import ca.uhn.fhir.jpa.search.builder.predicate.ResourceTablePredicateBuilder; import com.google.common.collect.Lists; -import org.hibernate.dialect.DerbyTenSevenDialect; -import org.hibernate.dialect.MariaDB103Dialect; +import org.hibernate.dialect.DerbyDialect; import org.hibernate.dialect.MySQL8Dialect; -import org.hibernate.dialect.Oracle12cDialect; -import org.hibernate.dialect.PostgreSQL95Dialect; -import org.hibernate.dialect.SQLServer2005Dialect; +import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.dialect.SQLServer2012Dialect; +import org.hibernate.dialect.SQLServerDialect; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -54,7 +54,7 @@ public class SearchQueryBuilderTest { public void testRangeSqlServer2005_NoSort() { HibernatePropertiesProvider dialectProvider = new HibernatePropertiesProvider(); - dialectProvider.setDialectForUnitTest(new SQLServer2005Dialect()); + dialectProvider.setDialectForUnitTest(new SQLServerDialect()); SearchQueryBuilder builder = new SearchQueryBuilder(myFhirContext, myStorageSettings, myPartitionSettings, myRequestPartitionId, "Patient", mySqlBuilderFactory, dialectProvider, false); builder.addResourceIdsPredicate(Lists.newArrayList(500L, 501L)); GeneratedSql generated; @@ -66,13 +66,13 @@ public class SearchQueryBuilderTest { // Max only generated = builder.generate(null, 10); - assertEquals("SELECT TOP(?) T0.RES_ID FROM HFJ_RESOURCE T0 WHERE (((T0.RES_TYPE = ?) AND (T0.RES_DELETED_AT IS NULL)) AND (T0.RES_ID IN (?,?) ))", generated.getSql().toUpperCase(Locale.ROOT)); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains(10, "Patient", 500L, 501L)); + assertEquals("SELECT T0.RES_ID FROM HFJ_RESOURCE T0 WHERE (((T0.RES_TYPE = ?) AND (T0.RES_DELETED_AT IS NULL)) AND (T0.RES_ID IN (?,?) )) ORDER BY @@VERSION OFFSET 0 ROWS FETCH FIRST ? ROWS ONLY", generated.getSql().toUpperCase(Locale.ROOT)); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10)); // Range generated = builder.generate(10, 5); - assertEquals("with query as (select inner_query.*, row_number() over (order by current_timestamp) as __row__ from ( SELECT t0.RES_ID as page0_ FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ) inner_query ) select page0_ from query where __row__ >= ? and __row__ < ?", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 11, 16)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) order by @@version offset ? rows fetch next ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -80,7 +80,7 @@ public class SearchQueryBuilderTest { public void testRangeSqlServer2005_WithSort() { HibernatePropertiesProvider dialectProvider = new HibernatePropertiesProvider(); - dialectProvider.setDialectForUnitTest(new SQLServer2005Dialect()); + dialectProvider.setDialectForUnitTest(new SQLServerDialect()); SearchQueryBuilder builder = new SearchQueryBuilder(myFhirContext, myStorageSettings, myPartitionSettings, myRequestPartitionId, "Patient", mySqlBuilderFactory, dialectProvider, false); builder.addResourceIdsPredicate(Lists.newArrayList(500L, 501L)); builder.addSortDate(builder.getOrCreateResourceTablePredicateBuilder().getColumnLastUpdated(), true); @@ -88,21 +88,18 @@ public class SearchQueryBuilderTest { // No range generated = builder.generate(null, null); -// assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY CASE WHEN t0.RES_UPDATED IS NULL THEN 1 ELSE 0 END ASC, t0.RES_UPDATED ASC", generated.getSql()); assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L)); // Max only generated = builder.generate(null, 10); -// assertEquals("SELECT TOP(?) t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY CASE WHEN t0.RES_UPDATED IS NULL THEN 1 ELSE 0 END ASC, t0.RES_UPDATED ASC", generated.getSql()); - assertEquals("SELECT TOP(?) T0.RES_ID FROM HFJ_RESOURCE T0 WHERE (((T0.RES_TYPE = ?) AND (T0.RES_DELETED_AT IS NULL)) AND (T0.RES_ID IN (?,?) )) ORDER BY T0.RES_UPDATED ASC", generated.getSql().toUpperCase(Locale.ROOT)); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains(10, "Patient", 500L, 501L)); + assertEquals("SELECT T0.RES_ID FROM HFJ_RESOURCE T0 WHERE (((T0.RES_TYPE = ?) AND (T0.RES_DELETED_AT IS NULL)) AND (T0.RES_ID IN (?,?) )) ORDER BY T0.RES_UPDATED ASC OFFSET 0 ROWS FETCH FIRST ? ROWS ONLY", generated.getSql().toUpperCase(Locale.ROOT)); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10)); // Range generated = builder.generate(10, 5); -// assertEquals("WITH query AS (SELECT inner_query.*, ROW_NUMBER() OVER (ORDER BY CURRENT_TIMESTAMP) as __hibernate_row_nr__ FROM ( SELECT TOP(?) t0.RES_ID as page0_ FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY CASE WHEN t0.RES_UPDATED IS NULL THEN 1 ELSE 0 END ASC, t0.RES_UPDATED ASC ) inner_query ) SELECT page0_ FROM query WHERE __hibernate_row_nr__ >= ? AND __hibernate_row_nr__ < ?", generated.getSql()); - assertEquals("with query as (select inner_query.*, row_number() over (order by current_timestamp) as __row__ from ( SELECT top(?) t0.RES_ID as page0_ FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC ) inner_query ) select page0_ from query where __row__ >= ? and __row__ < ?", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains(5, "Patient", 500L, 501L, 11, 16)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC offset ? rows fetch next ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -123,13 +120,13 @@ public class SearchQueryBuilderTest { // Max only generated = builder.generate(null, 10); - assertEquals("SELECT TOP(?) T0.RES_ID FROM HFJ_RESOURCE T0 WHERE (((T0.RES_TYPE = ?) AND (T0.RES_DELETED_AT IS NULL)) AND (T0.RES_ID IN (?,?) ))", generated.getSql().toUpperCase(Locale.ROOT)); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains(10, "Patient", 500L, 501L)); + assertEquals("SELECT T0.RES_ID FROM HFJ_RESOURCE T0 WHERE (((T0.RES_TYPE = ?) AND (T0.RES_DELETED_AT IS NULL)) AND (T0.RES_ID IN (?,?) )) ORDER BY @@VERSION OFFSET 0 ROWS FETCH FIRST ? ROWS ONLY", generated.getSql().toUpperCase(Locale.ROOT)); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10)); // Range generated = builder.generate(10, 5); - assertEquals("with query as (select inner_query.*, row_number() over (order by current_timestamp) as __row__ from ( SELECT t0.RES_ID as page0_ FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ) inner_query ) select page0_ from query where __row__ >= ? and __row__ < ?", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 11, 16)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) order by @@version offset ? rows fetch next ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -145,19 +142,16 @@ public class SearchQueryBuilderTest { // No range generated = builder.generate(null, null); -// assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY CASE WHEN t0.RES_UPDATED IS NULL THEN 1 ELSE 0 END ASC, t0.RES_UPDATED ASC", generated.getSql()); assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L)); // Max only generated = builder.generate(null, 10); -// assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY CASE WHEN t0.RES_UPDATED IS NULL THEN 1 ELSE 0 END ASC, t0.RES_UPDATED ASC offset 0 rows fetch next ? rows only", generated.getSql()); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC offset 0 rows fetch next ? rows only", generated.getSql()); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC offset 0 rows fetch first ? rows only", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10)); // Range generated = builder.generate(10, 5); -// assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY CASE WHEN t0.RES_UPDATED IS NULL THEN 1 ELSE 0 END ASC, t0.RES_UPDATED ASC offset ? rows fetch next ? rows only", generated.getSql()); assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC offset ? rows fetch next ? rows only", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); @@ -167,7 +161,7 @@ public class SearchQueryBuilderTest { public void testRangePostgreSQL95_NoSort() { HibernatePropertiesProvider dialectProvider = new HibernatePropertiesProvider(); - dialectProvider.setDialectForUnitTest(new PostgreSQL95Dialect()); + dialectProvider.setDialectForUnitTest(new PostgreSQLDialect()); SearchQueryBuilder builder = new SearchQueryBuilder(myFhirContext, myStorageSettings, myPartitionSettings, myRequestPartitionId, "Patient", mySqlBuilderFactory, dialectProvider, false); builder.addResourceIdsPredicate(Lists.newArrayList(500L, 501L)); GeneratedSql generated; @@ -179,13 +173,13 @@ public class SearchQueryBuilderTest { // Max only generated = builder.generate(null, 10); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) limit ?", generated.getSql()); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) fetch first ? rows only", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10)); // Range generated = builder.generate(10, 5); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) limit ? offset ?", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 5, 10)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) offset ? rows fetch next ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -193,7 +187,7 @@ public class SearchQueryBuilderTest { public void testRangePostgreSQL95_WithSort() { HibernatePropertiesProvider dialectProvider = new HibernatePropertiesProvider(); - dialectProvider.setDialectForUnitTest(new PostgreSQL95Dialect()); + dialectProvider.setDialectForUnitTest(new PostgreSQLDialect()); SearchQueryBuilder builder = new SearchQueryBuilder(myFhirContext, myStorageSettings, myPartitionSettings, myRequestPartitionId, "Patient", mySqlBuilderFactory, dialectProvider, false); builder.addResourceIdsPredicate(Lists.newArrayList(500L, 501L)); builder.addSortDate(builder.getOrCreateResourceTablePredicateBuilder().getColumnLastUpdated(), true); @@ -206,13 +200,13 @@ public class SearchQueryBuilderTest { // Max only generated = builder.generate(null, 10); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST limit ?", generated.getSql()); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST fetch first ? rows only", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10)); // Range generated = builder.generate(10, 5); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST limit ? offset ?", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 5, 10)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST offset ? rows fetch next ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -220,7 +214,7 @@ public class SearchQueryBuilderTest { public void testRangeOracle12c_NoSort() { HibernatePropertiesProvider dialectProvider = new HibernatePropertiesProvider(); - dialectProvider.setDialectForUnitTest(new Oracle12cDialect()); + dialectProvider.setDialectForUnitTest(new HapiFhirOracleDialect()); SearchQueryBuilder builder = new SearchQueryBuilder(myFhirContext, myStorageSettings, myPartitionSettings, myRequestPartitionId, "Patient", mySqlBuilderFactory, dialectProvider, false); builder.addResourceIdsPredicate(Lists.newArrayList(500L, 501L)); GeneratedSql generated; @@ -232,13 +226,13 @@ public class SearchQueryBuilderTest { // Max only generated = builder.generate(null, 10); - assertEquals("select * from ( SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ) where rownum <= ?", generated.getSql()); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) fetch first ? rows only", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10)); // Range generated = builder.generate(10, 5); - assertEquals("select * from ( select row_.*, rownum rownum_ from ( SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ) row_ where rownum <= ?) where rownum_ > ?", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 15, 10)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) offset ? rows fetch next ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -246,7 +240,7 @@ public class SearchQueryBuilderTest { public void testRangeOracle12c_WithSort() { HibernatePropertiesProvider dialectProvider = new HibernatePropertiesProvider(); - dialectProvider.setDialectForUnitTest(new Oracle12cDialect()); + dialectProvider.setDialectForUnitTest(new HapiFhirOracleDialect()); SearchQueryBuilder builder = new SearchQueryBuilder(myFhirContext, myStorageSettings, myPartitionSettings, myRequestPartitionId, "Patient", mySqlBuilderFactory, dialectProvider, false); builder.addResourceIdsPredicate(Lists.newArrayList(500L, 501L)); builder.addSortDate(builder.getOrCreateResourceTablePredicateBuilder().getColumnLastUpdated(), true); @@ -259,13 +253,13 @@ public class SearchQueryBuilderTest { // Max only generated = builder.generate(null, 10); - assertEquals("select * from ( SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST ) where rownum <= ?", generated.getSql()); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST fetch first ? rows only", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10)); // Range generated = builder.generate(10, 5); - assertEquals("select * from ( select row_.*, rownum rownum_ from ( SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST ) row_ where rownum <= ?) where rownum_ > ?", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 15, 10)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST offset ? rows fetch next ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -290,7 +284,7 @@ public class SearchQueryBuilderTest { // Range generated = builder.generate(10, 5); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) limit ?, ?", generated.getSql()); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) limit ?,?", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -320,7 +314,7 @@ public class SearchQueryBuilderTest { // Range generated = builder.generate(10, 5); // assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY CASE WHEN t0.RES_UPDATED IS NULL THEN 1 ELSE 0 END ASC, t0.RES_UPDATED ASC limit ?, ?", generated.getSql()); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC limit ?, ?", generated.getSql()); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC limit ?,?", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -330,7 +324,7 @@ public class SearchQueryBuilderTest { public void testRangeMariaDB103_NoSort() { HibernatePropertiesProvider dialectProvider = new HibernatePropertiesProvider(); - dialectProvider.setDialectForUnitTest(new MariaDB103Dialect()); + dialectProvider.setDialectForUnitTest(new HapiFhirMariaDBDialect()); SearchQueryBuilder builder = new SearchQueryBuilder(myFhirContext, myStorageSettings, myPartitionSettings, myRequestPartitionId, "Patient", mySqlBuilderFactory, dialectProvider, false); builder.addResourceIdsPredicate(Lists.newArrayList(500L, 501L)); GeneratedSql generated; @@ -347,7 +341,7 @@ public class SearchQueryBuilderTest { // Range generated = builder.generate(10, 5); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) limit ?, ?", generated.getSql()); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) limit ?,?", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -356,7 +350,7 @@ public class SearchQueryBuilderTest { public void testRangeMariaDB103_WithSort() { HibernatePropertiesProvider dialectProvider = new HibernatePropertiesProvider(); - dialectProvider.setDialectForUnitTest(new MariaDB103Dialect()); + dialectProvider.setDialectForUnitTest(new HapiFhirMariaDBDialect()); SearchQueryBuilder builder = new SearchQueryBuilder(myFhirContext, myStorageSettings, myPartitionSettings, myRequestPartitionId, "Patient", mySqlBuilderFactory, dialectProvider, false); builder.addResourceIdsPredicate(Lists.newArrayList(500L, 501L)); builder.addSortDate(builder.getOrCreateResourceTablePredicateBuilder().getColumnLastUpdated(), true); @@ -377,7 +371,7 @@ public class SearchQueryBuilderTest { // Range generated = builder.generate(10, 5); // assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY CASE WHEN t0.RES_UPDATED IS NULL THEN 1 ELSE 0 END ASC, t0.RES_UPDATED ASC limit ?, ?", generated.getSql()); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC limit ?, ?", generated.getSql()); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC limit ?,?", generated.getSql()); assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -387,7 +381,7 @@ public class SearchQueryBuilderTest { public void testRangeDerbyTenSeven_NoSort() { HibernatePropertiesProvider dialectProvider = new HibernatePropertiesProvider(); - dialectProvider.setDialectForUnitTest(new DerbyTenSevenDialect()); + dialectProvider.setDialectForUnitTest(new DerbyDialect()); SearchQueryBuilder builder = new SearchQueryBuilder(myFhirContext, myStorageSettings, myPartitionSettings, myRequestPartitionId, "Patient", mySqlBuilderFactory, dialectProvider, false); builder.addResourceIdsPredicate(Lists.newArrayList(500L, 501L)); GeneratedSql generated; @@ -399,13 +393,13 @@ public class SearchQueryBuilderTest { // Max only generated = builder.generate(null, 10); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) fetch first 10 rows only", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) fetch first ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10)); // Range generated = builder.generate(10, 5); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) offset 10 rows fetch next 5 rows only", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) offset ? rows fetch next ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } @@ -413,7 +407,7 @@ public class SearchQueryBuilderTest { public void testRangeDerbyTenSeven_WithSort() { HibernatePropertiesProvider dialectProvider = new HibernatePropertiesProvider(); - dialectProvider.setDialectForUnitTest(new DerbyTenSevenDialect()); + dialectProvider.setDialectForUnitTest(new DerbyDialect()); SearchQueryBuilder builder = new SearchQueryBuilder(myFhirContext, myStorageSettings, myPartitionSettings, myRequestPartitionId, "Patient", mySqlBuilderFactory, dialectProvider, false); builder.addResourceIdsPredicate(Lists.newArrayList(500L, 501L)); builder.addSortDate(builder.getOrCreateResourceTablePredicateBuilder().getColumnLastUpdated(), true); @@ -426,13 +420,13 @@ public class SearchQueryBuilderTest { // Max only generated = builder.generate(null, 10); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST fetch first 10 rows only", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST fetch first ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10)); // Range generated = builder.generate(10, 5); - assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST offset 10 rows fetch next 5 rows only", generated.getSql()); - assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L)); + assertEquals("SELECT t0.RES_ID FROM HFJ_RESOURCE t0 WHERE (((t0.RES_TYPE = ?) AND (t0.RES_DELETED_AT IS NULL)) AND (t0.RES_ID IN (?,?) )) ORDER BY t0.RES_UPDATED ASC NULLS LAST offset ? rows fetch next ? rows only", generated.getSql()); + assertThat(generated.getBindVariables().toString(), generated.getBindVariables(), contains("Patient", 500L, 501L, 10, 5)); } diff --git a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/term/LoincFullLoadR4SandboxIT.java b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/term/LoincFullLoadR4SandboxIT.java index dd4f999f059..8396aaab023 100644 --- a/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/term/LoincFullLoadR4SandboxIT.java +++ b/hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/term/LoincFullLoadR4SandboxIT.java @@ -32,7 +32,7 @@ import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; -import org.hibernate.dialect.PostgreSQL10Dialect; +import org.hibernate.dialect.PostgreSQLDialect; import org.hl7.fhir.r4.model.ValueSet; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -52,8 +52,8 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.ResourceUtils; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.Query; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -706,7 +706,7 @@ public class LoincFullLoadR4SandboxIT extends BaseJpaTest { @Override public String getHibernateDialect() { if (USE_REAL_DB) { - return PostgreSQL10Dialect.class.getName(); + return PostgreSQLDialect.class.getName(); } return super.getHibernateDialect(); diff --git a/hapi-fhir-jpaserver-uhnfhirtest/pom.xml b/hapi-fhir-jpaserver-uhnfhirtest/pom.xml index 539f240c9a6..4acc1750f21 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/pom.xml +++ b/hapi-fhir-jpaserver-uhnfhirtest/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../pom.xml @@ -65,21 +65,6 @@ ${project.version} - - com.helger - ph-schematron - - - Saxon-HE - net.sf.saxon - - - - - com.helger - ph-commons - - org.springframework spring-web @@ -108,8 +93,8 @@ - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided @@ -119,48 +104,6 @@ h2 test - - - org.eclipse.jetty - jetty-servlets - test - - - org.eclipse.jetty - jetty-webapp - test - - - org.eclipse.jetty - jetty-servlet - test - - - org.eclipse.jetty - jetty-server - test - - - org.eclipse.jetty - jetty-util - test - - - org.eclipse.jetty.websocket - websocket-jetty-api - test - - - org.eclipse.jetty.websocket - websocket-core-client - test - - - org.eclipse.jetty.websocket - websocket-jetty-server - test - - org.apache.jena apache-jena-libs @@ -190,6 +133,13 @@ ${project.version} + + ca.uhn.hapi.fhir + hapi-fhir-test-utilities + test + ${project.version} + + diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/TestRestfulServer.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/TestRestfulServer.java index 84e393ce4fd..58b7f4f9e4b 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/TestRestfulServer.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/TestRestfulServer.java @@ -47,6 +47,9 @@ import ca.uhn.fhirtest.config.TestR4BConfig; import ca.uhn.fhirtest.config.TestR4Config; import ca.uhn.fhirtest.config.TestR5Config; import ca.uhn.hapi.converters.server.VersionedApiConverterInterceptor; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.springframework.web.context.ContextLoaderListener; @@ -55,9 +58,6 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import java.util.ArrayList; import java.util.List; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; public class TestRestfulServer extends RestfulServer { @@ -80,7 +80,7 @@ public class TestRestfulServer extends RestfulServer { public void destroy() { super.destroy(); ourLog.info("Server is shutting down"); - myAppCtx.destroy(); + myAppCtx.close(); } @SuppressWarnings("unchecked") diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/FhirTestBalpAuditContextServices.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/FhirTestBalpAuditContextServices.java index 394e35eb70d..144aad7c2fb 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/FhirTestBalpAuditContextServices.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/FhirTestBalpAuditContextServices.java @@ -3,7 +3,6 @@ package ca.uhn.fhirtest.config; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.storage.interceptor.balp.IBalpAuditContextServices; -import joptsimple.internal.Strings; import org.hl7.fhir.r4.model.Reference; import javax.annotation.Nonnull; @@ -73,6 +72,6 @@ public class FhirTestBalpAuditContextServices implements IBalpAuditContextServic parts[2] = "X"; parts[3] = "X"; } - return Strings.join(parts, "."); + return String.join(".", parts); } } diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/FhirTesterConfig.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/FhirTesterConfig.java index b41af3fa429..d6c493cf78a 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/FhirTesterConfig.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/FhirTesterConfig.java @@ -4,7 +4,6 @@ import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.to.FhirTesterMvcConfig; import ca.uhn.fhir.to.TesterConfig; import ca.uhn.fhirtest.mvc.SubscriptionPlaygroundController; -import org.springframework.beans.factory.annotation.Autowire; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @@ -116,7 +115,7 @@ public class FhirTesterConfig { return retVal; } - @Bean(autowire = Autowire.BY_TYPE) + @Bean public SubscriptionPlaygroundController subscriptionPlaygroundController() { return new SubscriptionPlaygroundController(); } diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestAuditConfig.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestAuditConfig.java index 03e838b3296..7d68437d1f5 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestAuditConfig.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestAuditConfig.java @@ -12,6 +12,8 @@ import ca.uhn.fhir.jpa.search.DatabaseBackedPagingProvider; import ca.uhn.fhir.jpa.util.CurrentThreadCaptureQueriesListener; import ca.uhn.fhir.jpa.validation.ValidationSettings; import ca.uhn.fhirtest.interceptor.PublicSecurityInterceptor; +import jakarta.annotation.PostConstruct; +import jakarta.persistence.EntityManagerFactory; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.apache.commons.dbcp2.BasicDataSource; import org.hl7.fhir.r5.utils.validation.constants.ReferenceValidationPolicy; @@ -28,8 +30,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.Properties; import java.util.concurrent.TimeUnit; -import javax.annotation.PostConstruct; -import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @@ -102,9 +102,11 @@ public class TestAuditConfig { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( - ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { + ConfigurableListableBeanFactory theConfigurableListableBeanFactory, + FhirContext theFhirContext, + JpaStorageSettings theStorageSettings) { LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory( - theConfigurableListableBeanFactory, theFhirContext); + theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaAudit"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestDstu2Config.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestDstu2Config.java index a3e4f203b2a..e19ac54a653 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestDstu2Config.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestDstu2Config.java @@ -14,6 +14,7 @@ import ca.uhn.fhir.rest.server.interceptor.RequestValidatingInterceptor; import ca.uhn.fhir.validation.IValidatorModule; import ca.uhn.fhir.validation.ResultSeverityEnum; import ca.uhn.fhirtest.interceptor.PublicSecurityInterceptor; +import jakarta.persistence.EntityManagerFactory; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.apache.commons.dbcp2.BasicDataSource; import org.hibernate.search.backend.lucene.cfg.LuceneBackendSettings; @@ -34,7 +35,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.Properties; import java.util.concurrent.TimeUnit; -import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @@ -120,9 +120,11 @@ public class TestDstu2Config { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( - ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { + ConfigurableListableBeanFactory theConfigurableListableBeanFactory, + FhirContext theFhirContext, + JpaStorageSettings theStorageSettings) { LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory( - theConfigurableListableBeanFactory, theFhirContext); + theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaDstu2"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestDstu3Config.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestDstu3Config.java index 0e4e285b9a2..2531b87b4b8 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestDstu3Config.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestDstu3Config.java @@ -15,6 +15,7 @@ import ca.uhn.fhir.rest.server.interceptor.RequestValidatingInterceptor; import ca.uhn.fhir.validation.IInstanceValidatorModule; import ca.uhn.fhir.validation.ResultSeverityEnum; import ca.uhn.fhirtest.interceptor.PublicSecurityInterceptor; +import jakarta.persistence.EntityManagerFactory; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.apache.commons.dbcp2.BasicDataSource; import org.hibernate.search.backend.lucene.cfg.LuceneBackendSettings; @@ -35,7 +36,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.Properties; import java.util.concurrent.TimeUnit; -import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @@ -120,9 +120,11 @@ public class TestDstu3Config { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( - ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { + ConfigurableListableBeanFactory theConfigurableListableBeanFactory, + FhirContext theFhirContext, + JpaStorageSettings theStorageSettings) { LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory( - theConfigurableListableBeanFactory, theFhirContext); + theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaDstu3"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR4BConfig.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR4BConfig.java index bafbdc2daf3..6cbb003cd29 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR4BConfig.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR4BConfig.java @@ -15,6 +15,7 @@ import ca.uhn.fhir.rest.server.interceptor.RequestValidatingInterceptor; import ca.uhn.fhir.validation.IInstanceValidatorModule; import ca.uhn.fhir.validation.ResultSeverityEnum; import ca.uhn.fhirtest.interceptor.PublicSecurityInterceptor; +import jakarta.persistence.EntityManagerFactory; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.apache.commons.dbcp2.BasicDataSource; import org.hibernate.search.backend.lucene.cfg.LuceneBackendSettings; @@ -36,7 +37,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.Properties; import java.util.concurrent.TimeUnit; -import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @@ -118,9 +118,11 @@ public class TestR4BConfig { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( - ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { + ConfigurableListableBeanFactory theConfigurableListableBeanFactory, + FhirContext theFhirContext, + JpaStorageSettings theStorageSettings) { LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory( - theConfigurableListableBeanFactory, theFhirContext); + theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaR4B"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR4Config.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR4Config.java index 1c62b7a5225..ba0a5db50af 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR4Config.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR4Config.java @@ -21,6 +21,7 @@ import ca.uhn.fhir.rest.server.interceptor.RequestValidatingInterceptor; import ca.uhn.fhir.validation.IInstanceValidatorModule; import ca.uhn.fhir.validation.ResultSeverityEnum; import ca.uhn.fhirtest.interceptor.PublicSecurityInterceptor; +import jakarta.persistence.EntityManagerFactory; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.apache.commons.dbcp2.BasicDataSource; import org.hibernate.search.backend.lucene.cfg.LuceneBackendSettings; @@ -41,7 +42,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.Properties; import java.util.concurrent.TimeUnit; -import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @@ -121,9 +121,11 @@ public class TestR4Config { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( - ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { + ConfigurableListableBeanFactory theConfigurableListableBeanFactory, + FhirContext theFhirContext, + JpaStorageSettings theStorageSettings) { LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory( - theConfigurableListableBeanFactory, theFhirContext); + theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaR4"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR5Config.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR5Config.java index e255f2627cb..775125e84fe 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR5Config.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/config/TestR5Config.java @@ -15,6 +15,7 @@ import ca.uhn.fhir.rest.server.interceptor.RequestValidatingInterceptor; import ca.uhn.fhir.validation.IInstanceValidatorModule; import ca.uhn.fhir.validation.ResultSeverityEnum; import ca.uhn.fhirtest.interceptor.PublicSecurityInterceptor; +import jakarta.persistence.EntityManagerFactory; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.apache.commons.dbcp2.BasicDataSource; import org.hibernate.search.backend.lucene.cfg.LuceneBackendSettings; @@ -37,7 +38,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.Properties; import java.util.concurrent.TimeUnit; -import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @@ -130,9 +130,11 @@ public class TestR5Config { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( - ConfigurableListableBeanFactory theConfigurableListableBeanFactory, FhirContext theFhirContext) { + ConfigurableListableBeanFactory theConfigurableListableBeanFactory, + FhirContext theFhirContext, + JpaStorageSettings theStorageSettings) { LocalContainerEntityManagerFactoryBean retVal = HapiEntityManagerFactoryUtil.newEntityManagerFactory( - theConfigurableListableBeanFactory, theFhirContext); + theConfigurableListableBeanFactory, theFhirContext, theStorageSettings); retVal.setPersistenceUnitName("PU_HapiFhirJpaR5"); retVal.setDataSource(dataSource()); retVal.setJpaProperties(jpaProperties()); diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/interceptor/AnalyticsInterceptor.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/interceptor/AnalyticsInterceptor.java index 65043a50226..4ef6091af33 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/interceptor/AnalyticsInterceptor.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/interceptor/AnalyticsInterceptor.java @@ -10,6 +10,7 @@ import ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory; import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.UrlUtil; +import jakarta.annotation.PreDestroy; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -26,7 +27,6 @@ import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.UUID; -import javax.annotation.PreDestroy; import static org.apache.commons.lang3.StringUtils.defaultIfBlank; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/joke/HolyFooCowInterceptor.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/joke/HolyFooCowInterceptor.java index 2405d91b39a..5a730df3671 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/joke/HolyFooCowInterceptor.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/joke/HolyFooCowInterceptor.java @@ -3,9 +3,8 @@ package ca.uhn.fhirtest.joke; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.rest.server.exceptions.UnclassifiedServerFailureException; import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/migrate/FhirTestAutoMigrator.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/migrate/FhirTestAutoMigrator.java index 0de60267015..438eff48732 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/migrate/FhirTestAutoMigrator.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/migrate/FhirTestAutoMigrator.java @@ -8,13 +8,13 @@ import ca.uhn.fhir.jpa.migrate.dao.HapiMigrationDao; import ca.uhn.fhir.jpa.migrate.tasks.HapiFhirJpaMigrationTasks; import ca.uhn.fhir.util.VersionEnum; import ca.uhn.fhirtest.config.CommonConfig; +import jakarta.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.Properties; import java.util.Set; -import javax.annotation.PostConstruct; import javax.sql.DataSource; public class FhirTestAutoMigrator { diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/mvc/SubscriptionPlaygroundController.java b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/mvc/SubscriptionPlaygroundController.java index f8dc38ef043..1b9a3f72e5f 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/mvc/SubscriptionPlaygroundController.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/main/java/ca/uhn/fhirtest/mvc/SubscriptionPlaygroundController.java @@ -3,6 +3,7 @@ package ca.uhn.fhirtest.mvc; import ca.uhn.fhir.rest.client.impl.GenericClient; import ca.uhn.fhir.to.BaseController; import ca.uhn.fhir.to.model.HomeRequest; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.Subscription; import org.springframework.ui.ModelMap; @@ -10,7 +11,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList; import java.util.List; -import javax.servlet.http.HttpServletRequest; @org.springframework.stereotype.Controller() public class SubscriptionPlaygroundController extends BaseController { diff --git a/hapi-fhir-jpaserver-uhnfhirtest/src/test/java/ca/uhn/fhirtest/UhnFhirTestApp.java b/hapi-fhir-jpaserver-uhnfhirtest/src/test/java/ca/uhn/fhirtest/UhnFhirTestApp.java index 9b5dd2c68f5..4c79a0ca6cc 100644 --- a/hapi-fhir-jpaserver-uhnfhirtest/src/test/java/ca/uhn/fhirtest/UhnFhirTestApp.java +++ b/hapi-fhir-jpaserver-uhnfhirtest/src/test/java/ca/uhn/fhirtest/UhnFhirTestApp.java @@ -3,8 +3,8 @@ package ca.uhn.fhirtest; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.client.api.IGenericClient; +import org.eclipse.jetty.ee10.webapp.WebAppContext; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.webapp.WebAppContext; import org.hl7.fhir.dstu3.model.Organization; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.dstu3.model.Subscription; @@ -63,7 +63,7 @@ public class UhnFhirTestApp { root.setContextPath("/"); root.setDescriptor("hapi-fhir-jpaserver-uhnfhirtest/src/main/webapp/WEB-INF/web.xml"); - root.setResourceBase("hapi-fhir-jpaserver-uhnfhirtest/target/hapi-fhir-jpaserver"); + root.setBaseResourceAsString("hapi-fhir-jpaserver-uhnfhirtest/target/hapi-fhir-jpaserver"); root.setParentLoaderPriority(true); diff --git a/hapi-fhir-server-cds-hooks/pom.xml b/hapi-fhir-server-cds-hooks/pom.xml index 4ab4abd28ef..9e017d981b0 100644 --- a/hapi-fhir-server-cds-hooks/pom.xml +++ b/hapi-fhir-server-cds-hooks/pom.xml @@ -7,7 +7,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/api/json/CdsServiceRequestContextJson.java b/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/api/json/CdsServiceRequestContextJson.java index a4d999a4ae5..d2832a79f56 100644 --- a/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/api/json/CdsServiceRequestContextJson.java +++ b/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/api/json/CdsServiceRequestContextJson.java @@ -20,6 +20,7 @@ package ca.uhn.hapi.fhir.cdshooks.api.json; import ca.uhn.fhir.model.api.IModelJson; +import com.fasterxml.jackson.annotation.JsonAnyGetter; import org.hl7.fhir.instance.model.api.IBaseResource; import java.util.Collections; @@ -29,6 +30,8 @@ import java.util.Map; import java.util.Set; public class CdsServiceRequestContextJson extends BaseCdsServiceJson implements IModelJson { + + @JsonAnyGetter private Map myMap; public String getString(String theKey) { diff --git a/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/svc/CdsHooksContextBooter.java b/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/svc/CdsHooksContextBooter.java index 48e2fab4ab5..df6762d7151 100644 --- a/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/svc/CdsHooksContextBooter.java +++ b/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/svc/CdsHooksContextBooter.java @@ -28,6 +28,7 @@ import ca.uhn.hapi.fhir.cdshooks.api.CdsServicePrefetch; import ca.uhn.hapi.fhir.cdshooks.api.json.CdsServiceJson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.annotation.PreDestroy; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,7 +40,6 @@ import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -import javax.annotation.PreDestroy; /** * This bean creates a customer-defined spring context which will diff --git a/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/svc/CdsServiceRegistryImpl.java b/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/svc/CdsServiceRegistryImpl.java index 99c6f314c47..3155e16ea0f 100644 --- a/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/svc/CdsServiceRegistryImpl.java +++ b/hapi-fhir-server-cds-hooks/src/main/java/ca/uhn/hapi/fhir/cdshooks/svc/CdsServiceRegistryImpl.java @@ -35,13 +35,13 @@ import ca.uhn.hapi.fhir.cdshooks.svc.cr.discovery.ICrDiscoveryServiceFactory; import ca.uhn.hapi.fhir.cdshooks.svc.prefetch.CdsPrefetchSvc; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.function.Function; import javax.annotation.Nonnull; -import javax.annotation.PostConstruct; public class CdsServiceRegistryImpl implements ICdsServiceRegistry { private static final Logger ourLog = LoggerFactory.getLogger(CdsServiceRegistryImpl.class); diff --git a/hapi-fhir-server-mdm/pom.xml b/hapi-fhir-server-mdm/pom.xml index 35f51c77d5b..0a008f0fe86 100644 --- a/hapi-fhir-server-mdm/pom.xml +++ b/hapi-fhir-server-mdm/pom.xml @@ -7,7 +7,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-server-mdm/src/main/java/ca/uhn/fhir/mdm/provider/MdmProviderLoader.java b/hapi-fhir-server-mdm/src/main/java/ca/uhn/fhir/mdm/provider/MdmProviderLoader.java index e5f03242298..67c643d07fe 100644 --- a/hapi-fhir-server-mdm/src/main/java/ca/uhn/fhir/mdm/provider/MdmProviderLoader.java +++ b/hapi-fhir-server-mdm/src/main/java/ca/uhn/fhir/mdm/provider/MdmProviderLoader.java @@ -28,11 +28,10 @@ import ca.uhn.fhir.mdm.api.IMdmControllerSvc; import ca.uhn.fhir.mdm.api.IMdmSettings; import ca.uhn.fhir.mdm.api.IMdmSubmitSvc; import ca.uhn.fhir.rest.server.provider.ResourceProviderFactory; +import jakarta.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import javax.annotation.PreDestroy; - @Service public class MdmProviderLoader { @Autowired diff --git a/hapi-fhir-server-openapi/pom.xml b/hapi-fhir-server-openapi/pom.xml index 5d58f58def4..8031d59df4d 100644 --- a/hapi-fhir-server-openapi/pom.xml +++ b/hapi-fhir-server-openapi/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -35,12 +35,17 @@ io.swagger.core.v3 - swagger-models - 2.1.7 + swagger-models-jakarta io.swagger.core.v3 - swagger-core + swagger-core-jakarta + + + io.swagger.core.v3 + swagger-models + + org.webjars @@ -59,8 +64,8 @@ - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided diff --git a/hapi-fhir-server-openapi/src/main/java/ca/uhn/fhir/rest/openapi/OpenApiInterceptor.java b/hapi-fhir-server-openapi/src/main/java/ca/uhn/fhir/rest/openapi/OpenApiInterceptor.java index b49b65f39bd..1463ea3484a 100644 --- a/hapi-fhir-server-openapi/src/main/java/ca/uhn/fhir/rest/openapi/OpenApiInterceptor.java +++ b/hapi-fhir-server-openapi/src/main/java/ca/uhn/fhir/rest/openapi/OpenApiInterceptor.java @@ -56,6 +56,9 @@ import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.oas.models.responses.ApiResponses; import io.swagger.v3.oas.models.servers.Server; import io.swagger.v3.oas.models.tags.Tag; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.convertors.factory.VersionConvertorFactory_30_40; @@ -93,7 +96,7 @@ import org.thymeleaf.templateresolver.ITemplateResolver; import org.thymeleaf.templateresolver.TemplateResolution; import org.thymeleaf.templateresource.ClassLoaderTemplateResource; import org.thymeleaf.web.servlet.IServletWebExchange; -import org.thymeleaf.web.servlet.JavaxServletWebApplication; +import org.thymeleaf.web.servlet.JakartaServletWebApplication; import java.io.IOException; import java.io.InputStream; @@ -110,9 +113,6 @@ import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.annotation.Nonnull; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static ca.uhn.fhir.rest.server.util.NarrativeUtil.sanitizeHtmlFragment; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; @@ -340,7 +340,7 @@ public class OpenApiInterceptor { HttpServletRequest servletRequest = theRequestDetails.getServletRequest(); ServletContext servletContext = servletRequest.getServletContext(); - JavaxServletWebApplication application = JavaxServletWebApplication.buildApplication(servletContext); + JakartaServletWebApplication application = JakartaServletWebApplication.buildApplication(servletContext); IServletWebExchange exchange = application.buildExchange(servletRequest, theResponse); WebContext context = new WebContext(exchange); context.setVariable(REQUEST_DETAILS, theRequestDetails); diff --git a/hapi-fhir-server-openapi/src/test/java/ca/uhn/fhir/rest/openapi/OpenApiInterceptorTest.java b/hapi-fhir-server-openapi/src/test/java/ca/uhn/fhir/rest/openapi/OpenApiInterceptorTest.java index 441a656b826..5ba2667e959 100644 --- a/hapi-fhir-server-openapi/src/test/java/ca/uhn/fhir/rest/openapi/OpenApiInterceptorTest.java +++ b/hapi-fhir-server-openapi/src/test/java/ca/uhn/fhir/rest/openapi/OpenApiInterceptorTest.java @@ -5,7 +5,13 @@ import ca.uhn.fhir.interceptor.api.Hook; import ca.uhn.fhir.interceptor.api.Interceptor; import ca.uhn.fhir.interceptor.api.Pointcut; import ca.uhn.fhir.model.api.annotation.Description; -import ca.uhn.fhir.rest.annotation.*; +import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; +import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.annotation.Operation; +import ca.uhn.fhir.rest.annotation.OperationParam; +import ca.uhn.fhir.rest.annotation.Patch; +import ca.uhn.fhir.rest.annotation.ResourceParam; +import ca.uhn.fhir.rest.annotation.Validate; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; @@ -26,12 +32,20 @@ import com.gargoylesoftware.htmlunit.html.HtmlPage; import io.swagger.v3.core.util.Yaml; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.PathItem; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.hamcrest.Matchers; -import org.hl7.fhir.instance.model.api.*; +import org.hl7.fhir.instance.model.api.IBaseBundle; +import org.hl7.fhir.instance.model.api.IBaseCoding; +import org.hl7.fhir.instance.model.api.IBaseConformance; +import org.hl7.fhir.instance.model.api.IBaseParameters; +import org.hl7.fhir.instance.model.api.IBaseReference; +import org.hl7.fhir.instance.model.api.IBaseResource; +import org.hl7.fhir.instance.model.api.IIdType; +import org.hl7.fhir.instance.model.api.IPrimitiveType; import org.hl7.fhir.r5.model.ActorDefinition; import org.hl7.fhir.r5.model.CapabilityStatement; import org.junit.jupiter.api.*; @@ -40,7 +54,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; -import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; @@ -51,7 +64,9 @@ import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; public class OpenApiInterceptorTest { diff --git a/hapi-fhir-server/pom.xml b/hapi-fhir-server/pom.xml index aaa176420d4..b3286ce44ec 100644 --- a/hapi-fhir-server/pom.xml +++ b/hapi-fhir-server/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -35,8 +35,8 @@ - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/IRestfulResponse.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/IRestfulResponse.java index 936fc86801d..fbca9e1add9 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/IRestfulResponse.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/IRestfulResponse.java @@ -30,7 +30,7 @@ import javax.annotation.Nullable; /** * Implementations of this interface represent a response back to the client from the server. It is - * conceptually similar to {@link javax.servlet.http.HttpServletResponse} but intended to be agnostic + * conceptually similar to {@link jakarta.servlet.http.HttpServletResponse} but intended to be agnostic * of the server framework being used. *

    * This class is a bit of an awkward abstraction given the two styles of servers it supports. diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/RequestDetails.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/RequestDetails.java index a8a0ae4af20..0a9d904c1bb 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/RequestDetails.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/RequestDetails.java @@ -28,6 +28,8 @@ import ca.uhn.fhir.rest.server.IRestfulServerDefaults; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor; import ca.uhn.fhir.util.StopWatch; import ca.uhn.fhir.util.UrlUtil; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; @@ -43,8 +45,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static org.apache.commons.lang3.StringUtils.isBlank; @@ -325,7 +325,7 @@ public abstract class RequestDetails { * @throws UnsupportedEncodingException if the character set encoding used is not supported and the text cannot be decoded * @throws IllegalStateException if {@link #getInputStream} method has been called on this request * @throws IOException if an input or output exception occurred - * @see javax.servlet.http.HttpServletRequest#getInputStream + * @see jakarta.servlet.http.HttpServletRequest#getInputStream */ public abstract Reader getReader() throws IOException; @@ -397,7 +397,10 @@ public abstract class RequestDetails { /** * Returns the server base URL (with no trailing '/') for a given request + * + * @deprecated Use {@link #getFhirServerBase()} instead. Deprecated in HAPI FHIR 7.0.0 */ + @Deprecated public abstract String getServerBaseForRequest(); /** diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/storage/TransactionDetails.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/storage/TransactionDetails.java index 4762a79e99c..3c769e0f915 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/storage/TransactionDetails.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/api/server/storage/TransactionDetails.java @@ -31,8 +31,17 @@ import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.function.Supplier; -import java.util.*; import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/ApacheProxyAddressStrategy.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/ApacheProxyAddressStrategy.java index 561bc7dfb08..5f1952bdd3d 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/ApacheProxyAddressStrategy.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/ApacheProxyAddressStrategy.java @@ -19,6 +19,8 @@ */ package ca.uhn.fhir.rest.server; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,8 +30,6 @@ import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import java.util.Optional; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; import static java.util.Optional.ofNullable; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/HardcodedServerAddressStrategy.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/HardcodedServerAddressStrategy.java index 5782290bdd2..6d192d30a1e 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/HardcodedServerAddressStrategy.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/HardcodedServerAddressStrategy.java @@ -19,11 +19,10 @@ */ package ca.uhn.fhir.rest.server; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.Validate; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - /** * Server address strategy which simply returns a hardcoded URL */ diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IServerAddressStrategy.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IServerAddressStrategy.java index 96d682e1a0e..7fbdd99491c 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IServerAddressStrategy.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IServerAddressStrategy.java @@ -19,8 +19,8 @@ */ package ca.uhn.fhir.rest.server; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; /** * Provides the server base for a given incoming request. This can be used to account for diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IServerConformanceProvider.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IServerConformanceProvider.java index f2b5eb31b9d..65ea9876d78 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IServerConformanceProvider.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IServerConformanceProvider.java @@ -22,11 +22,10 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.api.server.RequestDetails; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; -import javax.servlet.http.HttpServletRequest; - public interface IServerConformanceProvider { /** diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IncomingRequestAddressStrategy.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IncomingRequestAddressStrategy.java index 4653bdbca74..5220bdef551 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IncomingRequestAddressStrategy.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/IncomingRequestAddressStrategy.java @@ -19,11 +19,10 @@ */ package ca.uhn.fhir.rest.server; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - /** * Determines the server's base using the incoming request */ diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/ResourceBinding.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/ResourceBinding.java index febb8a729c9..f30a25e93c8 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/ResourceBinding.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/ResourceBinding.java @@ -33,8 +33,8 @@ public class ResourceBinding { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ResourceBinding.class); - private String resourceName; - private LinkedList myMethodBindings = new LinkedList<>(); + private String myResourceName; + private final LinkedList myMethodBindings = new LinkedList<>(); /** * Constructor @@ -44,8 +44,8 @@ public class ResourceBinding { } public BaseMethodBinding getMethod(RequestDetails theRequest) { - if (null == myMethodBindings) { - ourLog.warn("No methods exist for resource: {}", resourceName); + if (myMethodBindings.isEmpty()) { + ourLog.warn("No methods exist for resource: {}", myResourceName); return null; } @@ -75,11 +75,11 @@ public class ResourceBinding { } public String getResourceName() { - return resourceName; + return myResourceName; } public void setResourceName(String resourceName) { - this.resourceName = resourceName; + this.myResourceName = resourceName; } public List getMethodBindings() { @@ -87,13 +87,20 @@ public class ResourceBinding { } public void addMethod(BaseMethodBinding method) { + if (myMethodBindings.stream() + .anyMatch( + t -> t.getMethod().toString().equals(method.getMethod().toString()))) { + ourLog.warn( + "The following method has been registered twice against this RestfulServer: {}", + method.getMethod()); + } this.myMethodBindings.push(method); } @Override public boolean equals(Object o) { if (!(o instanceof ResourceBinding)) return false; - return resourceName.equals(((ResourceBinding) o).getResourceName()); + return myResourceName.equals(((ResourceBinding) o).getResourceName()); } @Override diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/RestfulServer.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/RestfulServer.java index 550a9d28fd3..30d5548e869 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/RestfulServer.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/RestfulServer.java @@ -65,6 +65,11 @@ import ca.uhn.fhir.util.UrlPathTokenizer; import ca.uhn.fhir.util.UrlUtil; import ca.uhn.fhir.util.VersionUtil; import com.google.common.collect.Lists; +import jakarta.servlet.ServletException; +import jakarta.servlet.UnavailableException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; @@ -99,11 +104,6 @@ import java.util.concurrent.locks.ReentrantLock; import java.util.jar.Manifest; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.servlet.ServletException; -import javax.servlet.UnavailableException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static ca.uhn.fhir.util.StringUtil.toUtf8String; import static java.util.stream.Collectors.toList; @@ -367,6 +367,10 @@ public class RestfulServer extends HttpServlet implements IRestfulServer t.close()); myGlobalBinding.getMethodBindings().forEach(t -> t.close()); myServerBinding.getMethodBindings().forEach(t -> t.close()); + + myResourceNameToBinding.clear(); + myGlobalBinding.getMethodBindings().clear(); + myServerBinding.getMethodBindings().clear(); } /** @@ -965,6 +969,10 @@ public class RestfulServer extends HttpServlet implements IRestfulServerfalse to indicate that the server itself should not also provide a response. * @return Return true if processing should continue normally. This is generally the right thing to do. * If your interceptor is providing a response rather than letting HAPI handle the response normally, you diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/InterceptorAdapter.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/InterceptorAdapter.java index a736b12725f..b4c8b559809 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/InterceptorAdapter.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/InterceptorAdapter.java @@ -26,12 +26,12 @@ import ca.uhn.fhir.rest.api.server.ResponseDetails; import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.hl7.fhir.instance.model.api.IBaseResource; import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; /** * Base class for {@link IServerInterceptor} implementations. Provides a No-op implementation diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptor.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptor.java index 40c74261f2f..f58f02a37e9 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptor.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptor.java @@ -31,6 +31,9 @@ import ca.uhn.fhir.rest.server.RestfulServerUtils.ResponseEncoding; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.UrlUtil; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.text.StringSubstitutor; @@ -41,9 +44,6 @@ import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Date; import java.util.Map.Entry; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/RequestValidatingInterceptor.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/RequestValidatingInterceptor.java index 69208893551..a734c691245 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/RequestValidatingInterceptor.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/RequestValidatingInterceptor.java @@ -30,10 +30,10 @@ import ca.uhn.fhir.rest.server.method.ResourceParameter; import ca.uhn.fhir.validation.FhirValidator; import ca.uhn.fhir.validation.ResultSeverityEnum; import ca.uhn.fhir.validation.ValidationResult; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.nio.charset.Charset; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/ResponseHighlighterInterceptor.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/ResponseHighlighterInterceptor.java index 6ad6ec0716e..34a10d6f94a 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/ResponseHighlighterInterceptor.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/ResponseHighlighterInterceptor.java @@ -45,6 +45,9 @@ import ca.uhn.fhir.util.FhirTerser; import ca.uhn.fhir.util.StopWatch; import ca.uhn.fhir.util.UrlUtil; import com.google.common.annotations.VisibleForTesting; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.text.StringEscapeUtils; @@ -66,9 +69,6 @@ import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/SearchPreferHandlingInterceptor.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/SearchPreferHandlingInterceptor.java index 51df7c08ff8..00dfd8a6dbf 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/SearchPreferHandlingInterceptor.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/SearchPreferHandlingInterceptor.java @@ -36,6 +36,8 @@ import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.method.SearchMethodBinding; import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.Validate; import java.util.HashMap; @@ -43,8 +45,6 @@ import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/ServeMediaResourceRawInterceptor.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/ServeMediaResourceRawInterceptor.java index d1ceea5cab0..0fbbeb67d4b 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/ServeMediaResourceRawInterceptor.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/ServeMediaResourceRawInterceptor.java @@ -31,6 +31,8 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.RestfulServerUtils; import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IPrimitiveType; @@ -39,8 +41,6 @@ import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/VerboseLoggingInterceptor.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/VerboseLoggingInterceptor.java index 7b000b05ab5..7dbcf69e73b 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/VerboseLoggingInterceptor.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/VerboseLoggingInterceptor.java @@ -21,10 +21,10 @@ package ca.uhn.fhir.rest.server.interceptor; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.util.Enumeration; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; /** * This interceptor creates verbose server log entries containing the complete request and response payloads. diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/SearchNarrowingInterceptor.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/SearchNarrowingInterceptor.java index 776a6221778..affa0936f39 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/SearchNarrowingInterceptor.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/SearchNarrowingInterceptor.java @@ -45,6 +45,8 @@ import ca.uhn.fhir.util.UrlUtil; import ca.uhn.fhir.util.ValidateUtil; import ca.uhn.fhir.util.bundle.ModifiableBundleEntry; import com.google.common.collect.ArrayListMultimap; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; @@ -62,8 +64,6 @@ import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.annotation.Nullable; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; /** * This interceptor can be used to automatically narrow the scope of searches in order to diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseOutcomeReturningMethodBinding.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseOutcomeReturningMethodBinding.java index e9c7e56458c..5142e676d8b 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseOutcomeReturningMethodBinding.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseOutcomeReturningMethodBinding.java @@ -22,11 +22,17 @@ package ca.uhn.fhir.rest.server.method; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.i18n.Msg; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.rest.api.PreferHeader; +import ca.uhn.fhir.rest.api.PreferReturnEnum; +import ca.uhn.fhir.rest.api.RequestTypeEnum; +import ca.uhn.fhir.rest.api.RestOperationTypeEnum; +import ca.uhn.fhir.rest.api.SummaryEnum; import ca.uhn.fhir.rest.api.server.IRestfulResponse; import ca.uhn.fhir.rest.api.server.IRestfulServer; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.api.server.ResponseDetails; -import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.server.RestfulServerUtils; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseOutcomeReturningMethodBindingWithResourceIdButNoResourceBody.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseOutcomeReturningMethodBindingWithResourceIdButNoResourceBody.java index 19a43078ce3..fc90d4a2b01 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseOutcomeReturningMethodBindingWithResourceIdButNoResourceBody.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseOutcomeReturningMethodBindingWithResourceIdButNoResourceBody.java @@ -19,9 +19,11 @@ */ package ca.uhn.fhir.rest.server.method; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.ConfigurationException; +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.i18n.Msg; -import ca.uhn.fhir.rest.annotation.*; +import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.param.ParameterUtil; import ca.uhn.fhir.rest.server.IResourceProvider; import org.hl7.fhir.instance.model.api.IBaseResource; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseResourceReturningMethodBinding.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseResourceReturningMethodBinding.java index 6233f6b6b0f..e3ad863f6e9 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseResourceReturningMethodBinding.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/BaseResourceReturningMethodBinding.java @@ -44,6 +44,8 @@ import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.ReflectionUtil; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.instance.model.api.IBaseOperationOutcome; @@ -56,8 +58,6 @@ import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Date; import java.util.Set; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; public abstract class BaseResourceReturningMethodBinding extends BaseMethodBinding { protected final ResponseBundleBuilder myResponseBundleBuilder; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/GraphQLMethodBinding.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/GraphQLMethodBinding.java index 7d716075a87..9a19db59c55 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/GraphQLMethodBinding.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/GraphQLMethodBinding.java @@ -33,6 +33,8 @@ import ca.uhn.fhir.rest.api.server.ResponseDetails; import ca.uhn.fhir.rest.param.ParameterUtil; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -42,8 +44,6 @@ import java.lang.reflect.Method; import java.util.Collections; import java.util.Set; import javax.annotation.Nonnull; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; public class GraphQLMethodBinding extends OperationMethodBinding { diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/MethodUtil.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/MethodUtil.java index cdfa6b625d1..a66fe54607c 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/MethodUtil.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/MethodUtil.java @@ -27,15 +27,43 @@ import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster; import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.model.api.TagList; import ca.uhn.fhir.model.api.annotation.Description; -import ca.uhn.fhir.rest.annotation.*; +import ca.uhn.fhir.rest.annotation.At; +import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; +import ca.uhn.fhir.rest.annotation.Count; +import ca.uhn.fhir.rest.annotation.Elements; +import ca.uhn.fhir.rest.annotation.GraphQLQueryBody; +import ca.uhn.fhir.rest.annotation.GraphQLQueryUrl; +import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.annotation.IncludeParam; +import ca.uhn.fhir.rest.annotation.Offset; +import ca.uhn.fhir.rest.annotation.Operation; +import ca.uhn.fhir.rest.annotation.OperationParam; +import ca.uhn.fhir.rest.annotation.OptionalParam; +import ca.uhn.fhir.rest.annotation.Patch; +import ca.uhn.fhir.rest.annotation.RawParam; +import ca.uhn.fhir.rest.annotation.RequiredParam; +import ca.uhn.fhir.rest.annotation.ResourceParam; +import ca.uhn.fhir.rest.annotation.ServerBase; +import ca.uhn.fhir.rest.annotation.Since; +import ca.uhn.fhir.rest.annotation.Sort; +import ca.uhn.fhir.rest.annotation.TransactionParam; +import ca.uhn.fhir.rest.annotation.Validate; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.rest.api.PatchTypeEnum; +import ca.uhn.fhir.rest.api.SearchContainedModeEnum; +import ca.uhn.fhir.rest.api.SearchTotalModeEnum; +import ca.uhn.fhir.rest.api.SummaryEnum; +import ca.uhn.fhir.rest.api.ValidationModeEnum; import ca.uhn.fhir.rest.api.server.RequestDetails; -import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.param.binder.CollectionBinder; import ca.uhn.fhir.rest.server.method.OperationParameter.IOperationParamConverter; import ca.uhn.fhir.rest.server.method.ResourceParameter.Mode; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.ParametersUtil; import ca.uhn.fhir.util.ReflectionUtil; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IPrimitiveType; @@ -45,8 +73,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SearchParameter.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SearchParameter.java index 29c0d40fe1f..7a4316d535e 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SearchParameter.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SearchParameter.java @@ -19,16 +19,59 @@ */ package ca.uhn.fhir.rest.server.method; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.ConfigurationException; +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.context.RuntimePrimitiveDatatypeDefinition; import ca.uhn.fhir.i18n.Msg; -import ca.uhn.fhir.model.api.*; +import ca.uhn.fhir.model.api.IQueryParameterAnd; +import ca.uhn.fhir.model.api.IQueryParameterOr; +import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.model.base.composite.BaseIdentifierDt; import ca.uhn.fhir.model.base.composite.BaseQuantityDt; import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.rest.annotation.OptionalParam; -import ca.uhn.fhir.rest.api.*; -import ca.uhn.fhir.rest.param.*; -import ca.uhn.fhir.rest.param.binder.*; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.QualifiedParamList; +import ca.uhn.fhir.rest.api.RestSearchParameterTypeEnum; +import ca.uhn.fhir.rest.param.CompositeAndListParam; +import ca.uhn.fhir.rest.param.CompositeOrListParam; +import ca.uhn.fhir.rest.param.CompositeParam; +import ca.uhn.fhir.rest.param.DateAndListParam; +import ca.uhn.fhir.rest.param.DateOrListParam; +import ca.uhn.fhir.rest.param.DateParam; +import ca.uhn.fhir.rest.param.DateRangeParam; +import ca.uhn.fhir.rest.param.HasAndListParam; +import ca.uhn.fhir.rest.param.HasOrListParam; +import ca.uhn.fhir.rest.param.HasParam; +import ca.uhn.fhir.rest.param.NumberAndListParam; +import ca.uhn.fhir.rest.param.NumberOrListParam; +import ca.uhn.fhir.rest.param.NumberParam; +import ca.uhn.fhir.rest.param.QuantityAndListParam; +import ca.uhn.fhir.rest.param.QuantityOrListParam; +import ca.uhn.fhir.rest.param.QuantityParam; +import ca.uhn.fhir.rest.param.ReferenceAndListParam; +import ca.uhn.fhir.rest.param.ReferenceOrListParam; +import ca.uhn.fhir.rest.param.ReferenceParam; +import ca.uhn.fhir.rest.param.SpecialAndListParam; +import ca.uhn.fhir.rest.param.SpecialOrListParam; +import ca.uhn.fhir.rest.param.SpecialParam; +import ca.uhn.fhir.rest.param.StringAndListParam; +import ca.uhn.fhir.rest.param.StringOrListParam; +import ca.uhn.fhir.rest.param.StringParam; +import ca.uhn.fhir.rest.param.TokenAndListParam; +import ca.uhn.fhir.rest.param.TokenOrListParam; +import ca.uhn.fhir.rest.param.TokenParam; +import ca.uhn.fhir.rest.param.UriAndListParam; +import ca.uhn.fhir.rest.param.UriOrListParam; +import ca.uhn.fhir.rest.param.UriParam; +import ca.uhn.fhir.rest.param.binder.CalendarBinder; +import ca.uhn.fhir.rest.param.binder.DateBinder; +import ca.uhn.fhir.rest.param.binder.FhirPrimitiveBinder; +import ca.uhn.fhir.rest.param.binder.IParamBinder; +import ca.uhn.fhir.rest.param.binder.QueryParameterAndBinder; +import ca.uhn.fhir.rest.param.binder.QueryParameterOrBinder; +import ca.uhn.fhir.rest.param.binder.QueryParameterTypeBinder; +import ca.uhn.fhir.rest.param.binder.StringBinder; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.util.CollectionUtil; @@ -37,7 +80,16 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IPrimitiveType; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; public class SearchParameter extends BaseQueryParameter { diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SortParameter.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SortParameter.java index 0bd2c343c75..98cf3753987 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SortParameter.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SortParameter.java @@ -19,11 +19,15 @@ */ package ca.uhn.fhir.rest.server.method; -import ca.uhn.fhir.context.*; +import ca.uhn.fhir.context.ConfigurationException; +import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.rest.annotation.Sort; +import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.SortOrderEnum; +import ca.uhn.fhir.rest.api.SortSpec; import ca.uhn.fhir.rest.api.server.RequestDetails; -import ca.uhn.fhir.rest.api.*; import ca.uhn.fhir.rest.param.ParameterUtil; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SummaryEnumParameter.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SummaryEnumParameter.java index ec6f632cba4..00ed63c3457 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SummaryEnumParameter.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/method/SummaryEnumParameter.java @@ -29,7 +29,10 @@ import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import java.lang.reflect.Method; -import java.util.*; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/provider/ServerCapabilityStatementProvider.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/provider/ServerCapabilityStatementProvider.java index d07a60d8366..1cbb83bebba 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/provider/ServerCapabilityStatementProvider.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/provider/ServerCapabilityStatementProvider.java @@ -52,6 +52,8 @@ import ca.uhn.fhir.util.ExtensionUtil; import ca.uhn.fhir.util.FhirTerser; import ca.uhn.fhir.util.HapiExtensions; import com.google.common.collect.TreeMultimap; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.text.WordUtils; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseConformance; @@ -75,8 +77,6 @@ import java.util.TreeSet; import java.util.UUID; import java.util.stream.Collectors; import javax.annotation.Nonnull; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetails.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetails.java index fead7ac698c..d8ee5d57e48 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetails.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetails.java @@ -28,6 +28,8 @@ import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.RestfulServerUtils; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.Validate; @@ -46,8 +48,6 @@ import java.util.Map; import java.util.StringTokenizer; import java.util.zip.GZIPInputStream; import javax.annotation.Nonnull; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.commons.lang3.StringUtils.trim; diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponse.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponse.java index 7b991a17c7a..b51d6ca2960 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponse.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponse.java @@ -22,6 +22,8 @@ package ca.uhn.fhir.rest.server.servlet; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.server.BaseRestfulResponse; import ca.uhn.fhir.util.IoUtil; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; @@ -35,8 +37,6 @@ import java.util.List; import java.util.Map.Entry; import java.util.zip.GZIPOutputStream; import javax.annotation.Nonnull; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; public class ServletRestfulResponse extends BaseRestfulResponse { diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletSubRequestDetails.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletSubRequestDetails.java index e57ea6b157d..77effb67ab4 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletSubRequestDetails.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletSubRequestDetails.java @@ -19,12 +19,13 @@ */ package ca.uhn.fhir.rest.server.servlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; public class ServletSubRequestDetails extends ServletRequestDetails { diff --git a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/util/ITestingUiClientFactory.java b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/util/ITestingUiClientFactory.java index 7692cd61767..9058a0cd0d9 100644 --- a/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/util/ITestingUiClientFactory.java +++ b/hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/util/ITestingUiClientFactory.java @@ -21,8 +21,7 @@ package ca.uhn.fhir.rest.server.util; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.client.api.IGenericClient; - -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** * This interface isn't used by hapi-fhir-base, but is used by the diff --git a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/IncomingRequestAddressStrategyTest.java b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/IncomingRequestAddressStrategyTest.java index d80f8dcf6f3..723aa57633b 100644 --- a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/IncomingRequestAddressStrategyTest.java +++ b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/IncomingRequestAddressStrategyTest.java @@ -2,7 +2,7 @@ package ca.uhn.fhir.rest.server; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertNull; public class IncomingRequestAddressStrategyTest { diff --git a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/SimpleBundleProviderTest.java b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/SimpleBundleProviderTest.java index a80f58d2bba..07d3f5e2e66 100644 --- a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/SimpleBundleProviderTest.java +++ b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/SimpleBundleProviderTest.java @@ -2,7 +2,7 @@ package ca.uhn.fhir.rest.server; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; public class SimpleBundleProviderTest { diff --git a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/interceptor/ConfigLoaderTest.java b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/interceptor/ConfigLoaderTest.java index fe377df7773..9694eccae74 100644 --- a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/interceptor/ConfigLoaderTest.java +++ b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/interceptor/ConfigLoaderTest.java @@ -5,7 +5,9 @@ import org.junit.jupiter.api.Test; import java.util.Map; import java.util.Properties; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; class ConfigLoaderTest { diff --git a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/method/ConformanceMethodBindingTest.java b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/method/ConformanceMethodBindingTest.java index af3c956d1d8..2648b618be3 100644 --- a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/method/ConformanceMethodBindingTest.java +++ b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/method/ConformanceMethodBindingTest.java @@ -16,7 +16,7 @@ import org.mockito.Answers; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.lang.reflect.Method; import static org.mockito.ArgumentMatchers.any; diff --git a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/method/MethodMatchEnumTest.java b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/method/MethodMatchEnumTest.java index a91acb56545..2cfa9aae844 100644 --- a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/method/MethodMatchEnumTest.java +++ b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/method/MethodMatchEnumTest.java @@ -2,7 +2,7 @@ package ca.uhn.fhir.rest.server.method; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; public class MethodMatchEnumTest { diff --git a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetailsTest.java b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetailsTest.java index 799a7f77482..3eeb771b22f 100644 --- a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetailsTest.java +++ b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetailsTest.java @@ -3,7 +3,7 @@ package ca.uhn.fhir.rest.server.servlet; import ca.uhn.fhir.rest.api.Constants; import org.junit.jupiter.api.Test; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponseTest.java b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponseTest.java index bb28d105053..bb6e6b97979 100644 --- a/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponseTest.java +++ b/hapi-fhir-server/src/test/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponseTest.java @@ -10,7 +10,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/hapi-fhir-serviceloaders/hapi-fhir-caching-api/pom.xml b/hapi-fhir-serviceloaders/hapi-fhir-caching-api/pom.xml index 2efd21502bb..153d21bec27 100644 --- a/hapi-fhir-serviceloaders/hapi-fhir-caching-api/pom.xml +++ b/hapi-fhir-serviceloaders/hapi-fhir-caching-api/pom.xml @@ -7,7 +7,7 @@ hapi-fhir-serviceloaders ca.uhn.hapi.fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../pom.xml diff --git a/hapi-fhir-serviceloaders/hapi-fhir-caching-caffeine/pom.xml b/hapi-fhir-serviceloaders/hapi-fhir-caching-caffeine/pom.xml index 3db18cec3bb..577b77c3056 100644 --- a/hapi-fhir-serviceloaders/hapi-fhir-caching-caffeine/pom.xml +++ b/hapi-fhir-serviceloaders/hapi-fhir-caching-caffeine/pom.xml @@ -7,7 +7,7 @@ hapi-fhir-serviceloaders ca.uhn.hapi.fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../pom.xml @@ -21,7 +21,7 @@ ca.uhn.hapi.fhir hapi-fhir-caching-api - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT diff --git a/hapi-fhir-serviceloaders/hapi-fhir-caching-guava/pom.xml b/hapi-fhir-serviceloaders/hapi-fhir-caching-guava/pom.xml index 341ac8b5cfd..789346cd68a 100644 --- a/hapi-fhir-serviceloaders/hapi-fhir-caching-guava/pom.xml +++ b/hapi-fhir-serviceloaders/hapi-fhir-caching-guava/pom.xml @@ -7,7 +7,7 @@ hapi-fhir-serviceloaders ca.uhn.hapi.fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../pom.xml diff --git a/hapi-fhir-serviceloaders/hapi-fhir-caching-testing/pom.xml b/hapi-fhir-serviceloaders/hapi-fhir-caching-testing/pom.xml index ef1e667f1e8..26a01f302a4 100644 --- a/hapi-fhir-serviceloaders/hapi-fhir-caching-testing/pom.xml +++ b/hapi-fhir-serviceloaders/hapi-fhir-caching-testing/pom.xml @@ -7,7 +7,7 @@ hapi-fhir ca.uhn.hapi.fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../../pom.xml diff --git a/hapi-fhir-serviceloaders/pom.xml b/hapi-fhir-serviceloaders/pom.xml index b2ffa705596..830172b35a3 100644 --- a/hapi-fhir-serviceloaders/pom.xml +++ b/hapi-fhir-serviceloaders/pom.xml @@ -5,7 +5,7 @@ hapi-deployable-pom ca.uhn.hapi.fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-autoconfigure/pom.xml b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-autoconfigure/pom.xml index 627cefbce72..11e06f6bf2b 100644 --- a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-autoconfigure/pom.xml +++ b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-autoconfigure/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../../hapi-deployable-pom/pom.xml @@ -60,8 +60,8 @@ true - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api true diff --git a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-autoconfigure/src/main/java/ca/uhn/fhir/spring/boot/autoconfigure/FhirAutoConfiguration.java b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-autoconfigure/src/main/java/ca/uhn/fhir/spring/boot/autoconfigure/FhirAutoConfiguration.java index 2e524810521..66f674ab2fb 100644 --- a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-autoconfigure/src/main/java/ca/uhn/fhir/spring/boot/autoconfigure/FhirAutoConfiguration.java +++ b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-autoconfigure/src/main/java/ca/uhn/fhir/spring/boot/autoconfigure/FhirAutoConfiguration.java @@ -45,6 +45,8 @@ import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor; import ca.uhn.fhir.rest.server.interceptor.RequestValidatingInterceptor; import ca.uhn.fhir.rest.server.interceptor.ResponseValidatingInterceptor; +import jakarta.persistence.EntityManagerFactory; +import jakarta.servlet.ServletException; import okhttp3.OkHttpClient; import org.apache.http.client.HttpClient; import org.springframework.beans.factory.ObjectProvider; @@ -75,8 +77,6 @@ import org.springframework.util.CollectionUtils; import java.util.List; import java.util.concurrent.ScheduledExecutorService; -import javax.persistence.EntityManagerFactory; -import javax.servlet.ServletException; import javax.sql.DataSource; /** diff --git a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-client-apache/pom.xml b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-client-apache/pom.xml index 1c49210557f..f7e1fc2f252 100644 --- a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-client-apache/pom.xml +++ b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-client-apache/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-fhir-spring-boot-samples - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT hapi-fhir-spring-boot-sample-client-apache diff --git a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-client-okhttp/pom.xml b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-client-okhttp/pom.xml index e7e3ddb3c43..ed42f43c5bb 100644 --- a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-client-okhttp/pom.xml +++ b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-client-okhttp/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-fhir-spring-boot-samples - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT diff --git a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-server-jersey/pom.xml b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-server-jersey/pom.xml index 90d0122dc8c..14c6b0a2b61 100644 --- a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-server-jersey/pom.xml +++ b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-server-jersey/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-fhir-spring-boot-samples - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT diff --git a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-server-jersey/src/main/java/sample/fhir/server/jersey/provider/PatientResourceProvider.java b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-server-jersey/src/main/java/sample/fhir/server/jersey/provider/PatientResourceProvider.java index f5866d7e615..9c11a4ed57f 100644 --- a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-server-jersey/src/main/java/sample/fhir/server/jersey/provider/PatientResourceProvider.java +++ b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-samples/hapi-fhir-spring-boot-sample-server-jersey/src/main/java/sample/fhir/server/jersey/provider/PatientResourceProvider.java @@ -50,8 +50,8 @@ public class PatientResourceProvider extends AbstractJaxRsResourceProvider ca.uhn.hapi.fhir hapi-fhir-spring-boot - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT diff --git a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-starter/pom.xml b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-starter/pom.xml index 9c442072b80..e833cf5256a 100644 --- a/hapi-fhir-spring-boot/hapi-fhir-spring-boot-starter/pom.xml +++ b/hapi-fhir-spring-boot/hapi-fhir-spring-boot-starter/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-spring-boot/pom.xml b/hapi-fhir-spring-boot/pom.xml index 4e9363295a7..6824520b126 100644 --- a/hapi-fhir-spring-boot/pom.xml +++ b/hapi-fhir-spring-boot/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-fhir - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../pom.xml diff --git a/hapi-fhir-sql-migrate/pom.xml b/hapi-fhir-sql-migrate/pom.xml index 53ddb291362..dbbbc4b1d7a 100644 --- a/hapi-fhir-sql-migrate/pom.xml +++ b/hapi-fhir-sql-migrate/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -32,7 +32,7 @@ - org.hibernate + org.hibernate.orm hibernate-core diff --git a/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/DriverTypeEnum.java b/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/DriverTypeEnum.java index 0c49ad0ab9b..1eadeca435b 100644 --- a/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/DriverTypeEnum.java +++ b/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/DriverTypeEnum.java @@ -84,26 +84,26 @@ public enum DriverTypeEnum { String retval; switch (this) { case H2_EMBEDDED: - retval = "hapifhirh2.sql"; + retval = "h2.sql"; break; case DERBY_EMBEDDED: - retval = "derbytenseven.sql"; + retval = "derby.sql"; break; case MYSQL_5_7: case MARIADB_10_1: - retval = "mysql57.sql"; + retval = "mysql.sql"; break; case POSTGRES_9_4: - retval = "hapifhirpostgres94-complete.sql"; + retval = "postgres.sql"; break; case ORACLE_12C: - retval = "oracle12c.sql"; + retval = "oracle.sql"; break; case MSSQL_2012: - retval = "sqlserver2012.sql"; + retval = "sqlserver.sql"; break; case COCKROACHDB_21_1: - retval = "cockroachdb201.sql"; + retval = "cockroachdb.sql"; break; default: throw new ConfigurationException( diff --git a/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/JdbcUtils.java b/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/JdbcUtils.java index b9863105de6..551407f8e05 100644 --- a/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/JdbcUtils.java +++ b/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/JdbcUtils.java @@ -39,6 +39,7 @@ import org.hibernate.engine.jdbc.env.spi.NameQualifierSupport; import org.hibernate.engine.jdbc.env.spi.QualifiedObjectNameFormatter; import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; import org.hibernate.service.ServiceRegistry; +import org.hibernate.sql.ast.SqlAstTranslatorFactory; import org.hibernate.tool.schema.extract.spi.ExtractionContext; import org.hibernate.tool.schema.extract.spi.SequenceInformation; import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor; @@ -46,6 +47,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.ColumnMapRowMapper; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.LinkedCaseInsensitiveMap; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -230,6 +232,8 @@ public class JdbcUtils { return new ColumnType(ColumnTypeEnum.DOUBLE, length); case Types.FLOAT: return new ColumnType(ColumnTypeEnum.FLOAT, length); + case Types.TINYINT: + return new ColumnType(ColumnTypeEnum.TINYINT, length); default: throw new IllegalArgumentException(Msg.code(34) + "Don't know how to handle datatype " + dataType + " for column " + theColumnName + " on table " + theTableName); @@ -357,7 +361,7 @@ public class JdbcUtils { massageIdentifier(metadata, theTableName), null); - Set columnNames = new HashSet<>(); + LinkedCaseInsensitiveMap columnNames = new LinkedCaseInsensitiveMap<>(); while (indexes.next()) { String tableName = indexes.getString("TABLE_NAME").toUpperCase(Locale.US); if (!theTableName.equalsIgnoreCase(tableName)) { @@ -366,10 +370,10 @@ public class JdbcUtils { String columnName = indexes.getString("COLUMN_NAME"); columnName = columnName.toUpperCase(Locale.US); - columnNames.add(columnName); + columnNames.put(columnName, columnName); } - return columnNames; + return columnNames.keySet(); } catch (SQLException e) { throw new InternalErrorException(Msg.code(38) + e); } @@ -388,7 +392,7 @@ public class JdbcUtils { new DatabaseMetaDataDialectResolutionInfoAdapter(connection.getMetaData())); Set sequenceNames = new HashSet<>(); - if (dialect.supportsSequences()) { + if (dialect.getSequenceSupport().supportsSequences()) { // Use Hibernate to get a list of current sequences SequenceInformationExtractor sequenceInformationExtractor = @@ -412,6 +416,11 @@ public class JdbcUtils { return dialect; } + @Override + public SqlAstTranslatorFactory getSqlAstTranslatorFactory() { + return null; + } + @Override public ExtractedDatabaseMetaData getExtractedDatabaseMetaData() { return null; @@ -435,7 +444,7 @@ public class JdbcUtils { @Override public IdentifierHelper getIdentifierHelper() { return new NormalizingIdentifierHelperImpl( - this, null, true, true, true, null, null, null); + this, null, true, true, true, true, null, null, null); } @Override diff --git a/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/entity/HapiMigrationEntity.java b/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/entity/HapiMigrationEntity.java index 7e9db2b7e3d..7ae686d268f 100644 --- a/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/entity/HapiMigrationEntity.java +++ b/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/entity/HapiMigrationEntity.java @@ -21,16 +21,16 @@ package ca.uhn.fhir.jpa.migrate.entity; import ca.uhn.fhir.jpa.migrate.taskdef.BaseTask; import ca.uhn.fhir.util.VersionEnum; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; import org.hibernate.annotations.GenericGenerator; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.RowMapper; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; // Note even though we are using javax.persistence annotations here, we are managing these records outside of jpa // so these annotations are for informational purposes only diff --git a/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/taskdef/ColumnTypeEnum.java b/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/taskdef/ColumnTypeEnum.java index d78223f7773..8c894e824c6 100644 --- a/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/taskdef/ColumnTypeEnum.java +++ b/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/taskdef/ColumnTypeEnum.java @@ -31,5 +31,11 @@ public enum ColumnTypeEnum { BLOB, CLOB, DOUBLE, - TEXT; + + /** + * Unlimited length text, with a column definition containing the annotation: + * @JdbcTypeCode(SqlTypes.LONG32VARCHAR) + */ + TEXT, + BIG_DECIMAL; } diff --git a/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/taskdef/ColumnTypeToDriverTypeToSqlType.java b/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/taskdef/ColumnTypeToDriverTypeToSqlType.java index 03b222718cd..97ec7c8c673 100644 --- a/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/taskdef/ColumnTypeToDriverTypeToSqlType.java +++ b/hapi-fhir-sql-migrate/src/main/java/ca/uhn/fhir/jpa/migrate/taskdef/ColumnTypeToDriverTypeToSqlType.java @@ -123,13 +123,21 @@ public final class ColumnTypeToDriverTypeToSqlType { "oid"); // the PG driver will write oid into a `text` column setColumnType(ColumnTypeEnum.CLOB, DriverTypeEnum.MSSQL_2012, "varchar(MAX)"); - setColumnType(ColumnTypeEnum.TEXT, DriverTypeEnum.H2_EMBEDDED, "character varying"); - setColumnType(ColumnTypeEnum.TEXT, DriverTypeEnum.DERBY_EMBEDDED, "long varchar"); + setColumnType(ColumnTypeEnum.TEXT, DriverTypeEnum.H2_EMBEDDED, "character large object"); + setColumnType(ColumnTypeEnum.TEXT, DriverTypeEnum.DERBY_EMBEDDED, "clob"); setColumnType(ColumnTypeEnum.TEXT, DriverTypeEnum.MARIADB_10_1, "longtext"); setColumnType(ColumnTypeEnum.TEXT, DriverTypeEnum.MYSQL_5_7, "longtext"); - setColumnType(ColumnTypeEnum.TEXT, DriverTypeEnum.ORACLE_12C, "long"); + setColumnType(ColumnTypeEnum.TEXT, DriverTypeEnum.ORACLE_12C, "clob"); setColumnType(ColumnTypeEnum.TEXT, DriverTypeEnum.POSTGRES_9_4, "text"); setColumnType(ColumnTypeEnum.TEXT, DriverTypeEnum.MSSQL_2012, "varchar(MAX)"); + + setColumnType(ColumnTypeEnum.BIG_DECIMAL, DriverTypeEnum.H2_EMBEDDED, "numeric(38,2)"); + setColumnType(ColumnTypeEnum.BIG_DECIMAL, DriverTypeEnum.DERBY_EMBEDDED, "decimal(31,2)"); + setColumnType(ColumnTypeEnum.BIG_DECIMAL, DriverTypeEnum.MARIADB_10_1, "decimal(38,2)"); + setColumnType(ColumnTypeEnum.BIG_DECIMAL, DriverTypeEnum.MYSQL_5_7, "decimal(38,2)"); + setColumnType(ColumnTypeEnum.BIG_DECIMAL, DriverTypeEnum.ORACLE_12C, "number(38,2)"); + setColumnType(ColumnTypeEnum.BIG_DECIMAL, DriverTypeEnum.POSTGRES_9_4, "numeric(38,2)"); + setColumnType(ColumnTypeEnum.BIG_DECIMAL, DriverTypeEnum.MSSQL_2012, "numeric(38,2)"); } public static Map> getColumnTypeToDriverTypeToSqlType() { diff --git a/hapi-fhir-sql-migrate/src/test/java/ca/uhn/fhir/jpa/migrate/taskdef/AddColumnTest.java b/hapi-fhir-sql-migrate/src/test/java/ca/uhn/fhir/jpa/migrate/taskdef/AddColumnTest.java index 77620832c74..f22a01fb5a5 100644 --- a/hapi-fhir-sql-migrate/src/test/java/ca/uhn/fhir/jpa/migrate/taskdef/AddColumnTest.java +++ b/hapi-fhir-sql-migrate/src/test/java/ca/uhn/fhir/jpa/migrate/taskdef/AddColumnTest.java @@ -93,7 +93,7 @@ public class AddColumnTest extends BaseTest { getMigrator().migrate(); fail(); } catch (HapiMigrationException e) { - assertThat(e.getMessage(), startsWith("HAPI-0047: Failure executing task \"Add column FOO_COLUMN on table FOO_TABLE\", aborting! Cause: ca.uhn.fhir.jpa.migrate.HapiMigrationException: HAPI-0061: Failed during task 4.0.0.2001.01: ")); + assertThat(e.getMessage(), startsWith("HAPI-0047: Failure executing task \"Add column foo_column on table FOO_TABLE\", aborting! Cause: ca.uhn.fhir.jpa.migrate.HapiMigrationException: HAPI-0061: Failed during task 4.0.0.2001.01: ")); } } diff --git a/hapi-fhir-storage-batch2-jobs/pom.xml b/hapi-fhir-storage-batch2-jobs/pom.xml index 87c80e9aea2..6b5bfb0f4cc 100644 --- a/hapi-fhir-storage-batch2-jobs/pom.xml +++ b/hapi-fhir-storage-batch2-jobs/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -26,8 +26,8 @@ - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided diff --git a/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/export/BulkDataExportProvider.java b/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/export/BulkDataExportProvider.java index f35052d3156..928c1f45f45 100644 --- a/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/export/BulkDataExportProvider.java +++ b/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/export/BulkDataExportProvider.java @@ -62,6 +62,7 @@ import ca.uhn.fhir.util.OperationOutcomeUtil; import ca.uhn.fhir.util.SearchParameterUtil; import ca.uhn.fhir.util.UrlUtil; import com.google.common.annotations.VisibleForTesting; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.instance.model.api.IBaseOperationOutcome; import org.hl7.fhir.instance.model.api.IIdType; @@ -83,7 +84,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import javax.servlet.http.HttpServletResponse; import static ca.uhn.fhir.rest.api.server.bulk.BulkExportJobParameters.ExportStyle; import static ca.uhn.fhir.util.DatatypeUtil.toStringValue; diff --git a/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkDataImportProvider.java b/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkDataImportProvider.java index 6e2396a6401..ecef4c12c05 100644 --- a/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkDataImportProvider.java +++ b/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkDataImportProvider.java @@ -38,6 +38,7 @@ import ca.uhn.fhir.util.OperationOutcomeUtil; import ca.uhn.fhir.util.ParametersUtil; import ca.uhn.fhir.util.UrlUtil; import ca.uhn.fhir.util.ValidateUtil; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.hl7.fhir.instance.model.api.IBase; @@ -57,7 +58,6 @@ import java.util.Date; import java.util.List; import java.util.Optional; import javax.annotation.Nonnull; -import javax.servlet.http.HttpServletResponse; import static ca.uhn.fhir.batch2.jobs.export.BulkDataExportProvider.validatePreferAsyncHeader; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkImportFileServlet.java b/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkImportFileServlet.java index c0579dd167d..6f69dfe9eb6 100644 --- a/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkImportFileServlet.java +++ b/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkImportFileServlet.java @@ -24,6 +24,9 @@ import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import ca.uhn.fhir.util.UrlUtil; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.ReaderInputStream; import org.slf4j.Logger; @@ -38,9 +41,6 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static ca.uhn.fhir.rest.api.Constants.CHARSET_UTF8_CTSUFFIX; import static ca.uhn.fhir.rest.api.Constants.CT_FHIR_NDJSON; diff --git a/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkImportJobParameters.java b/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkImportJobParameters.java index 22077e858ac..4a40f45b09f 100644 --- a/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkImportJobParameters.java +++ b/hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/BulkImportJobParameters.java @@ -22,15 +22,15 @@ package ca.uhn.fhir.batch2.jobs.imprt; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.model.api.IModelJson; import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; import org.apache.commons.lang3.Validate; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; /** * This class is the parameters model object for starting a diff --git a/hapi-fhir-storage-batch2-jobs/src/test/java/ca/uhn/fhir/batch2/jobs/BaseR4ServerTest.java b/hapi-fhir-storage-batch2-jobs/src/test/java/ca/uhn/fhir/batch2/jobs/BaseR4ServerTest.java index 0b631445657..23fe01f5fb2 100644 --- a/hapi-fhir-storage-batch2-jobs/src/test/java/ca/uhn/fhir/batch2/jobs/BaseR4ServerTest.java +++ b/hapi-fhir-storage-batch2-jobs/src/test/java/ca/uhn/fhir/batch2/jobs/BaseR4ServerTest.java @@ -8,8 +8,8 @@ import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.test.utilities.JettyUtil; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterEach; public class BaseR4ServerTest { diff --git a/hapi-fhir-storage-batch2-jobs/src/test/java/ca/uhn/fhir/batch2/jobs/imprt/BulkDataImportProviderTest.java b/hapi-fhir-storage-batch2-jobs/src/test/java/ca/uhn/fhir/batch2/jobs/imprt/BulkDataImportProviderTest.java index 7ba6807d180..69aea5aed76 100644 --- a/hapi-fhir-storage-batch2-jobs/src/test/java/ca/uhn/fhir/batch2/jobs/imprt/BulkDataImportProviderTest.java +++ b/hapi-fhir-storage-batch2-jobs/src/test/java/ca/uhn/fhir/batch2/jobs/imprt/BulkDataImportProviderTest.java @@ -279,7 +279,7 @@ public class BulkDataImportProviderTest { assertEquals(202, response.getStatusLine().getStatusCode()); assertEquals("Accepted", response.getStatusLine().getReasonPhrase()); assertEquals("120", response.getFirstHeader(Constants.HEADER_RETRY_AFTER).getValue()); - assertThat(response.getFirstHeader(Constants.HEADER_X_PROGRESS).getValue(), containsString("Job was created at 2022-01-01")); + assertThat(response.getFirstHeader(Constants.HEADER_X_PROGRESS).getValue(), containsString("Job was created at 2022-01")); } } diff --git a/hapi-fhir-storage-batch2-test-utilities/pom.xml b/hapi-fhir-storage-batch2-test-utilities/pom.xml index ab92cdf2bff..57f9d4347cf 100644 --- a/hapi-fhir-storage-batch2-test-utilities/pom.xml +++ b/hapi-fhir-storage-batch2-test-utilities/pom.xml @@ -7,7 +7,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-storage-batch2-test-utilities/src/main/java/ca/uhn/hapi/fhir/batch2/test/support/TestJobParameters.java b/hapi-fhir-storage-batch2-test-utilities/src/main/java/ca/uhn/hapi/fhir/batch2/test/support/TestJobParameters.java index 9ae48d15300..9c6cd0832ca 100644 --- a/hapi-fhir-storage-batch2-test-utilities/src/main/java/ca/uhn/hapi/fhir/batch2/test/support/TestJobParameters.java +++ b/hapi-fhir-storage-batch2-test-utilities/src/main/java/ca/uhn/hapi/fhir/batch2/test/support/TestJobParameters.java @@ -24,7 +24,7 @@ import ca.uhn.fhir.model.api.annotation.PasswordField; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.Length; -import javax.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotBlank; public class TestJobParameters implements IModelJson { diff --git a/hapi-fhir-storage-batch2/pom.xml b/hapi-fhir-storage-batch2/pom.xml index 5329617d4fc..803455a67d2 100644 --- a/hapi-fhir-storage-batch2/pom.xml +++ b/hapi-fhir-storage-batch2/pom.xml @@ -7,7 +7,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -20,6 +20,18 @@ + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + test + + ca.uhn.hapi.fhir hapi-fhir-base @@ -50,6 +62,7 @@ org.hibernate.validator hibernate-validator + org.glassfish jakarta.el @@ -72,11 +85,6 @@ spring-test test - - ch.qos.logback - logback-classic - test - org.springframework.data spring-data-commons diff --git a/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/coordinator/JobCoordinatorImpl.java b/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/coordinator/JobCoordinatorImpl.java index a8935f5046a..adc1f4e9fe7 100644 --- a/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/coordinator/JobCoordinatorImpl.java +++ b/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/coordinator/JobCoordinatorImpl.java @@ -39,6 +39,8 @@ import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import ca.uhn.fhir.util.Logs; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.springframework.data.domain.Page; @@ -53,8 +55,6 @@ import java.util.List; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/coordinator/JobParameterJsonValidator.java b/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/coordinator/JobParameterJsonValidator.java index 279d0d8d9e0..abf03a8a1df 100644 --- a/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/coordinator/JobParameterJsonValidator.java +++ b/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/coordinator/JobParameterJsonValidator.java @@ -26,16 +26,16 @@ import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.model.api.IModelJson; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nonnull; -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; diff --git a/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/jobs/parameters/PartitionedUrl.java b/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/jobs/parameters/PartitionedUrl.java index 5504f50c4b2..9990b79070e 100644 --- a/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/jobs/parameters/PartitionedUrl.java +++ b/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/jobs/parameters/PartitionedUrl.java @@ -22,11 +22,10 @@ package ca.uhn.fhir.batch2.jobs.parameters; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.model.api.IModelJson; import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.constraints.Pattern; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import javax.validation.constraints.Pattern; - public class PartitionedUrl implements IModelJson { @Override public String toString() { diff --git a/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/model/JobDefinition.java b/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/model/JobDefinition.java index 8a7aea8190b..a2777a2bcbd 100644 --- a/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/model/JobDefinition.java +++ b/hapi-fhir-storage-batch2/src/main/java/ca/uhn/fhir/batch2/model/JobDefinition.java @@ -345,8 +345,8 @@ public class JobDefinition { *

    * Validation: * Fields should be annotated with - * any appropriate javax.validation (JSR 380) annotations (e.g. - * {@link javax.validation.constraints.Min} or {@link javax.validation.constraints.Pattern}). + * any appropriate jakarta.validation (JSR 380) annotations (e.g. + * {@link jakarta.validation.constraints.Min} or {@link jakarta.validation.constraints.Pattern}). * In addition, if there are validation rules that are too complex to express using * JSR 380, you can also specify a programmatic validator using {@link #setParametersValidator(IJobParametersValidator)}. *

    @@ -357,7 +357,7 @@ public class JobDefinition { *

    * * @see ca.uhn.fhir.model.api.annotation.PasswordField - * @see javax.validation.constraints + * @see jakarta.validation.constraints * @see JobDefinition.Builder#setParametersValidator(IJobParametersValidator) */ @SuppressWarnings("unchecked") diff --git a/hapi-fhir-storage-batch2/src/test/java/ca/uhn/fhir/batch2/coordinator/TestJobParameters.java b/hapi-fhir-storage-batch2/src/test/java/ca/uhn/fhir/batch2/coordinator/TestJobParameters.java index bea3a00065f..3bfb3b14ca3 100644 --- a/hapi-fhir-storage-batch2/src/test/java/ca/uhn/fhir/batch2/coordinator/TestJobParameters.java +++ b/hapi-fhir-storage-batch2/src/test/java/ca/uhn/fhir/batch2/coordinator/TestJobParameters.java @@ -5,7 +5,7 @@ import ca.uhn.fhir.model.api.IModelJson; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.Length; -import javax.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotBlank; public class TestJobParameters implements IModelJson { diff --git a/hapi-fhir-storage-batch2/src/test/java/ca/uhn/fhir/batch2/maintenance/JobMaintenanceServiceImplTest.java b/hapi-fhir-storage-batch2/src/test/java/ca/uhn/fhir/batch2/maintenance/JobMaintenanceServiceImplTest.java index 13104c12187..ba11ac13560 100644 --- a/hapi-fhir-storage-batch2/src/test/java/ca/uhn/fhir/batch2/maintenance/JobMaintenanceServiceImplTest.java +++ b/hapi-fhir-storage-batch2/src/test/java/ca/uhn/fhir/batch2/maintenance/JobMaintenanceServiceImplTest.java @@ -19,6 +19,7 @@ import ca.uhn.fhir.batch2.model.WorkChunkStatusEnum; import ca.uhn.fhir.jpa.api.config.JpaStorageSettings; import ca.uhn.fhir.jpa.model.sched.ISchedulerService; import ca.uhn.fhir.jpa.subscription.channel.api.IChannelProducer; +import ca.uhn.fhir.util.Logs; import ca.uhn.test.util.LogbackCaptureTestExtension; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; @@ -34,6 +35,7 @@ import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.LoggerFactory; import org.springframework.messaging.Message; import java.util.Arrays; @@ -68,7 +70,7 @@ import static org.mockito.Mockito.when; public class JobMaintenanceServiceImplTest extends BaseBatch2Test { @RegisterExtension - LogbackCaptureTestExtension myLogCapture = new LogbackCaptureTestExtension((Logger) JobMaintenanceServiceImpl.ourLog, Level.WARN); + LogbackCaptureTestExtension myLogCapture = new LogbackCaptureTestExtension((Logger) LoggerFactory.getLogger("ca.uhn.fhir.log.batch_troubleshooting"), Level.WARN); @Mock IJobCompletionHandler myCompletionHandler; @Mock diff --git a/hapi-fhir-storage-cr/pom.xml b/hapi-fhir-storage-cr/pom.xml index aaa18119b78..c28054aa757 100644 --- a/hapi-fhir-storage-cr/pom.xml +++ b/hapi-fhir-storage-cr/pom.xml @@ -7,7 +7,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -94,6 +94,11 @@ + + com.fasterxml.jackson.module + jackson-module-jakarta-xmlbind-annotations + + ca.uhn.hapi.fhir hapi-fhir-converter @@ -134,23 +139,16 @@ ${spring-security-core.version} - + + jakarta.servlet + jakarta.servlet-api + - These dependencies are added/swapped because the - Clinical Reasoning components no longer include it. - These will need to be adjusted / removed as soon as - the HAPI Jakarta PR hits --> - javax.servlet - javax.servlet-api + jakarta.xml.bind + jakarta.xml.bind-api - - javax.xml.bind - jaxb-api - 2.3.1 - - diff --git a/hapi-fhir-storage-cr/src/test/java/ca/uhn/fhir/cr/dstu3/BaseCrDstu3TestServer.java b/hapi-fhir-storage-cr/src/test/java/ca/uhn/fhir/cr/dstu3/BaseCrDstu3TestServer.java index b88bb544a63..de10ff63f25 100644 --- a/hapi-fhir-storage-cr/src/test/java/ca/uhn/fhir/cr/dstu3/BaseCrDstu3TestServer.java +++ b/hapi-fhir-storage-cr/src/test/java/ca/uhn/fhir/cr/dstu3/BaseCrDstu3TestServer.java @@ -19,8 +19,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.Resource; import org.junit.jupiter.api.AfterEach; diff --git a/hapi-fhir-storage-cr/src/test/java/ca/uhn/fhir/cr/r4/BaseCrR4TestServer.java b/hapi-fhir-storage-cr/src/test/java/ca/uhn/fhir/cr/r4/BaseCrR4TestServer.java index 1495d4ad4b5..a4449b3f0d1 100644 --- a/hapi-fhir-storage-cr/src/test/java/ca/uhn/fhir/cr/r4/BaseCrR4TestServer.java +++ b/hapi-fhir-storage-cr/src/test/java/ca/uhn/fhir/cr/r4/BaseCrR4TestServer.java @@ -26,8 +26,8 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Resource; import org.junit.jupiter.api.AfterEach; diff --git a/hapi-fhir-storage-mdm/pom.xml b/hapi-fhir-storage-mdm/pom.xml index 2af9a4e6dbc..0a0a3ba68ca 100644 --- a/hapi-fhir-storage-mdm/pom.xml +++ b/hapi-fhir-storage-mdm/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-storage-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmSubmitterInterceptorLoader.java b/hapi-fhir-storage-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmSubmitterInterceptorLoader.java index 1e5cb18bcfd..eac3ab35686 100644 --- a/hapi-fhir-storage-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmSubmitterInterceptorLoader.java +++ b/hapi-fhir-storage-mdm/src/main/java/ca/uhn/fhir/jpa/mdm/interceptor/MdmSubmitterInterceptorLoader.java @@ -27,12 +27,11 @@ import ca.uhn.fhir.mdm.api.IMdmSettings; import ca.uhn.fhir.mdm.interceptor.IMdmStorageInterceptor; import ca.uhn.fhir.mdm.interceptor.MdmSearchExpandingInterceptor; import ca.uhn.fhir.mdm.log.Logs; +import jakarta.annotation.PostConstruct; import org.hl7.fhir.dstu2.model.Subscription; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; -import javax.annotation.PostConstruct; - public class MdmSubmitterInterceptorLoader { private static final Logger ourLog = Logs.getMdmTroubleshootingLog(); diff --git a/hapi-fhir-storage-mdm/src/main/java/ca/uhn/fhir/mdm/batch2/clear/MdmClearJobParameters.java b/hapi-fhir-storage-mdm/src/main/java/ca/uhn/fhir/mdm/batch2/clear/MdmClearJobParameters.java index fed4b7d3615..3219c11152f 100644 --- a/hapi-fhir-storage-mdm/src/main/java/ca/uhn/fhir/mdm/batch2/clear/MdmClearJobParameters.java +++ b/hapi-fhir-storage-mdm/src/main/java/ca/uhn/fhir/mdm/batch2/clear/MdmClearJobParameters.java @@ -21,12 +21,12 @@ package ca.uhn.fhir.mdm.batch2.clear; import ca.uhn.fhir.batch2.jobs.parameters.PartitionedJobParameters; import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.constraints.Pattern; import org.apache.commons.lang3.Validate; import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; -import javax.validation.constraints.Pattern; public class MdmClearJobParameters extends PartitionedJobParameters { @JsonProperty("resourceType") diff --git a/hapi-fhir-storage-test-utilities/pom.xml b/hapi-fhir-storage-test-utilities/pom.xml index 9a46e263b1e..4c7ab58eb6c 100644 --- a/hapi-fhir-storage-test-utilities/pom.xml +++ b/hapi-fhir-storage-test-utilities/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml diff --git a/hapi-fhir-storage/pom.xml b/hapi-fhir-storage/pom.xml index d5a2887d24f..f199f69626a 100644 --- a/hapi-fhir-storage/pom.xml +++ b/hapi-fhir-storage/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -85,7 +85,7 @@ org.hibernate.search - hibernate-search-mapper-orm + hibernate-search-mapper-orm-orm6 org.hibernate.search @@ -132,8 +132,8 @@ - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/cache/BaseResourceCacheSynchronizer.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/cache/BaseResourceCacheSynchronizer.java index dc05cb761ee..197f19e6572 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/cache/BaseResourceCacheSynchronizer.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/cache/BaseResourceCacheSynchronizer.java @@ -32,6 +32,8 @@ import ca.uhn.fhir.rest.api.server.SystemRequestDetails; import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import ca.uhn.fhir.subscription.SubscriptionConstants; import com.google.common.annotations.VisibleForTesting; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import org.apache.commons.lang3.time.DateUtils; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; @@ -47,8 +49,6 @@ import java.util.List; import java.util.concurrent.Semaphore; import java.util.stream.Collectors; import javax.annotation.Nonnull; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; public abstract class BaseResourceCacheSynchronizer implements IResourceChangeListener { private static final Logger ourLog = LoggerFactory.getLogger(BaseResourceCacheSynchronizer.class); diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDao.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDao.java index 176983551fb..35a87a736d1 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDao.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDao.java @@ -42,6 +42,7 @@ import ca.uhn.fhir.rest.param.HistorySearchDateRangeParam; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.ResourceGoneException; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; +import jakarta.servlet.http.HttpServletResponse; import org.hl7.fhir.instance.model.api.IBaseMetaType; import org.hl7.fhir.instance.model.api.IBaseParameters; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -54,7 +55,6 @@ import java.util.Map; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.servlet.http.HttpServletResponse; /** * Note that this interface is not considered a stable interface. While it is possible to build applications diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoComposition.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoComposition.java index a269de9bec5..5fd5cadaadc 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoComposition.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoComposition.java @@ -23,12 +23,11 @@ import ca.uhn.fhir.rest.api.SortSpec; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.param.DateRangeParam; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.instance.model.api.IPrimitiveType; -import javax.servlet.http.HttpServletRequest; - public interface IFhirResourceDaoComposition extends IFhirResourceDao { IBundleProvider getDocumentForComposition( diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoEncounter.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoEncounter.java index f97b47dacad..06b3d846a2c 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoEncounter.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoEncounter.java @@ -22,12 +22,11 @@ package ca.uhn.fhir.jpa.api.dao; import ca.uhn.fhir.rest.api.SortSpec; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.param.DateRangeParam; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.instance.model.api.IPrimitiveType; -import javax.servlet.http.HttpServletRequest; - public interface IFhirResourceDaoEncounter extends IFhirResourceDao { IBundleProvider encounterInstanceEverything( diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoObservation.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoObservation.java index 82fbbf9135d..5c7049c59cd 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoObservation.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoObservation.java @@ -22,10 +22,9 @@ package ca.uhn.fhir.jpa.api.dao; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.api.server.RequestDetails; +import jakarta.servlet.http.HttpServletResponse; import org.hl7.fhir.instance.model.api.IBaseResource; -import javax.servlet.http.HttpServletResponse; - public interface IFhirResourceDaoObservation extends IFhirResourceDao { /** diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoPatient.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoPatient.java index 1a14ce9ad5a..c4021290fee 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoPatient.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/api/dao/IFhirResourceDaoPatient.java @@ -22,11 +22,10 @@ package ca.uhn.fhir.jpa.api.dao; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.param.TokenOrListParam; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; -import javax.servlet.http.HttpServletRequest; - public interface IFhirResourceDaoPatient extends IFhirResourceDao { IBundleProvider patientInstanceEverything( diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/binary/provider/BinaryAccessProvider.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/binary/provider/BinaryAccessProvider.java index 52cce62c41a..6c776110764 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/binary/provider/BinaryAccessProvider.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/binary/provider/BinaryAccessProvider.java @@ -42,6 +42,8 @@ import ca.uhn.fhir.util.BinaryUtil; import ca.uhn.fhir.util.DateUtils; import ca.uhn.fhir.util.HapiExtensions; import com.google.common.annotations.VisibleForTesting; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.hl7.fhir.instance.model.api.IBase; @@ -60,8 +62,6 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Optional; import javax.annotation.Nonnull; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import static ca.uhn.fhir.util.UrlUtil.sanitizeUrlPart; import static org.apache.commons.lang3.StringUtils.isBlank; diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/ISearchBuilder.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/ISearchBuilder.java index a44f6cc5e19..51ac6b736b6 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/ISearchBuilder.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/ISearchBuilder.java @@ -28,13 +28,13 @@ import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.api.server.storage.IResourcePersistentId; import ca.uhn.fhir.rest.param.DateRangeParam; +import jakarta.persistence.EntityManager; import org.hl7.fhir.instance.model.api.IBaseResource; import java.util.Collection; import java.util.List; import java.util.Set; import javax.annotation.Nonnull; -import javax.persistence.EntityManager; public interface ISearchBuilder> { String SEARCH_BUILDER_BEAN_NAME = "SearchBuilder"; diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/expunge/PartitionAwareSupplier.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/expunge/PartitionAwareSupplier.java index 0be025f0355..7d627254c08 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/expunge/PartitionAwareSupplier.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/expunge/PartitionAwareSupplier.java @@ -23,7 +23,7 @@ import ca.uhn.fhir.jpa.dao.tx.HapiTransactionService; import ca.uhn.fhir.rest.api.server.RequestDetails; import java.util.function.Supplier; -import javax.validation.constraints.NotNull; +import javax.annotation.Nonnull; /** * Utility class wrapping a supplier in a transaction with the purpose of performing the supply operation with a @@ -33,13 +33,13 @@ public class PartitionAwareSupplier { private final HapiTransactionService myTransactionService; private final RequestDetails myRequestDetails; - @NotNull + @Nonnull public PartitionAwareSupplier(HapiTransactionService theTxService, RequestDetails theRequestDetails) { myTransactionService = theTxService; myRequestDetails = theRequestDetails; } - @NotNull + @Nonnull public T supplyInPartitionedContext(Supplier theResourcePersistentIdSupplier) { return myTransactionService.withRequest(myRequestDetails).execute(tx -> theResourcePersistentIdSupplier.get()); } diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/tx/HapiTransactionService.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/tx/HapiTransactionService.java index 348dce762be..ed9a68289d8 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/tx/HapiTransactionService.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/dao/tx/HapiTransactionService.java @@ -73,6 +73,7 @@ public class HapiTransactionService implements IHapiTransactionService { HapiTransactionService.class.getName() + "_EXISTING_SEARCH_PARAMS"; private static final Logger ourLog = LoggerFactory.getLogger(HapiTransactionService.class); private static final ThreadLocal ourRequestPartitionThreadLocal = new ThreadLocal<>(); + private static final ThreadLocal ourExistingTransaction = new ThreadLocal<>(); @Autowired protected IInterceptorBroadcaster myInterceptorBroadcaster; @@ -220,6 +221,11 @@ public class HapiTransactionService implements IHapiTransactionService { myTransactionManager = theTransactionManager; } + @VisibleForTesting + public void setPartitionSettingsForUnitTest(PartitionSettings thePartitionSettings) { + myPartitionSettings = thePartitionSettings; + } + @Nullable protected T doExecute(ExecutionBuilder theExecutionBuilder, TransactionCallback theCallback) { final RequestPartitionId requestPartitionId; @@ -237,8 +243,9 @@ public class HapiTransactionService implements IHapiTransactionService { ourRequestPartitionThreadLocal.set(requestPartitionId); } - if (Objects.equals(previousRequestPartitionId, requestPartitionId)) { - if (canReuseExistingTransaction(theExecutionBuilder)) { + if (!myPartitionSettings.isPartitioningEnabled() + || Objects.equals(previousRequestPartitionId, requestPartitionId)) { + if (ourExistingTransaction.get() == this && canReuseExistingTransaction(theExecutionBuilder)) { /* * If we're already in an active transaction, and it's for the right partition, * and it's not a read-only transaction, we don't need to open a new transaction @@ -246,12 +253,22 @@ public class HapiTransactionService implements IHapiTransactionService { */ return executeInExistingTransaction(theCallback); } - } else if (myTransactionPropagationWhenChangingPartitions == Propagation.REQUIRES_NEW) { - return executeInNewTransactionForPartitionChange( - theExecutionBuilder, theCallback, requestPartitionId, previousRequestPartitionId); } - return doExecuteInTransaction(theExecutionBuilder, theCallback, requestPartitionId, previousRequestPartitionId); + HapiTransactionService previousExistingTransaction = ourExistingTransaction.get(); + try { + ourExistingTransaction.set(this); + + if (myTransactionPropagationWhenChangingPartitions == Propagation.REQUIRES_NEW) { + return executeInNewTransactionForPartitionChange( + theExecutionBuilder, theCallback, requestPartitionId, previousRequestPartitionId); + } else { + return doExecuteInTransaction( + theExecutionBuilder, theCallback, requestPartitionId, previousRequestPartitionId); + } + } finally { + ourExistingTransaction.set(previousExistingTransaction); + } } @Nullable diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/model/search/SearchBuilderLoadIncludesParameters.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/model/search/SearchBuilderLoadIncludesParameters.java index f199bbfe9be..558c7a4648d 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/model/search/SearchBuilderLoadIncludesParameters.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/model/search/SearchBuilderLoadIncludesParameters.java @@ -24,11 +24,11 @@ import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.api.server.storage.IResourcePersistentId; import ca.uhn.fhir.rest.param.DateRangeParam; +import jakarta.persistence.EntityManager; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import javax.persistence.EntityManager; public class SearchBuilderLoadIncludesParameters { diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaProvider.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaProvider.java index 7a017937c4e..03819a3dd79 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaProvider.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaProvider.java @@ -29,6 +29,7 @@ import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.ParametersUtil; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.instance.model.api.IBaseParameters; import org.hl7.fhir.instance.model.api.IPrimitiveType; @@ -39,7 +40,6 @@ import java.util.Date; import java.util.Enumeration; import java.util.Set; import java.util.TreeSet; -import javax.servlet.http.HttpServletRequest; public abstract class BaseJpaProvider { public static final String REMOTE_ADDR = "req.remoteAddr"; diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java index 8c2a8b35ff3..11b3dee3043 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java @@ -54,15 +54,14 @@ import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.provider.ProviderConstants; import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.util.ParametersUtil; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.instance.model.api.IBaseMetaType; import org.hl7.fhir.instance.model.api.IBaseParameters; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.instance.model.api.IPrimitiveType; -import org.springframework.beans.factory.annotation.Required; import java.util.Date; -import javax.servlet.http.HttpServletRequest; import static ca.uhn.fhir.jpa.model.util.JpaConstants.OPERATION_META_ADD; import static ca.uhn.fhir.jpa.model.util.JpaConstants.OPERATION_META_DELETE; @@ -107,7 +106,6 @@ public abstract class BaseJpaResourceProvider extends B return myDao; } - @Required public void setDao(IFhirResourceDao theDao) { myDao = theDao; } diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseStorageSystemProvider.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseStorageSystemProvider.java index 3ad030ff555..2a984c2f90d 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseStorageSystemProvider.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/provider/BaseStorageSystemProvider.java @@ -29,7 +29,6 @@ import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.provider.ProviderConstants; import org.hl7.fhir.instance.model.api.IBaseParameters; import org.hl7.fhir.instance.model.api.IPrimitiveType; -import org.springframework.beans.factory.annotation.Required; public abstract class BaseStorageSystemProvider extends BaseJpaProvider { protected IFhirSystemDao myDao; @@ -74,7 +73,6 @@ public abstract class BaseStorageSystemProvider extends BaseJpaProvider { return myDao; } - @Required public void setDao(IFhirSystemDao theDao) { myDao = theDao; } diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/subscription/channel/impl/LinkedBlockingChannelFactory.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/subscription/channel/impl/LinkedBlockingChannelFactory.java index 13bd3aede1f..f69a42a0df8 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/subscription/channel/impl/LinkedBlockingChannelFactory.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/subscription/channel/impl/LinkedBlockingChannelFactory.java @@ -28,13 +28,13 @@ import ca.uhn.fhir.jpa.subscription.channel.api.IChannelSettings; import ca.uhn.fhir.jpa.subscription.channel.subscription.IChannelNamer; import ca.uhn.fhir.subscription.SubscriptionConstants; import ca.uhn.fhir.util.ThreadPoolUtil; +import jakarta.annotation.PreDestroy; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; -import javax.annotation.PreDestroy; public class LinkedBlockingChannelFactory implements IChannelFactory { diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/util/CircularQueueCaptureQueriesListener.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/util/CircularQueueCaptureQueriesListener.java index ed355cdc3fa..beb038ab49c 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/util/CircularQueueCaptureQueriesListener.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/util/CircularQueueCaptureQueriesListener.java @@ -32,6 +32,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; +import java.util.Locale; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; @@ -50,12 +51,17 @@ import javax.annotation.Nonnull; */ public class CircularQueueCaptureQueriesListener extends BaseCaptureQueriesListener { + public static final Predicate DEFAULT_SELECT_INCLUSION_CRITERIA = + t -> t.toLowerCase(Locale.US).startsWith("select"); private static final int CAPACITY = 1000; private static final Logger ourLog = LoggerFactory.getLogger(CircularQueueCaptureQueriesListener.class); private Queue myQueries; private AtomicInteger myCommitCounter; private AtomicInteger myRollbackCounter; + @Nonnull + private Predicate mySelectQueryInclusionCriteria = DEFAULT_SELECT_INCLUSION_CRITERIA; + /** * Constructor */ @@ -63,6 +69,16 @@ public class CircularQueueCaptureQueriesListener extends BaseCaptureQueriesListe startCollecting(); } + /** + * Sets an alternate inclusion criteria for select queries. This can be used to add + * additional criteria beyond the default value of {@link #DEFAULT_SELECT_INCLUSION_CRITERIA}. + */ + public CircularQueueCaptureQueriesListener setSelectQueryInclusionCriteria( + @Nonnull Predicate theSelectQueryInclusionCriteria) { + mySelectQueryInclusionCriteria = theSelectQueryInclusionCriteria; + return this; + } + @Override protected Queue provideQueryList() { return myQueries; @@ -133,6 +149,22 @@ public class CircularQueueCaptureQueriesListener extends BaseCaptureQueriesListe return getQueriesStartingWith(theStart, null); } + private List getQueriesMatching(Predicate thePredicate, String theThreadName) { + return getCapturedQueries().stream() + .filter(t -> theThreadName == null || t.getThreadName().equals(theThreadName)) + .filter(t -> thePredicate.test(t.getSql(false, false))) + .collect(Collectors.toList()); + } + + private List getQueriesMatching(Predicate thePredicate) { + return getQueriesMatching(thePredicate, null); + } + + private List getQueriesForCurrentThreadMatching(Predicate thePredicate) { + String threadName = Thread.currentThread().getName(); + return getQueriesMatching(thePredicate, threadName); + } + public int getCommitCount() { return myCommitCounter.get(); } @@ -145,7 +177,7 @@ public class CircularQueueCaptureQueriesListener extends BaseCaptureQueriesListe * Returns all SELECT queries executed on the current thread - Index 0 is oldest */ public List getSelectQueries() { - return getQueriesStartingWith("select"); + return getQueriesMatching(mySelectQueryInclusionCriteria); } /** @@ -173,7 +205,7 @@ public class CircularQueueCaptureQueriesListener extends BaseCaptureQueriesListe * Returns all SELECT queries executed on the current thread - Index 0 is oldest */ public List getSelectQueriesForCurrentThread() { - return getQueriesForCurrentThreadStartingWith("select"); + return getQueriesForCurrentThreadMatching(mySelectQueryInclusionCriteria); } /** diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/util/SqlQuery.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/util/SqlQuery.java index 1717acdcbf7..efb4161dcca 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/util/SqlQuery.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/util/SqlQuery.java @@ -23,6 +23,8 @@ import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.util.UrlUtil; import org.apache.commons.lang3.Validate; import org.hibernate.engine.jdbc.internal.BasicFormatterImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; @@ -31,6 +33,7 @@ import java.util.List; import static org.apache.commons.lang3.StringUtils.trim; public class SqlQuery { + private static final Logger ourLog = LoggerFactory.getLogger(SqlQuery.class); private final String myThreadName = Thread.currentThread().getName(); private final String mySql; private final List myParams; diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/AsyncMemoryQueueBackedFhirClientBalpSink.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/AsyncMemoryQueueBackedFhirClientBalpSink.java index 4a39746796c..d95da46a49e 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/AsyncMemoryQueueBackedFhirClientBalpSink.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/AsyncMemoryQueueBackedFhirClientBalpSink.java @@ -24,6 +24,7 @@ import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.util.BundleBuilder; import ca.uhn.fhir.util.ThreadPoolUtil; +import jakarta.annotation.PreDestroy; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.instance.model.api.IBaseResource; import org.slf4j.Logger; @@ -35,7 +36,6 @@ import java.util.List; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import javax.annotation.PreDestroy; /** * This implementation of the {@link IBalpAuditEventSink} transmits audit events to diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/BalpAuditCaptureInterceptor.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/BalpAuditCaptureInterceptor.java index d7ae427a476..59855cc987a 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/BalpAuditCaptureInterceptor.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/BalpAuditCaptureInterceptor.java @@ -36,9 +36,6 @@ import org.hl7.fhir.r4.model.AuditEvent; import java.nio.charset.StandardCharsets; import java.util.*; import javax.annotation.Nonnull; -import javax.servlet.http.HttpServletRequest; - -import static org.apache.commons.lang3.StringUtils.isNotBlank; /** * The IHE Basic Audit Logging Pattern (BALP) interceptor can be used to autopmatically generate @@ -319,7 +316,7 @@ public class BalpAuditCaptureInterceptor { auditEvent.setOutcome(AuditEvent.AuditEventOutcome._0); auditEvent.setRecorded(new Date()); - auditEvent.getSource().getObserver().setDisplay(theRequestDetails.getServerBaseForRequest()); + auditEvent.getSource().getObserver().setDisplay(theRequestDetails.getFhirServerBase()); AuditEvent.AuditEventAgentComponent clientAgent = auditEvent.addAgent(); clientAgent.setWho(myContextServices.getAgentClientWho(theRequestDetails)); @@ -333,8 +330,8 @@ public class BalpAuditCaptureInterceptor { AuditEvent.AuditEventAgentComponent serverAgent = auditEvent.addAgent(); serverAgent.getType().addCoding(theProfile.getAgentServerTypeCoding()); - serverAgent.getWho().setDisplay(theRequestDetails.getServerBaseForRequest()); - serverAgent.getNetwork().setAddress(theRequestDetails.getServerBaseForRequest()); + serverAgent.getWho().setDisplay(theRequestDetails.getFhirServerBase()); + serverAgent.getNetwork().setAddress(theRequestDetails.getFhirServerBase()); serverAgent.setRequestor(false); AuditEvent.AuditEventAgentComponent userAgent = auditEvent.addAgent(); @@ -374,19 +371,14 @@ public class BalpAuditCaptureInterceptor { // Description StringBuilder description = new StringBuilder(); - HttpServletRequest servletRequest = theRequestDetails.getServletRequest(); - description.append(servletRequest.getMethod()); + description.append(theRequestDetails.getRequestType().name()); description.append(" "); - description.append(servletRequest.getRequestURI()); - if (isNotBlank(servletRequest.getQueryString())) { - description.append("?"); - description.append(servletRequest.getQueryString()); - } + description.append(theRequestDetails.getCompleteUrl()); queryEntity.setDescription(description.toString()); // Query String StringBuilder queryString = new StringBuilder(); - queryString.append(theRequestDetails.getServerBaseForRequest()); + queryString.append(theRequestDetails.getFhirServerBase()); queryString.append("/"); queryString.append(theRequestDetails.getRequestPath()); boolean first = true; diff --git a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/IBalpAuditContextServices.java b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/IBalpAuditContextServices.java index 412991d6d08..89003183c57 100644 --- a/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/IBalpAuditContextServices.java +++ b/hapi-fhir-storage/src/main/java/ca/uhn/fhir/storage/interceptor/balp/IBalpAuditContextServices.java @@ -95,7 +95,7 @@ public interface IBalpAuditContextServices { @Nonnull RequestDetails theRequestDetails, @Nonnull IBaseResource theResource, @Nonnull IIdType theResourceId) { - String serverBaseUrl = theRequestDetails.getServerBaseForRequest(); + String serverBaseUrl = theRequestDetails.getFhirServerBase(); String resourceName = theResourceId.getResourceType(); return theResourceId.withServerBase(serverBaseUrl, resourceName).getValue(); } diff --git a/hapi-fhir-storage/src/test/java/ca/uhn/fhir/storage/interceptor/balp/BalpAuditCaptureInterceptorTest.java b/hapi-fhir-storage/src/test/java/ca/uhn/fhir/storage/interceptor/balp/BalpAuditCaptureInterceptorTest.java index 141d3f72b89..3e324882f51 100644 --- a/hapi-fhir-storage/src/test/java/ca/uhn/fhir/storage/interceptor/balp/BalpAuditCaptureInterceptorTest.java +++ b/hapi-fhir-storage/src/test/java/ca/uhn/fhir/storage/interceptor/balp/BalpAuditCaptureInterceptorTest.java @@ -34,9 +34,14 @@ import org.mockito.junit.jupiter.MockitoExtension; import javax.annotation.Nonnull; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.stream.Collectors; import static ca.uhn.fhir.storage.interceptor.balp.BalpConstants.*; @@ -547,7 +552,7 @@ public class BalpAuditCaptureInterceptorTest implements ITestDataBuilder { assertEquals(AuditEvent.AuditEventOutcome._0, auditEvent.getOutcome()); assertHasPatientEntities(auditEvent, "Patient/P1"); assertQuery(auditEvent, ourServer.getBaseUrl() + "/Observation?subject=Patient%2FP1"); - assertQueryDescription(auditEvent, "GET /Observation?subject=Patient%2FP1"); + assertQueryDescription(auditEvent, "GET " + ourServer.getBaseUrl() + "/Observation?subject=Patient%2FP1"); } @Test @@ -584,11 +589,11 @@ public class BalpAuditCaptureInterceptorTest implements ITestDataBuilder { assertEquals(AuditEvent.AuditEventOutcome._0, auditEvent.getOutcome()); assertHasPatientEntities(auditEvent); assertQuery(auditEvent, ourServer.getBaseUrl() + "/CodeSystem"); - assertQueryDescription(auditEvent, "GET /CodeSystem"); + assertQueryDescription(auditEvent, "GET " + ourServer.getBaseUrl() + "/CodeSystem"); } @Test - public void testSearch_ResponseIncludesSinglePatientCompartment_LoadPageTwo() { + public void testSearch_ResponseIncludesSinglePatientCompartment_LoadPageTwo() throws ExecutionException, InterruptedException { // Setup create10Observations("Patient/P1"); @@ -624,7 +629,7 @@ public class BalpAuditCaptureInterceptorTest implements ITestDataBuilder { assertEquals(AuditEvent.AuditEventOutcome._0, auditEvent.getOutcome()); assertHasPatientEntities(auditEvent, "Patient/P1"); assertQuery(auditEvent, ourServer.getBaseUrl() + "/Observation?_count=5&subject=Patient%2FP1"); - assertQueryDescription(auditEvent, "GET /Observation?subject=Patient%2FP1&_count=5"); + assertQueryDescription(auditEvent, "GET " + ourServer.getBaseUrl() + "/Observation?subject=Patient%2FP1&_count=5"); auditEvent = myAuditEventCaptor.getAllValues().get(1); ourLog.info("Audit Event: {}", ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(auditEvent)); @@ -669,7 +674,7 @@ public class BalpAuditCaptureInterceptorTest implements ITestDataBuilder { assertEquals(AuditEvent.AuditEventOutcome._0, auditEvent.getOutcome()); assertHasPatientEntities(auditEvent, "Patient/P1"); assertQuery(auditEvent, ourServer.getBaseUrl() + "/Observation/_search?subject=Patient%2FP1"); - assertQueryDescription(auditEvent, "POST /Observation/_search"); + assertQueryDescription(auditEvent, "POST " + ourServer.getBaseUrl() + "/Observation/_search"); } @Test @@ -704,7 +709,7 @@ public class BalpAuditCaptureInterceptorTest implements ITestDataBuilder { assertEquals(AuditEvent.AuditEventOutcome._0, auditEvent.getOutcome()); assertHasPatientEntities(auditEvent, "Patient/P1"); assertQuery(auditEvent, ourServer.getBaseUrl() + "/Observation/_search?subject=Patient%2FP1"); - assertQueryDescription(auditEvent, "GET /Observation/_search?subject=Patient%2FP1"); + assertQueryDescription(auditEvent, "GET " + ourServer.getBaseUrl() + "/Observation/_search?subject=Patient%2FP1"); } @Test diff --git a/hapi-fhir-structures-dstu2.1/pom.xml b/hapi-fhir-structures-dstu2.1/pom.xml index 58a42fc146f..32c2507e9ba 100644 --- a/hapi-fhir-structures-dstu2.1/pom.xml +++ b/hapi-fhir-structures-dstu2.1/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -38,6 +38,13 @@ + + jakarta.servlet + jakarta.servlet-api + provided + true + + @@ -65,17 +72,6 @@ true
    - - - javax.servlet - servlet-api - 2.5 - provided - - commons-codec commons-codec @@ -97,36 +93,6 @@ xmlunit-core test - - org.eclipse.jetty - jetty-servlets - test - - - org.eclipse.jetty - jetty-servlet - test - - - org.eclipse.jetty - jetty-server - test - - - org.eclipse.jetty - jetty-util - test - - - org.eclipse.jetty - jetty-webapp - test - - - org.eclipse.jetty - jetty-http - test - ch.qos.logback logback-classic @@ -210,23 +176,18 @@ - com.helger - ph-schematron + com.helger.schematron + ph-schematron-api test - com.helger - ph-commons + com.helger.schematron + ph-schematron-xslt test - javax.activation - javax.activation-api - test - - - javax.xml.bind - jaxb-api + jakarta.activation + jakarta.activation-api test @@ -284,7 +245,7 @@ --> - javax.servlet*;resolution:=optional, + jakarta.servlet*;resolution:=optional, * diff --git a/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/hapi/rest/server/ServerConformanceProvider.java b/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/hapi/rest/server/ServerConformanceProvider.java index 59f3614d32f..f58805ed7c6 100644 --- a/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/hapi/rest/server/ServerConformanceProvider.java +++ b/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/hapi/rest/server/ServerConformanceProvider.java @@ -36,22 +36,22 @@ import ca.uhn.fhir.rest.server.method.SearchParameter; import ca.uhn.fhir.rest.server.util.BaseServerCapabilityStatementProvider; import ca.uhn.fhir.rest.server.*; import ca.uhn.fhir.rest.server.method.*; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.dstu2016may.model.Enumerations.ConformanceResourceStatus; -import org.hl7.fhir.dstu2016may.model.Enumerations.ResourceType; import org.hl7.fhir.dstu2016may.model.OperationDefinition.OperationDefinitionParameterComponent; +import org.hl7.fhir.dstu2016may.model.OperationDefinition.OperationKind; import org.hl7.fhir.dstu2016may.model.OperationDefinition.OperationParameterUse; import org.hl7.fhir.dstu2016may.model.*; import org.hl7.fhir.dstu2016may.model.Conformance.*; -import org.hl7.fhir.dstu2016may.model.OperationDefinition.OperationKind; +import org.hl7.fhir.dstu2016may.model.Enumerations.ResourceType; import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IPrimitiveType; import java.util.Map.Entry; import java.util.*; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CreateBinaryDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CreateBinaryDstu2_1Test.java deleted file mode 100644 index d8b81a61e16..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CreateBinaryDstu2_1Test.java +++ /dev/null @@ -1,172 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.Create; -import ca.uhn.fhir.rest.annotation.ResourceParam; -import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.Binary; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -public class CreateBinaryDstu2_1Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static Binary ourLastBinary; - private static byte[] ourLastBinaryBytes; - private static String ourLastBinaryString; - private static int ourPort; - private static Server ourServer; - - @BeforeEach - public void before() { - ourLastBinary = null; - ourLastBinaryBytes = null; - ourLastBinaryString = null; - } - - @Test - public void testRawBytesBinaryContentType() throws Exception { - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); - post.setEntity(new ByteArrayEntity(new byte[] { 0, 1, 2, 3, 4 })); - post.addHeader("Content-Type", "application/foo"); - CloseableHttpResponse status = ourClient.execute(post); - try { - assertEquals("application/foo", ourLastBinary.getContentType()); - assertArrayEquals(new byte[] { 0, 1, 2, 3, 4 }, ourLastBinary.getContent()); - assertArrayEquals(new byte[] { 0, 1, 2, 3, 4 }, ourLastBinaryBytes); - } finally { - IOUtils.closeQuietly(status); - } - } - - /** - * Technically the client shouldn't be doing it this way, but we'll be accepting - */ - @Test - public void testRawBytesFhirContentType() throws Exception { - - Binary b = new Binary(); - b.setContentType("application/foo"); - b.setContent(new byte[] { 0, 1, 2, 3, 4 }); - String encoded = ourCtx.newJsonParser().encodeResourceToString(b); - - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); - post.setEntity(new StringEntity(encoded)); - post.addHeader("Content-Type", Constants.CT_FHIR_JSON); - CloseableHttpResponse status = ourClient.execute(post); - try { - assertEquals("application/foo", ourLastBinary.getContentType()); - assertArrayEquals(new byte[] { 0, 1, 2, 3, 4 }, ourLastBinary.getContent()); - } finally { - IOUtils.closeQuietly(status); - } - } - - @Test - public void testRawBytesFhirContentTypeContainingFhir() throws Exception { - - Patient p = new Patient(); - p.getText().setDivAsString("A PATIENT"); - - Binary b = new Binary(); - b.setContentType("application/xml+fhir"); - b.setContent(ourCtx.newXmlParser().encodeResourceToString(p).getBytes("UTF-8")); - String encoded = ourCtx.newJsonParser().encodeResourceToString(b); - - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); - post.setEntity(new StringEntity(encoded)); - post.addHeader("Content-Type", Constants.CT_FHIR_JSON); - CloseableHttpResponse status = ourClient.execute(post); - try { - assertEquals("application/xml+fhir", ourLastBinary.getContentType()); - assertArrayEquals(b.getContent(), ourLastBinary.getContent()); - assertEquals(encoded, ourLastBinaryString); - assertArrayEquals(encoded.getBytes("UTF-8"), ourLastBinaryBytes); - } finally { - IOUtils.closeQuietly(status); - } - } - - @Test - public void testRawBytesNoContentType() throws Exception { - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); - post.setEntity(new ByteArrayEntity(new byte[] { 0, 1, 2, 3, 4 })); - CloseableHttpResponse status = ourClient.execute(post); - try { - assertNull(ourLastBinary.getContentType()); - assertArrayEquals(new byte[] { 0, 1, 2, 3, 4 }, ourLastBinary.getContent()); - } finally { - IOUtils.closeQuietly(status); - } - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - BinaryProvider binaryProvider = new BinaryProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(binaryProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - } - - public static class BinaryProvider implements IResourceProvider { - - @Create() - public MethodOutcome createBinary(@ResourceParam Binary theBinary, @ResourceParam String theBinaryString, @ResourceParam byte[] theBinaryBytes) { - ourLastBinary = theBinary; - ourLastBinaryString = theBinaryString; - ourLastBinaryBytes = theBinaryBytes; - return new MethodOutcome(new IdType("Binary/001/_history/002")); - } - - @Override - public Class getResourceType() { - return Binary.class; - } - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CreateDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CreateDstu2_1Test.java deleted file mode 100644 index 8b6f5cafa8f..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CreateDstu2_1Test.java +++ /dev/null @@ -1,283 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.i18n.Msg; -import ca.uhn.fhir.rest.annotation.Create; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.Read; -import ca.uhn.fhir.rest.annotation.ResourceParam; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.rest.client.MyPatientWithExtensions; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -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.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.DateType; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.OperationOutcome; -import org.hl7.fhir.dstu2016may.model.OperationOutcome.OperationOutcomeIssueComponent; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseOperationOutcome; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.stringContainsInOrder; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class CreateDstu2_1Test { - private static CloseableHttpClient ourClient; - - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CreateDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - public static IBaseOperationOutcome ourReturnOo; - - @BeforeEach - public void before() { - ourReturnOo = null; - } - - /** - * #472 - */ - @Test - public void testCreateReturnsLocationHeader() throws Exception { - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); - httpPost.setEntity(new StringEntity("{\"resourceType\":\"Patient\", \"status\":\"active\"}", ContentType.parse(Constants.CT_FHIR_JSON+"; charset=utf-8"))); - HttpResponse status = ourClient.execute(httpPost); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(201, status.getStatusLine().getStatusCode()); - - assertEquals(1, status.getHeaders("Location").length); - assertEquals(1, status.getHeaders("Content-Location").length); - assertEquals("http://localhost:" + ourPort + "/Patient/1", status.getFirstHeader("Location").getValue()); - - } - - @Test - public void testCreateReturnsRepresentation() throws Exception { - ourReturnOo = new OperationOutcome().addIssue(new OperationOutcomeIssueComponent().setDiagnostics("DIAG")); - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); - httpPost.setEntity(new StringEntity("{\"resourceType\":\"Patient\", \"gender\":\"male\"}", ContentType.parse(Constants.CT_FHIR_JSON+"; charset=utf-8"))); - HttpResponse status = ourClient.execute(httpPost); - String expectedContent = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"gender\":\"male\"}"; - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals(expectedContent, responseContent); - - } - - /** - * #342 - */ - @Test - public void testCreateWithInvalidContent() throws Exception { - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); - httpPost.setEntity(new StringEntity("FOO", ContentType.parse("application/xml+fhir; charset=utf-8"))); - HttpResponse status = ourClient.execute(httpPost); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(400, status.getStatusLine().getStatusCode()); - - assertThat(responseContent, containsString("", - "", - "", - "", - "", - "", - "", - "", - "")); - //@formatter:on - - assertThat(responseContent, not(containsString("http://hl7.org/fhir/"))); - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class PatientProvider implements IResourceProvider { - - @Create() - public MethodOutcome create(@ResourceParam Patient theIdParam) { - theIdParam.setId("1"); - return new MethodOutcome(new IdType("Patient", "1"), true).setOperationOutcome(ourReturnOo) - .setResource(theIdParam); - } - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Read() - public MyPatientWithExtensions read(@IdParam IdType theIdParam) { - MyPatientWithExtensions p0 = new MyPatientWithExtensions(); - p0.setId(theIdParam); - p0.setDateExt(new DateType("2011-01-01")); - return p0; - } - - @Search - public List search() { - ArrayList retVal = new ArrayList(); - - MyPatientWithExtensions p0 = new MyPatientWithExtensions(); - p0.setId(new IdType("Patient/0")); - p0.setDateExt(new DateType("2011-01-01")); - retVal.add(p0); - - Patient p1 = new Patient(); - p1.setId(new IdType("Patient/1")); - p1.addName().addFamily("The Family"); - retVal.add(p1); - - return retVal; - } - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CustomTypeServerDstu2_1.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CustomTypeServerDstu2_1.java index bc39778fe31..6ba6d4cf304 100644 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CustomTypeServerDstu2_1.java +++ b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/CustomTypeServerDstu2_1.java @@ -1,6 +1,7 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; @@ -11,46 +12,43 @@ import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; 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.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu2016may.model.IdType; import org.hl7.fhir.dstu2016may.model.OperationOutcome; import org.hl7.fhir.dstu2016may.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; public class CustomTypeServerDstu2_1 { - private static CloseableHttpClient ourClient; - - private static FhirContext ourCtx = FhirContext.forDstu2_1(); + private static final FhirContext ourCtx = FhirContext.forDstu2_1(); private static String ourLastConditionalUrl; private static IdType ourLastId; private static IdType ourLastIdParam; private static boolean ourLastRequestWasSearch; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CustomTypeServerDstu2_1.class); - private static int ourPort; - private static Server ourServer; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastId = null; @@ -67,7 +65,7 @@ public class CustomTypeServerDstu2_1 { patient.setId("2"); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); // httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?identifier=system%7C001"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -87,7 +85,7 @@ public class CustomTypeServerDstu2_1 { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/2"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/2"); // httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?identifier=system%7C001"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -100,7 +98,7 @@ public class CustomTypeServerDstu2_1 { assertEquals(400, status.getStatusLine().getStatusCode()); OperationOutcome oo = ourCtx.newXmlParser().parseResource(OperationOutcome.class, responseContent); - assertEquals("Can not create resource with ID \"2\", ID must not be supplied on a create (POST) operation (use an HTTP PUT / update operation if you wish to supply an ID)", oo.getIssue().get(0).getDiagnostics()); + assertEquals(Msg.code(365) + "Can not create resource with ID \"2\", ID must not be supplied on a create (POST) operation (use an HTTP PUT / update operation if you wish to supply an ID)", oo.getIssue().get(0).getDiagnostics()); } @Test @@ -109,7 +107,7 @@ public class CustomTypeServerDstu2_1 { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/2"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/2"); httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?identifier=system%7C001"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -122,38 +120,15 @@ public class CustomTypeServerDstu2_1 { assertEquals(400, status.getStatusLine().getStatusCode()); OperationOutcome oo = ourCtx.newXmlParser().parseResource(OperationOutcome.class, responseContent); - assertEquals("Can not create resource with ID \"2\", ID must not be supplied on a create (POST) operation (use an HTTP PUT / update operation if you wish to supply an ID)", oo.getIssue().get(0).getDiagnostics()); + assertEquals(Msg.code(365) + "Can not create resource with ID \"2\", ID must not be supplied on a create (POST) operation (use an HTTP PUT / update operation if you wish to supply an ID)", oo.getIssue().get(0).getDiagnostics()); } @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Create() diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalDstu2_1Test.java deleted file mode 100644 index ad7fe63c5a3..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalDstu2_1Test.java +++ /dev/null @@ -1,132 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; -import ca.uhn.fhir.rest.annotation.Delete; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.rest.client.api.IGenericClient; -import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class DeleteConditionalDstu2_1Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static IGenericClient ourHapiClient; - private static String ourLastConditionalUrl; - private static IdType ourLastIdParam; - private static boolean ourLastRequestWasDelete; - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(DeleteConditionalDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - - - @BeforeEach - public void before() { - ourLastConditionalUrl = null; - ourLastIdParam = null; - ourLastRequestWasDelete = false; - } - - - - @Test - public void testSearchStillWorks() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier().setValue("002"); - -// HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true"); -// -// HttpResponse status = ourClient.execute(httpGet); -// -// String responseContent = IOUtils.toString(status.getEntity().getContent()); -// IOUtils.closeQuietly(status.getEntity().getContent()); -// -// ourLog.info("Response was:\n{}", responseContent); - - //@formatter:off - ourHapiClient - .delete() - .resourceConditionalByType(Patient.class) - .where(Patient.IDENTIFIER.exactly().systemAndIdentifier("SOMESYS","SOMEID")) - .execute(); - //@formatter:on - - assertTrue(ourLastRequestWasDelete); - assertEquals(null, ourLastIdParam); - assertEquals("Patient?identifier=SOMESYS%7CSOMEID", ourLastConditionalUrl); - - } - - - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - ourCtx.getRestfulClientFactory().setSocketTimeout(500 * 1000); - ourHapiClient = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/"); - ourHapiClient.registerInterceptor(new LoggingInterceptor()); - } - - public static class PatientProvider implements IResourceProvider { - - @Delete() - public MethodOutcome deletePatient(@IdParam IdType theIdParam, @ConditionalUrlParam String theConditional) { - ourLastRequestWasDelete = true; - ourLastConditionalUrl = theConditional; - ourLastIdParam = theIdParam; - return new MethodOutcome(new IdType("Patient/001/_history/002")); - } - - @Override - public Class getResourceType() { - return Patient.class; - } - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/FormatParameterDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/FormatParameterDstu2_1Test.java deleted file mode 100644 index e5c7478ec9d..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/FormatParameterDstu2_1Test.java +++ /dev/null @@ -1,255 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.annotation.ResourceDef; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.Read; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class FormatParameterDstu2_1Test { - - private static final String VALUE_XML = ""; - private static final String VALUE_JSON = "{\"resourceType\":\"Patient\",\"id\":\"p1ReadId\",\"meta\":{\"profile\":[\"http://foo_profile\"]},\"identifier\":[{\"value\":\"p1ReadValue\"}]}"; - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FormatParameterDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; - - /** - * See #346 - */ - @Test - public void testFormatXml() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=xml"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals(VALUE_XML, responseContent); - } finally { - IOUtils.closeQuietly(status); - } - } - - /** - * See #346 - */ - @Test - public void testFormatApplicationXml() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/xml"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals(VALUE_XML, responseContent); - } finally { - IOUtils.closeQuietly(status); - } - } - - /** - * See #346 - */ - @Test - public void testFormatApplicationXmlFhir() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/xml%2Bfhir"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals(VALUE_XML, responseContent); - } finally { - IOUtils.closeQuietly(status); - } - } - - /** - * See #346 - */ - @Test - public void testFormatApplicationXmlFhirUnescaped() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); - - // The plus isn't escaped here, and it should be.. but we'll be lenient - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/xml+fhir"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals(VALUE_XML, responseContent); - } finally { - IOUtils.closeQuietly(status); - } - } - - /** - * See #346 - */ - @Test - public void testFormatJson() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=json"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals(VALUE_JSON, responseContent); - } finally { - IOUtils.closeQuietly(status); - } - } - - /** - * See #346 - */ - @Test - public void testFormatApplicationJson() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/json"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals(VALUE_JSON, responseContent); - } finally { - IOUtils.closeQuietly(status); - } - } - - /** - * See #346 - */ - @Test - public void testFormatApplicationJsonFhir() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/json%2Bfhir"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals(VALUE_JSON, responseContent); - } finally { - IOUtils.closeQuietly(status); - } - } - - /** - * See #346 - */ - @Test - public void testFormatApplicationJsonFhirUnescaped() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - - // The plus isn't escaped here, and it should be.. but we'll be lenient - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/json+fhir"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals(VALUE_JSON, responseContent); - } finally { - IOUtils.closeQuietly(status); - } - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setFhirContext(ourCtx); - ourServlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Read(version = true) - public Patient read(@IdParam IdType theId) { - Patient p1 = new MyPatient(); - p1.setId("p1ReadId"); - p1.addIdentifier().setValue("p1ReadValue"); - return p1; - } - - } - - @ResourceDef(name = "Patient", profile = "http://foo_profile") - public static class MyPatient extends Patient { - - private static final long serialVersionUID = 1L; - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/MetadataConformanceDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/MetadataConformanceDstu2_1Test.java deleted file mode 100644 index b2d8553b8f2..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/MetadataConformanceDstu2_1Test.java +++ /dev/null @@ -1,191 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.OptionalParam; -import ca.uhn.fhir.rest.annotation.ResourceParam; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.annotation.Validate; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.rest.param.StringParam; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import ca.uhn.fhir.util.VersionUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.hapi.rest.server.ServerConformanceProvider; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.stringContainsInOrder; -import static org.junit.jupiter.api.Assertions.assertEquals; - -@SuppressWarnings("deprecation") -public class MetadataConformanceDstu2_1Test { - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(MetadataConformanceDstu2_1Test.class); - - - @Test - public void testSummary() throws Exception { - String output; - - // With - HttpRequestBase httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_summary=true&_pretty=true"); - CloseableHttpResponse status = ourClient.execute(httpPost); - try { - output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - assertEquals(200, status.getStatusLine().getStatusCode()); - ourLog.info(output); - assertThat(output, containsString("", "SUBSETTED", "")); - assertThat(output, not(stringContainsInOrder("searchParam"))); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - // Without - httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_pretty=true"); - status = ourClient.execute(httpPost); - try { - output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - assertEquals(200, status.getStatusLine().getStatusCode()); - ourLog.info(output); - assertThat(output, containsString("", "SUBSETTED", ""))); - assertThat(output, stringContainsInOrder("searchParam")); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - } - - @Test - public void testElements() throws Exception { - String output; - - HttpRequestBase httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_elements=fhirVersion&_pretty=true"); - CloseableHttpResponse status = ourClient.execute(httpPost); - try { - output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - assertEquals(200, status.getStatusLine().getStatusCode()); - ourLog.info(output); - assertThat(output, containsString("", "SUBSETTED", "")); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - } - - @Test - public void testHttpMethods() throws Exception { - String output; - - HttpRequestBase httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata"); - CloseableHttpResponse status = ourClient.execute(httpPost); - try { - output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(output, containsString(" getResourceType() { - return Patient.class; - } - - @Search - public List search(@OptionalParam(name="foo") StringParam theFoo) { - throw new UnsupportedOperationException(); - } - - @Validate() - public MethodOutcome validate(@ResourceParam Patient theResource) { - return new MethodOutcome(); - } - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu2_1Test.java deleted file mode 100644 index 2075b04e46e..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu2_1Test.java +++ /dev/null @@ -1,786 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.Operation; -import ca.uhn.fhir.rest.annotation.OperationParam; -import ca.uhn.fhir.rest.annotation.Read; -import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.rest.api.server.IBundleProvider; -import ca.uhn.fhir.rest.client.api.IGenericClient; -import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -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.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.Bundle; -import org.hl7.fhir.dstu2016may.model.Conformance; -import org.hl7.fhir.dstu2016may.model.Conformance.ConformanceRestOperationComponent; -import org.hl7.fhir.dstu2016may.model.DateTimeType; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.IntegerType; -import org.hl7.fhir.dstu2016may.model.Money; -import org.hl7.fhir.dstu2016may.model.OperationDefinition; -import org.hl7.fhir.dstu2016may.model.OperationDefinition.OperationParameterUse; -import org.hl7.fhir.dstu2016may.model.Parameters; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.dstu2016may.model.StringType; -import org.hl7.fhir.dstu2016may.model.UnsignedIntType; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInRelativeOrder; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -public class OperationServerDstu2_1Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; - - private static IdType ourLastId; - private static String ourLastMethod; - private static StringType ourLastParam1; - private static Patient ourLastParam2; - private static List ourLastParam3; - private static Money ourLastParamMoney1; - private static UnsignedIntType ourLastParamUnsignedInt1; - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationServerDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - private IGenericClient myFhirClient; - - @BeforeEach - public void before() { - ourLastParam1 = null; - ourLastParam2 = null; - ourLastParam3 = null; - ourLastParamUnsignedInt1 = null; - ourLastParamMoney1 = null; - ourLastId = null; - ourLastMethod = ""; - - myFhirClient = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); - } - - - @Test - public void testConformance() { - LoggingInterceptor loggingInterceptor = new LoggingInterceptor(); - loggingInterceptor.setLogResponseBody(true); - myFhirClient.registerInterceptor(loggingInterceptor); - - Conformance p = myFhirClient.fetchConformance().ofType(Conformance.class).prettyPrint().execute(); - ourLog.debug(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p)); - - List ops = p.getRest().get(0).getOperation(); - assertThat(ops.size(), greaterThan(1)); - - List opNames = toOpNames(ops); - assertThat(opNames, containsInRelativeOrder("OP_TYPE")); - -// OperationDefinition def = (OperationDefinition) ops.get(opNames.indexOf("OP_TYPE")).getDefinition().getResource(); - OperationDefinition def = myFhirClient.read().resource(OperationDefinition.class).withId(ops.get(opNames.indexOf("OP_TYPE")).getDefinition().getReferenceElement()).execute(); - assertEquals("OP_TYPE", def.getCode()); - } - - /** - * See #380 - */ - @Test - public void testOperationDefinition() { - OperationDefinition def = myFhirClient.read().resource(OperationDefinition.class).withId("OperationDefinition/Patient-t-OP_TYPE").execute(); - - ourLog.debug(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(def)); - -// @OperationParam(name="PARAM1") StringType theParam1, -// @OperationParam(name="PARAM2") Patient theParam2, -// @OperationParam(name="PARAM3", min=2, max=5) List theParam3, -// @OperationParam(name="PARAM4", min=1) List theParam4, - - assertEquals(4, def.getParameter().size()); - assertEquals("PARAM1", def.getParameter().get(0).getName()); - assertEquals(OperationParameterUse.IN, def.getParameter().get(0).getUse()); - assertEquals(0, def.getParameter().get(0).getMin()); - assertEquals("1", def.getParameter().get(0).getMax()); - - assertEquals("PARAM2", def.getParameter().get(1).getName()); - assertEquals(OperationParameterUse.IN, def.getParameter().get(1).getUse()); - assertEquals(0, def.getParameter().get(1).getMin()); - assertEquals("1", def.getParameter().get(1).getMax()); - - assertEquals("PARAM3", def.getParameter().get(2).getName()); - assertEquals(OperationParameterUse.IN, def.getParameter().get(2).getUse()); - assertEquals(2, def.getParameter().get(2).getMin()); - assertEquals("5", def.getParameter().get(2).getMax()); - - assertEquals("PARAM4", def.getParameter().get(3).getName()); - assertEquals(OperationParameterUse.IN, def.getParameter().get(3).getUse()); - assertEquals(1, def.getParameter().get(3).getMin()); - assertEquals("*", def.getParameter().get(3).getMax()); - - } - - private List toOpNames(List theOps) { - ArrayList retVal = new ArrayList(); - for (ConformanceRestOperationComponent next : theOps) { - retVal.add(next.getName()); - } - return retVal; - } - - @Test - public void testInstanceEverythingGet() throws Exception { - - // Try with a GET - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$everything"); - CloseableHttpResponse status = ourClient.execute(httpGet); - - assertEquals(200, status.getStatusLine().getStatusCode()); - String response = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals("instance $everything", ourLastMethod); - assertThat(response, startsWith(" getResourceType() { - return Patient.class; - } - - //@formatter:off - @Operation(name="$OP_INSTANCE") - public Parameters opInstance( - @IdParam IdType theId, - @OperationParam(name="PARAM1") StringType theParam1, - @OperationParam(name="PARAM2") Patient theParam2 - ) { - //@formatter:on - - ourLastMethod = "$OP_INSTANCE"; - ourLastId = theId; - ourLastParam1 = theParam1; - ourLastParam2 = theParam2; - - Parameters retVal = new Parameters(); - retVal.addParameter().setName("RET1").setValue(new StringType("RETVAL1")); - return retVal; - } - - //@formatter:off - @Operation(name="$OP_INSTANCE_OR_TYPE") - public Parameters opInstanceOrType( - @IdParam(optional=true) IdType theId, - @OperationParam(name="PARAM1") StringType theParam1, - @OperationParam(name="PARAM2") Patient theParam2 - ) { - //@formatter:on - - ourLastMethod = "$OP_INSTANCE_OR_TYPE"; - ourLastId = theId; - ourLastParam1 = theParam1; - ourLastParam2 = theParam2; - - Parameters retVal = new Parameters(); - retVal.addParameter().setName("RET1").setValue(new StringType("RETVAL1")); - return retVal; - } - - //@formatter:off - @Operation(name="$OP_PROFILE_DT2", idempotent=true) - public Bundle opProfileType( - @OperationParam(name="PARAM1") Money theParam1 - ) { - //@formatter:on - - ourLastMethod = "$OP_PROFILE_DT2"; - ourLastParamMoney1 = theParam1; - - Bundle retVal = new Bundle(); - retVal.addEntry().getResponse().setStatus("100"); - return retVal; - } - - //@formatter:off - @Operation(name="$OP_PROFILE_DT", idempotent=true) - public Bundle opProfileType( - @OperationParam(name="PARAM1") UnsignedIntType theParam1 - ) { - //@formatter:on - - ourLastMethod = "$OP_PROFILE_DT"; - ourLastParamUnsignedInt1 = theParam1; - - Bundle retVal = new Bundle(); - retVal.addEntry().getResponse().setStatus("100"); - return retVal; - } - - //@formatter:off - @SuppressWarnings("unused") - @Operation(name="$OP_TYPE", idempotent=true) - public Parameters opType( - @OperationParam(name="PARAM1") StringType theParam1, - @OperationParam(name="PARAM2") Patient theParam2, - @OperationParam(name="PARAM3", min=2, max=5) List theParam3, - @OperationParam(name="PARAM4", min=1) List theParam4 - ) { - //@formatter:on - - ourLastMethod = "$OP_TYPE"; - ourLastParam1 = theParam1; - ourLastParam2 = theParam2; - - Parameters retVal = new Parameters(); - retVal.addParameter().setName("RET1").setValue(new StringType("RETVAL1")); - return retVal; - } - - //@formatter:off - @Operation(name="$OP_TYPE_ONLY_STRING", idempotent=true) - public Parameters opTypeOnlyString( - @OperationParam(name="PARAM1") StringType theParam1 - ) { - //@formatter:on - - ourLastMethod = "$OP_TYPE"; - ourLastParam1 = theParam1; - - Parameters retVal = new Parameters(); - retVal.addParameter().setName("RET1").setValue(new StringType("RETVAL1")); - return retVal; - } - - //@formatter:off - @Operation(name="$OP_TYPE_RET_BUNDLE") - public Bundle opTypeRetBundle( - @OperationParam(name="PARAM1") StringType theParam1, - @OperationParam(name="PARAM2") Patient theParam2 - ) { - //@formatter:on - - ourLastMethod = "$OP_TYPE_RET_BUNDLE"; - ourLastParam1 = theParam1; - ourLastParam2 = theParam2; - - Bundle retVal = new Bundle(); - retVal.addEntry().getResponse().setStatus("100"); - return retVal; - } - - @Operation(name = "$everything", idempotent=true) - public Bundle patientEverything(@IdParam IdType thePatientId) { - ourLastMethod = "instance $everything"; - ourLastId = thePatientId; - return new Bundle(); - } - - /** - * Just to make sure this method doesn't "steal" calls - */ - @Read - public Patient read(@IdParam IdType theId) { - ourLastMethod = "read"; - Patient retVal = new Patient(); - retVal.setId(theId); - return retVal; - } - - } - - public static class PlainProvider { - - //@formatter:off - @Operation(name="$OP_INSTANCE_BUNDLE_PROVIDER", idempotent=true) - public IBundleProvider opInstanceReturnsBundleProvider() { - ourLastMethod = "$OP_INSTANCE_BUNDLE_PROVIDER"; - - List resources = new ArrayList<>(); - for (int i =0; i < 100;i++) { - Patient p = new Patient(); - p.setId("Patient/" + i); - p.addName().addFamily("Patient " + i); - resources.add(p); - } - - return new SimpleBundleProvider(resources); - } - - //@formatter:off - @Operation(name="$OP_SERVER") - public Parameters opServer( - @OperationParam(name="PARAM1") StringType theParam1, - @OperationParam(name="PARAM2") Patient theParam2 - ) { - //@formatter:on - - ourLastMethod = "$OP_SERVER"; - ourLastParam1 = theParam1; - ourLastParam2 = theParam2; - - Parameters retVal = new Parameters(); - retVal.addParameter().setName("RET1").setValue(new StringType("RETVAL1")); - return retVal; - } - - //@formatter:off - @Operation(name="$OP_SERVER_LIST_PARAM") - public Parameters opServerListParam( - @OperationParam(name="PARAM2") Patient theParam2, - @OperationParam(name="PARAM3") List theParam3 - ) { - //@formatter:on - - ourLastMethod = "$OP_SERVER_LIST_PARAM"; - ourLastParam2 = theParam2; - ourLastParam3 = theParam3; - - Parameters retVal = new Parameters(); - retVal.addParameter().setName("RET1").setValue(new StringType("RETVAL1")); - return retVal; - } - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu2_1Test.java deleted file mode 100644 index d8054c0c07e..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu2_1Test.java +++ /dev/null @@ -1,514 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.Operation; -import ca.uhn.fhir.rest.annotation.OperationParam; -import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.api.server.RequestDetails; -import ca.uhn.fhir.rest.param.StringAndListParam; -import ca.uhn.fhir.rest.param.StringOrListParam; -import ca.uhn.fhir.rest.param.StringParam; -import ca.uhn.fhir.rest.param.TokenAndListParam; -import ca.uhn.fhir.rest.param.TokenOrListParam; -import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.rest.param.TokenParamModifier; -import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import ca.uhn.fhir.util.UrlUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -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.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.hapi.rest.server.ServerConformanceProvider; -import org.hl7.fhir.dstu2016may.model.Conformance; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.OperationDefinition; -import org.hl7.fhir.dstu2016may.model.Parameters; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.dstu2016may.model.StringType; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.servlet.ServletConfig; -import javax.servlet.http.HttpServletRequest; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.stringContainsInOrder; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class OperationServerWithSearchParamTypesDstu2_1Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; - - private static String ourLastMethod; - private static List ourLastParamValStr; - private static List ourLastParamValTok; - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationServerWithSearchParamTypesDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - @BeforeEach - public void before() { - ourLastMethod = ""; - ourLastParamValStr = null; - ourLastParamValTok = null; - } - - private HttpServletRequest createHttpServletRequest() { - HttpServletRequest req = mock(HttpServletRequest.class); - when(req.getRequestURI()).thenReturn("/FhirStorm/fhir/Patient/_search"); - when(req.getServletPath()).thenReturn("/fhir"); - when(req.getRequestURL()).thenReturn(new StringBuffer().append("http://fhirstorm.dyndns.org:8080/FhirStorm/fhir/Patient/_search")); - when(req.getContextPath()).thenReturn("/FhirStorm"); - return req; - } - - private ServletConfig createServletConfig() { - ServletConfig sc = mock(ServletConfig.class); - when(sc.getServletContext()).thenReturn(null); - return sc; - } - - @Test - public void testAndListWithParameters() throws Exception { - Parameters p = new Parameters(); - p.addParameter().setName("valstr").setValue(new StringType("VALSTR1A,VALSTR1B")); - p.addParameter().setName("valstr").setValue(new StringType("VALSTR2A,VALSTR2B")); - p.addParameter().setName("valtok").setValue(new StringType("VALTOK1A|VALTOK1B")); - p.addParameter().setName("valtok").setValue(new StringType("VALTOK2A|VALTOK2B")); - String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$andlist"); - httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); - HttpResponse status = ourClient.execute(httpPost); - - assertEquals(200, status.getStatusLine().getStatusCode()); - String response = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(response); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals(2, ourLastParamValStr.size()); - assertEquals(2, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALSTR1A", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALSTR1B", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(1).getValue()); - assertEquals("VALSTR2A", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALSTR2B", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(1).getValue()); - assertEquals(2, ourLastParamValTok.size()); - assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALTOK1A", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOK1B", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALTOK2A", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOK2B", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("type $orlist", ourLastMethod); - } - - @Test - public void testEscapedOperationName() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/%24andlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); - HttpResponse status = ourClient.execute(httpGet); - - assertEquals(200, status.getStatusLine().getStatusCode()); - String response = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(response); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals(2, ourLastParamValStr.size()); - } - - @Test - public void testAndListWithUrl() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$andlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); - HttpResponse status = ourClient.execute(httpGet); - - assertEquals(200, status.getStatusLine().getStatusCode()); - String response = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(response); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals(2, ourLastParamValStr.size()); - assertEquals(2, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALSTR1A", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALSTR1B", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(1).getValue()); - assertEquals("VALSTR2A", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALSTR2B", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(1).getValue()); - assertEquals(2, ourLastParamValTok.size()); - assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALTOK1A", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOK1B", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALTOK2A", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOK2B", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("type $orlist", ourLastMethod); - } - - @Test - public void testGenerateConformance() throws Exception { - RestfulServer rs = new RestfulServer(ourCtx); - rs.setProviders(new PatientProvider()); - - ServerConformanceProvider sc = new ServerConformanceProvider(rs); - rs.setServerConformanceProvider(sc); - - rs.init(createServletConfig()); - - Conformance conformance = sc.getServerConformance(createHttpServletRequest(), createRequestDetails(rs)); - - String conf = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(conformance); - ourLog.info(conf); - //@formatter:off - assertThat(conf, stringContainsInOrder( - "", - "", - "", - "" - )); - assertThat(conf, stringContainsInOrder( - "", - "", - "" - )); - assertThat(conf, stringContainsInOrder( - "", - "", - "" - )); - //@formatter:on - - /* - * Check the operation definitions themselves - */ - OperationDefinition andListDef = sc.readOperationDefinition(new IdType("OperationDefinition/Patient-t-andlist"), createRequestDetails(rs)); - String def = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(andListDef); - ourLog.info(def); - //@formatter:off - assertThat(def, stringContainsInOrder( - "", - "", - "", - "", - "", - "", - "", - "" - )); - //@formatter:on - - andListDef = sc.readOperationDefinition(new IdType("OperationDefinition/Patient-t-andlist-withnomax"), createRequestDetails(rs)); - def = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(andListDef); - ourLog.info(def); - //@formatter:off - assertThat(def, stringContainsInOrder( - "", - "", - "", - "", - "", - "", - "", - "" - )); - //@formatter:on - - OperationDefinition orListDef = sc.readOperationDefinition(new IdType("OperationDefinition/Patient-t-orlist"), createRequestDetails(rs)); - def = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(orListDef); - ourLog.info(def); - //@formatter:off - assertThat(def, stringContainsInOrder( - "", - "", - "", - "", - "", - "", - "", - "" - )); - //@formatter:on - - orListDef = sc.readOperationDefinition(new IdType("OperationDefinition/Patient-t-orlist-withnomax"), createRequestDetails(rs)); - def = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(orListDef); - ourLog.info(def); - //@formatter:off - assertThat(def, stringContainsInOrder( - "", - "", - "", - "", - "", - "", - "", - "" - )); - //@formatter:on - - } - - @Test - public void testNonRepeatingWithParams() throws Exception { - Parameters p = new Parameters(); - p.addParameter().setName("valstr").setValue(new StringType("VALSTR")); - p.addParameter().setName("valtok").setValue(new StringType("VALTOKA|VALTOKB")); - String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$nonrepeating"); - httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); - HttpResponse status = ourClient.execute(httpPost); - - assertEquals(200, status.getStatusLine().getStatusCode()); - String response = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(response); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals(1, ourLastParamValStr.size()); - assertEquals(1, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALSTR", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals(1, ourLastParamValTok.size()); - assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALTOKA", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOKB", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("type $nonrepeating", ourLastMethod); - } - @Test - public void testNonRepeatingWithUrl() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$nonrepeating?valstr=VALSTR&valtok=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); - HttpResponse status = ourClient.execute(httpGet); - - assertEquals(200, status.getStatusLine().getStatusCode()); - String response = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(response); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals(1, ourLastParamValStr.size()); - assertEquals(1, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALSTR", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals(1, ourLastParamValTok.size()); - assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALTOKA", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOKB", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("type $nonrepeating", ourLastMethod); - } - - @Test - public void testNonRepeatingWithUrlQualified() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$nonrepeating?valstr:exact=VALSTR&valtok:not=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); - HttpResponse status = ourClient.execute(httpGet); - - assertEquals(200, status.getStatusLine().getStatusCode()); - String response = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(response); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals(1, ourLastParamValStr.size()); - assertEquals(1, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALSTR", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertTrue(ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).isExact()); - assertEquals(1, ourLastParamValTok.size()); - assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALTOKA", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOKB", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals(TokenParamModifier.NOT, ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getModifier()); - assertEquals("type $nonrepeating", ourLastMethod); - } - - @Test - public void testOrListWithParameters() throws Exception { - Parameters p = new Parameters(); - p.addParameter().setName("valstr").setValue(new StringType("VALSTR1A,VALSTR1B")); - p.addParameter().setName("valstr").setValue(new StringType("VALSTR2A,VALSTR2B")); - p.addParameter().setName("valtok").setValue(new StringType("VALTOK1A|VALTOK1B")); - p.addParameter().setName("valtok").setValue(new StringType("VALTOK2A|VALTOK2B")); - String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$orlist"); - httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); - HttpResponse status = ourClient.execute(httpPost); - - assertEquals(200, status.getStatusLine().getStatusCode()); - String response = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(response); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals(2, ourLastParamValStr.size()); - assertEquals(2, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALSTR1A", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALSTR1B", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(1).getValue()); - assertEquals("VALSTR2A", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALSTR2B", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(1).getValue()); - assertEquals(2, ourLastParamValTok.size()); - assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALTOK1A", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOK1B", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALTOK2A", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOK2B", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("type $orlist", ourLastMethod); - } - - @Test - public void testOrListWithUrl() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$orlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); - HttpResponse status = ourClient.execute(httpGet); - - assertEquals(200, status.getStatusLine().getStatusCode()); - String response = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(response); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals(2, ourLastParamValStr.size()); - assertEquals(2, ourLastParamValStr.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALSTR1A", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALSTR1B", ourLastParamValStr.get(0).getValuesAsQueryTokens().get(1).getValue()); - assertEquals("VALSTR2A", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALSTR2B", ourLastParamValStr.get(1).getValuesAsQueryTokens().get(1).getValue()); - assertEquals(2, ourLastParamValTok.size()); - assertEquals(1, ourLastParamValTok.get(0).getValuesAsQueryTokens().size()); - assertEquals("VALTOK1A", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOK1B", ourLastParamValTok.get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("VALTOK2A", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("VALTOK2B", ourLastParamValTok.get(1).getValuesAsQueryTokens().get(0).getValue()); - assertEquals("type $orlist", ourLastMethod); - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu2_1(); - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); - - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(new PatientProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class PatientProvider implements IResourceProvider { - - - @Operation(name = "$andlist", idempotent = true) - public Parameters andlist( - //@formatter:off - @OperationParam(name="valstr", max=10) StringAndListParam theValStr, - @OperationParam(name="valtok", max=10) TokenAndListParam theValTok - //@formatter:on - ) { - ourLastMethod = "type $orlist"; - ourLastParamValStr = theValStr.getValuesAsQueryTokens(); - ourLastParamValTok = theValTok.getValuesAsQueryTokens(); - - return createEmptyParams(); - } - - @Operation(name = "$andlist-withnomax", idempotent = true) - public Parameters andlistWithNoMax( - //@formatter:off - @OperationParam(name="valstr") StringAndListParam theValStr, - @OperationParam(name="valtok") TokenAndListParam theValTok - //@formatter:on - ) { - ourLastMethod = "type $orlist"; - ourLastParamValStr = theValStr.getValuesAsQueryTokens(); - ourLastParamValTok = theValTok.getValuesAsQueryTokens(); - - return createEmptyParams(); - } - - /** - * Just so we have something to return - */ - private Parameters createEmptyParams() { - Parameters retVal = new Parameters(); - retVal.setId("100"); - return retVal; - } - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Operation(name = "$nonrepeating", idempotent = true) - public Parameters nonrepeating( - //@formatter:off - @OperationParam(name="valstr") StringParam theValStr, - @OperationParam(name="valtok") TokenParam theValTok - //@formatter:on - ) { - ourLastMethod = "type $nonrepeating"; - ourLastParamValStr = Collections.singletonList(new StringOrListParam().add(theValStr)); - ourLastParamValTok = Collections.singletonList(new TokenOrListParam().add(theValTok)); - - return createEmptyParams(); - } - - @Operation(name = "$orlist", idempotent = true) - public Parameters orlist( - //@formatter:off - @OperationParam(name="valstr", max=10) List theValStr, - @OperationParam(name="valtok", max=10) List theValTok - //@formatter:on - ) { - ourLastMethod = "type $orlist"; - ourLastParamValStr = theValStr; - ourLastParamValTok = theValTok; - - return createEmptyParams(); - } - - @Operation(name = "$orlist-withnomax", idempotent = true) - public Parameters orlistWithNoMax( - //@formatter:off - @OperationParam(name="valstr") List theValStr, - @OperationParam(name="valtok") List theValTok - //@formatter:on - ) { - ourLastMethod = "type $orlist"; - ourLastParamValStr = theValStr; - ourLastParamValTok = theValTok; - - return createEmptyParams(); - } - - } - - - private RequestDetails createRequestDetails(RestfulServer theServer) { - ServletRequestDetails retVal = new ServletRequestDetails(); - retVal.setServer(theServer); - return retVal; - } - -} - diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/PatchDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/PatchDstu2_1Test.java deleted file mode 100644 index 970b61397e7..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/PatchDstu2_1Test.java +++ /dev/null @@ -1,188 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.i18n.Msg; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.Patch; -import ca.uhn.fhir.rest.annotation.ResourceParam; -import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.rest.api.PatchTypeEnum; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.OperationOutcome; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class PatchDstu2_1Test { - - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(PatchDstu2_1Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static int ourPort; - private static Server ourServer; - private static String ourLastMethod; - private static PatchTypeEnum ourLastPatchType; - private static String ourLastBody; - private static IdType ourLastId; - - @BeforeEach - public void before() { - ourLastMethod = null; - ourLastBody = null; - ourLastId = null; - } - - @Test - public void testPatchValidJson() throws Exception { - String requestContents = "[ { \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ \"foo\", \"bar\" ] } ]"; - HttpPatch httpPatch = new HttpPatch("http://localhost:" + ourPort + "/Patient/123"); - httpPatch.setEntity(new StringEntity(requestContents, ContentType.parse(Constants.CT_JSON_PATCH))); - httpPatch.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); - try (CloseableHttpResponse status = ourClient.execute(httpPatch)) { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals("
    OK
    ", responseContent); - } - - assertEquals("patientPatch", ourLastMethod); - assertEquals("Patient/123", ourLastId.getValue()); - assertEquals(requestContents, ourLastBody); - assertEquals(PatchTypeEnum.JSON_PATCH, ourLastPatchType); - } - - @Test - public void testPatchValidXml() throws Exception { - String requestContents = ""; - HttpPatch httpPatch = new HttpPatch("http://localhost:" + ourPort + "/Patient/123"); - httpPatch.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); - httpPatch.setEntity(new StringEntity(requestContents, ContentType.parse(Constants.CT_XML_PATCH))); - - try (CloseableHttpResponse status = ourClient.execute(httpPatch)) { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals("
    OK
    ", responseContent); - } - - assertEquals("patientPatch", ourLastMethod); - assertEquals("Patient/123", ourLastId.getValue()); - assertEquals(requestContents, ourLastBody); - assertEquals(PatchTypeEnum.XML_PATCH, ourLastPatchType); - } - - @Test - public void testPatchValidJsonWithCharset() throws Exception { - String requestContents = "[ { \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ \"foo\", \"bar\" ] } ]"; - HttpPatch httpPatch = new HttpPatch("http://localhost:" + ourPort + "/Patient/123"); - httpPatch.setEntity(new StringEntity(requestContents, ContentType.parse(Constants.CT_JSON_PATCH + Constants.CHARSET_UTF8_CTSUFFIX))); - CloseableHttpResponse status = ourClient.execute(httpPatch); - - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - assertEquals("patientPatch", ourLastMethod); - assertEquals("Patient/123", ourLastId.getValue()); - assertEquals(requestContents, ourLastBody); - } - - @Test - public void testPatchInvalidMimeType() throws Exception { - String requestContents = "[ { \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ \"foo\", \"bar\" ] } ]"; - HttpPatch httpPatch = new HttpPatch("http://localhost:" + ourPort + "/Patient/123"); - httpPatch.setEntity(new StringEntity(requestContents, ContentType.parse("text/plain; charset=UTF-8"))); - CloseableHttpResponse status = ourClient.execute(httpPatch); - - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(responseContent); - assertEquals(400, status.getStatusLine().getStatusCode()); - assertEquals("", responseContent); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - - @Override - public Class getResourceType() { - return Patient.class; - } - - //@formatter:off - @Patch - public OperationOutcome patientPatch(@IdParam IdType theId, PatchTypeEnum thePatchType, @ResourceParam String theBody) { - ourLastMethod = "patientPatch"; - ourLastBody = theBody; - ourLastId = theId; - ourLastPatchType = thePatchType; - OperationOutcome retVal = new OperationOutcome(); - retVal.getText().setDivAsString("
    OK
    "); - return retVal; - } - //@formatter:on - - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ReadDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ReadDstu2_1Test.java deleted file mode 100644 index ef1892e907c..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ReadDstu2_1Test.java +++ /dev/null @@ -1,122 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.Read; -import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.client.MyPatientWithExtensions; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.DateType; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.stringContainsInOrder; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class ReadDstu2_1Test { - private static CloseableHttpClient ourClient; - - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ReadDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - - - @Test - public void testRead() throws Exception { - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2?_format=xml&_pretty=true"); - HttpResponse status = ourClient.execute(httpGet); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals(null, status.getFirstHeader(Constants.HEADER_LOCATION)); - assertEquals("http://localhost:" + ourPort + "/Patient/2/_history/2", status.getFirstHeader(Constants.HEADER_CONTENT_LOCATION).getValue()); - - //@formatter:off - assertThat(responseContent, stringContainsInOrder( - "", - "", - "", - "", - "", - "", - "", - "", - "")); - //@formatter:on - } - - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class PatientProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Read(version=true) - public MyPatientWithExtensions read(@IdParam IdType theIdParam) { - MyPatientWithExtensions p0 = new MyPatientWithExtensions(); - p0.setId(theIdParam); - if (theIdParam.hasVersionIdPart() == false) { - p0.setIdElement(p0.getIdElement().withVersion("2")); - } - p0.setDateExt(new DateType("2011-01-01")); - return p0; - } - - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu2_1Test.java deleted file mode 100644 index 126f01451ae..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu2_1Test.java +++ /dev/null @@ -1,184 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.Count; -import ca.uhn.fhir.rest.annotation.OptionalParam; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.HumanName; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.stringContainsInOrder; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class SearchCountParamDstu2_1Test { - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchCountParamDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - private static String ourLastMethod; - private static Integer ourLastParam; - - @BeforeEach - public void before() { - ourLastMethod = null; - ourLastParam = null; - } - - @Test - public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_count=2"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals("search", ourLastMethod); - assertEquals(new Integer(2), ourLastParam); - - //@formatter:off - assertThat(responseContent, stringContainsInOrder( - "", - "", - "", - "", - "", - "", - "", - "")); - //@formatter:on - - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - /** - * See #372 - */ - @Test - public void testSearchWithNoCountParam() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithNoCountParam&_count=2"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals("searchWithNoCountParam", ourLastMethod); - assertEquals(null, ourLastParam); - - //@formatter:off - assertThat(responseContent, stringContainsInOrder( - "", - "", - "", - "", - "", - "", - "", - "")); - //@formatter:on - - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - //@formatter:off - @SuppressWarnings("rawtypes") - @Search() - public List search( - @OptionalParam(name=Patient.SP_IDENTIFIER) TokenParam theIdentifier, - @Count() Integer theParam - ) { - ourLastMethod = "search"; - ourLastParam = theParam; - ArrayList retVal = new ArrayList(); - for (int i = 1; i < 100; i++) { - retVal.add((Patient) new Patient().addName(new HumanName().addFamily("FAMILY")).setId("" + i)); - } - return retVal; - } - //@formatter:on - - //@formatter:off - @SuppressWarnings("rawtypes") - @Search(queryName="searchWithNoCountParam") - public List searchWithNoCountParam() { - ourLastMethod = "searchWithNoCountParam"; - ourLastParam = null; - ArrayList retVal = new ArrayList(); - for (int i = 1; i < 100; i++) { - retVal.add((Patient) new Patient().addName(new HumanName().addFamily("FAMILY")).setId("" + i)); - } - return retVal; - } - //@formatter:on - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchDstu2_1Test.java deleted file mode 100644 index dea3760cf4e..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchDstu2_1Test.java +++ /dev/null @@ -1,142 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.i18n.Msg; -import ca.uhn.fhir.rest.annotation.OptionalParam; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.rest.param.TokenAndListParam; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.HumanName; -import org.hl7.fhir.dstu2016may.model.OperationOutcome; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class SearchDstu2_1Test { - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - private static String ourLastMethod; - private static TokenAndListParam ourIdentifiers; - - @BeforeEach - public void before() { - ourLastMethod = null; - ourIdentifiers = null; - } - - @Test - public void testSearchNormal() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo%7Cbar"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertEquals("search", ourLastMethod); - - assertEquals("foo", ourIdentifiers.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getSystem()); - assertEquals("bar", ourIdentifiers.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue()); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - @Test - public void testSearchWithInvalidChain() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier.chain=foo%7Cbar"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(responseContent); - assertEquals(400, status.getStatusLine().getStatusCode()); - - OperationOutcome oo = (OperationOutcome) ourCtx.newXmlParser().parseResource(responseContent); - assertEquals(Msg.code(1935) + "Invalid search parameter \"identifier.chain\". Parameter contains a chain (.chain) and chains are not supported for this parameter (chaining is only allowed on reference parameters)", oo.getIssue().get(0).getDiagnostics()); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - //@formatter:off - @SuppressWarnings("rawtypes") - @Search() - public List search( - @OptionalParam(name=Patient.SP_IDENTIFIER) TokenAndListParam theIdentifiers - ) { - ourLastMethod = "search"; - ourIdentifiers = theIdentifiers; - ArrayList retVal = new ArrayList(); - retVal.add((Patient) new Patient().addName(new HumanName().addFamily("FAMILY")).setId("1")); - return retVal; - } - //@formatter:on - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamDstu2_1Test.java deleted file mode 100644 index fcd300cee41..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamDstu2_1Test.java +++ /dev/null @@ -1,121 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.OptionalParam; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.param.HasAndListParam; -import ca.uhn.fhir.rest.param.HasParam; -import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.HumanName; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class SearchHasParamDstu2_1Test { - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchHasParamDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - private static String ourLastMethod; - private static HasAndListParam ourLastParam; - - @BeforeEach - public void before() { - ourLastMethod = null; - ourLastParam = null; - } - - @Test - public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_has:Encounter:patient:type=SURG"); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals("search", ourLastMethod); - - HasParam param = ourLastParam.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0); - assertEquals("Encounter", param.getTargetResourceType()); - assertEquals("patient", param.getReferenceFieldName()); - assertEquals("type", param.getParameterName()); - assertEquals("SURG", param.getParameterValue()); - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - //@formatter:off - @SuppressWarnings("rawtypes") - @Search() - public List search( - @OptionalParam(name=Patient.SP_IDENTIFIER) TokenParam theIdentifier, - @OptionalParam(name="_has") HasAndListParam theParam - ) { - ourLastMethod = "search"; - ourLastParam = theParam; - ArrayList retVal = new ArrayList(); - retVal.add((Patient) new Patient().addName(new HumanName().addFamily("FAMILY")).setId("1")); - return retVal; - } - //@formatter:on - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchPostDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchPostDstu2_1Test.java deleted file mode 100644 index 7ab78bee8b9..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchPostDstu2_1Test.java +++ /dev/null @@ -1,260 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.OptionalParam; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.annotation.Sort; -import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.rest.api.SortSpec; -import ca.uhn.fhir.rest.param.StringAndListParam; -import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import com.google.common.collect.Lists; -import org.apache.commons.io.IOUtils; -import org.apache.http.NameValuePair; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicNameValuePair; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.HumanName; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class SearchPostDstu2_1Test { - - public class ParamLoggingInterceptor extends InterceptorAdapter { - - @Override - public boolean incomingRequestPreProcessed(HttpServletRequest theRequest, HttpServletResponse theResponse) { - ourLog.info("Params: {}", theRequest.getParameterMap()); - return true; - } - - - } - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchPostDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - private static String ourLastMethod; - private static SortSpec ourLastSortSpec; - private static StringAndListParam ourLastName; - private static RestfulServer ourServlet; - - @BeforeEach - public void before() { - ourLastMethod = null; - ourLastSortSpec = null; - ourLastName = null; - - ourServlet.getInterceptorService().unregisterAllInterceptors(); - } - - /** - * See #411 - */ - @Test - public void testSearchWithMixedParamsNoInterceptorsYesParams() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search?_format="+Constants.CT_FHIR_JSON); - httpPost.addHeader("Cache-Control","no-cache"); - List parameters = Lists.newArrayList(); - parameters.add(new BasicNameValuePair("name", "Smith")); - httpPost.setEntity(new UrlEncodedFormEntity(parameters)); - - ourLog.info("Outgoing post: {}", httpPost); - - CloseableHttpResponse status = ourClient.execute(httpPost); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertEquals("search", ourLastMethod); - assertEquals(null, ourLastSortSpec); - assertEquals(1, ourLastName.getValuesAsQueryTokens().size()); - assertEquals(1, ourLastName.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().size()); - assertEquals("Smith", ourLastName.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals(Constants.CT_FHIR_JSON, status.getEntity().getContentType().getValue().replaceAll(";.*", "")); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - /** - * See #411 - */ - @Test - public void testSearchWithMixedParamsNoInterceptorsNoParams() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search"); - httpPost.addHeader("Cache-Control","no-cache"); - List parameters = Lists.newArrayList(); - parameters.add(new BasicNameValuePair("name", "Smith")); - httpPost.setEntity(new UrlEncodedFormEntity(parameters)); - - ourLog.info("Outgoing post: {}", httpPost); - - CloseableHttpResponse status = ourClient.execute(httpPost); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertEquals("search", ourLastMethod); - assertEquals(null, ourLastSortSpec); - assertEquals(1, ourLastName.getValuesAsQueryTokens().size()); - assertEquals(1, ourLastName.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().size()); - assertEquals("Smith", ourLastName.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals(Constants.CT_FHIR_XML, status.getEntity().getContentType().getValue().replaceAll(";.*", "")); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - /** - * See #411 - */ - @Test - public void testSearchWithMixedParamsYesInterceptorsYesParams() throws Exception { - ourServlet.registerInterceptor(new ParamLoggingInterceptor()); - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search?_format="+Constants.CT_FHIR_JSON); - httpPost.addHeader("Cache-Control","no-cache"); - List parameters = Lists.newArrayList(); - parameters.add(new BasicNameValuePair("name", "Smith")); - httpPost.setEntity(new UrlEncodedFormEntity(parameters)); - - ourLog.info("Outgoing post: {}", httpPost); - - CloseableHttpResponse status = ourClient.execute(httpPost); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertEquals("search", ourLastMethod); - assertEquals(null, ourLastSortSpec); - assertEquals(1, ourLastName.getValuesAsQueryTokens().size()); - assertEquals(1, ourLastName.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().size()); - assertEquals("Smith", ourLastName.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals(Constants.CT_FHIR_JSON, status.getEntity().getContentType().getValue().replaceAll(";.*", "")); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - /** - * See #411 - */ - @Test - public void testSearchWithMixedParamsYesInterceptorsNoParams() throws Exception { - ourServlet.registerInterceptor(new ParamLoggingInterceptor()); - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search"); - httpPost.addHeader("Cache-Control","no-cache"); - List parameters = Lists.newArrayList(); - parameters.add(new BasicNameValuePair("name", "Smith")); - httpPost.setEntity(new UrlEncodedFormEntity(parameters)); - - ourLog.info("Outgoing post: {}", httpPost); - - CloseableHttpResponse status = ourClient.execute(httpPost); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertEquals("search", ourLastMethod); - assertEquals(null, ourLastSortSpec); - assertEquals(1, ourLastName.getValuesAsQueryTokens().size()); - assertEquals(1, ourLastName.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().size()); - assertEquals("Smith", ourLastName.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue()); - assertEquals(Constants.CT_FHIR_XML, status.getEntity().getContentType().getValue().replaceAll(";.*", "")); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - ourServlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - //@formatter:off - @SuppressWarnings("rawtypes") - @Search() - public List search( - @Sort SortSpec theSortSpec, - @OptionalParam(name=Patient.SP_NAME) StringAndListParam theName - ) { - ourLastMethod = "search"; - ourLastSortSpec = theSortSpec; - ourLastName = theName; - ArrayList retVal = new ArrayList<>(); - retVal.add((Patient) new Patient().addName(new HumanName().addFamily("FAMILY")).setId("foo")); - return retVal; - } - //@formatter:on - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchSortDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchSortDstu2_1Test.java deleted file mode 100644 index 2abec3a4fb3..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchSortDstu2_1Test.java +++ /dev/null @@ -1,132 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.annotation.Sort; -import ca.uhn.fhir.rest.api.SortOrderEnum; -import ca.uhn.fhir.rest.api.SortSpec; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.HumanName; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class SearchSortDstu2_1Test { - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchSortDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - private static String ourLastMethod; - private static SortSpec ourLastSortSpec; - - @BeforeEach - public void before() { - ourLastMethod = null; - ourLastSortSpec = null; - } - - @Test - public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_sort=param1,-param2,param3,-param4"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertEquals("search", ourLastMethod); - - assertEquals("param1", ourLastSortSpec.getParamName()); - assertEquals(SortOrderEnum.ASC, ourLastSortSpec.getOrder()); - - assertEquals("param2", ourLastSortSpec.getChain().getParamName()); - assertEquals(SortOrderEnum.DESC, ourLastSortSpec.getChain().getOrder()); - - assertEquals("param3", ourLastSortSpec.getChain().getChain().getParamName()); - assertEquals(SortOrderEnum.ASC, ourLastSortSpec.getChain().getChain().getOrder()); - - assertEquals("param4", ourLastSortSpec.getChain().getChain().getChain().getParamName()); - assertEquals(SortOrderEnum.DESC, ourLastSortSpec.getChain().getChain().getChain().getOrder()); - - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - //@formatter:off - @SuppressWarnings("rawtypes") - @Search() - public List search( - @Sort SortSpec theSortSpec - ) { - ourLastMethod = "search"; - ourLastSortSpec = theSortSpec; - ArrayList retVal = new ArrayList(); - for (int i = 1; i < 100; i++) { - retVal.add((Patient) new Patient().addName(new HumanName().addFamily("FAMILY")).setId("" + i)); - } - return retVal; - } - //@formatter:on - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu2_1Test.java index e565e08a5f0..3f80fe2b250 100644 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu2_1Test.java +++ b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu2_1Test.java @@ -5,28 +5,22 @@ import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu2016may.model.HumanName; import org.hl7.fhir.dstu2016may.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -34,13 +28,18 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchWithGenericListDstu2_1Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); + private static final FhirContext ourCtx = FhirContext.forDstu2_1(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithGenericListDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; private static String ourLastMethod; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -51,7 +50,7 @@ public class SearchWithGenericListDstu2_1Test { */ @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier=foo&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -59,43 +58,17 @@ public class SearchWithGenericListDstu2_1Test { assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals("searchByIdentifier", ourLastMethod); assertThat(responseContent, containsString("")); + assertThat(responseContent, containsString("")); } @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override @@ -109,7 +82,7 @@ public class SearchWithGenericListDstu2_1Test { public List searchByIdentifier( @RequiredParam(name=Patient.SP_IDENTIFIER) TokenParam theIdentifier) { ourLastMethod = "searchByIdentifier"; - ArrayList retVal = new ArrayList(); + ArrayList retVal = new ArrayList<>(); retVal.add((Patient) new Patient().addName(new HumanName().addFamily("FAMILY")).setId("1")); return retVal; } diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithIncludesDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithIncludesDstu2_1Test.java deleted file mode 100644 index 97b88e3bcad..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithIncludesDstu2_1Test.java +++ /dev/null @@ -1,135 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.Include; -import ca.uhn.fhir.rest.annotation.IncludeParam; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.Organization; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class SearchWithIncludesDstu2_1Test { - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithIncludesDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - - @Test - public void testSearchIncludesReferences() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true&_include=Patient:organization&_include=Organization:" + Organization.SP_PARTOF); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - - // Response should include both the patient, and the organization that was referred to - // by a linked resource - - assertThat(responseContent, containsString("")); - assertThat(responseContent, containsString("")); - assertThat(responseContent, containsString("")); - assertThat(responseContent, containsString("")); - - } - - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - //@formatter:off - @Search() - public List search(@IncludeParam() Set theIncludes) { - ourLog.info("Includes: {}", theIncludes); - - // Grandparent has ID, other orgs don't - Organization gp = new Organization(); - gp.setId("Organization/GP"); - gp.setName("grandparent"); - - Organization parent = new Organization(); - parent.setName("parent"); - parent.getPartOf().setResource(gp); - - Organization child = new Organization(); - child.setName("child"); - child.getPartOf().setResource(parent); - - Patient patient = new Patient(); - patient.setId("Patient/FOO"); - patient.getManagingOrganization().setResource(child); - - ArrayList retVal = new ArrayList(); - retVal.add(patient); - return retVal; - } - //@formatter:on - - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithServerAddressStrategyDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithServerAddressStrategyDstu2_1Test.java deleted file mode 100644 index d486934fa09..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/SearchWithServerAddressStrategyDstu2_1Test.java +++ /dev/null @@ -1,172 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.HumanName; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class SearchWithServerAddressStrategyDstu2_1Test { - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithServerAddressStrategyDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; - - @Test - public void testIncomingRequestAddressStrategy() throws Exception { - ourServlet.setServerAddressStrategy(new IncomingRequestAddressStrategy()); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("")); - } - - @Test - public void testApacheProxyAddressStrategy() throws Exception { - - ourServlet.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttp()); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("")); - - ourServlet.setServerAddressStrategy(new ApacheProxyAddressStrategy(false)); - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); - httpGet.addHeader("x-forwarded-host", "foo.com"); - status = ourClient.execute(httpGet); - responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("")); - - ourServlet.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttps()); - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); - httpGet.addHeader("x-forwarded-host", "foo.com"); - status = ourClient.execute(httpGet); - responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("")); - - ourServlet.setServerAddressStrategy(new ApacheProxyAddressStrategy(false)); - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); - httpGet.addHeader("x-forwarded-host", "foo.com"); - httpGet.addHeader("x-forwarded-proto", "https"); - status = ourClient.execute(httpGet); - responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("")); - - } - - @Test - public void testHardcodedAddressStrategy() throws Exception { - ourServlet.setServerAddressStrategy(new HardcodedServerAddressStrategy("http://example.com/fhir/base")); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); - HttpResponse status = ourClient.execute(httpGet); - String responseContent = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - ourLog.info(responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("")); - } - - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - ourServlet.setResourceProviders(patientProvider); - - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - //@formatter:off - @Search() - public List searchByIdentifier() { - ArrayList retVal = new ArrayList(); - retVal.add((Patient) new Patient().addName(new HumanName().addGiven("FAMILY")).setId("1")); - retVal.add((Patient) new Patient().addName(new HumanName().addGiven("FAMILY")).setId("2")); - return retVal; - } - //@formatter:on - - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerExceptionDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerExceptionDstu2_1Test.java deleted file mode 100644 index ec0f45e8320..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerExceptionDstu2_1Test.java +++ /dev/null @@ -1,137 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; -import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; -import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.OperationOutcome; -import org.hl7.fhir.dstu2016may.model.OperationOutcome.IssueType; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class ServerExceptionDstu2_1Test { - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ServerExceptionDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - public static BaseServerResponseException ourException; - - @Test - public void testAddHeadersNotFound() throws Exception { - - OperationOutcome operationOutcome = new OperationOutcome(); - operationOutcome.addIssue().setCode(IssueType.BUSINESSRULE); - - ourException = new ResourceNotFoundException("SOME MESSAGE"); - ourException.addResponseHeader("X-Foo", "BAR BAR"); - - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(status.getStatusLine().toString()); - ourLog.info(responseContent); - - assertEquals(404, status.getStatusLine().getStatusCode()); - assertEquals("BAR BAR", status.getFirstHeader("X-Foo").getValue()); - assertThat(status.getFirstHeader("X-Powered-By").getValue(), containsString("HAPI FHIR")); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - @Test - public void testAuthorize() throws Exception { - - OperationOutcome operationOutcome = new OperationOutcome(); - operationOutcome.addIssue().setCode(IssueType.BUSINESSRULE); - - ourException = new AuthenticationException().addAuthenticateHeaderForRealm("REALM"); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(status.getStatusLine().toString()); - ourLog.info(responseContent); - - assertEquals(401, status.getStatusLine().getStatusCode()); - assertEquals("Basic realm=\"REALM\"", status.getFirstHeader("WWW-Authenticate").getValue()); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Search() - public List search() { - throw ourException; - } - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeDstu2_1Test.java deleted file mode 100644 index 08854c9b191..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeDstu2_1Test.java +++ /dev/null @@ -1,422 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.Create; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.Read; -import ca.uhn.fhir.rest.annotation.ResourceParam; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.rest.client.MyPatientWithExtensions; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.methods.HttpTrace; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.CodeType; -import org.hl7.fhir.dstu2016may.model.Conformance; -import org.hl7.fhir.dstu2016may.model.DateType; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.OperationOutcome; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class ServerMimetypeDstu2_1Test { - private static CloseableHttpClient ourClient; - - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ServerMimetypeDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - - @Test - public void testConformanceMetadataUsesNewMimetypes() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/metadata"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String content = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(content); - Conformance conf = ourCtx.newXmlParser().parseResource(Conformance.class, content); - List strings = toStrings(conf.getFormat()); - assertThat(strings, contains(Constants.CT_FHIR_XML, Constants.CT_FHIR_JSON)); - } finally { - status.close(); - } - } - - - - private List toStrings(List theFormat) { - ArrayList retVal = new ArrayList<>(); - for (CodeType next : theFormat) { - retVal.add(next.asStringValue()); - } - return retVal; - } - - - - @Test - public void testCreateWithXmlLegacyNoAcceptHeader() throws Exception { - Patient p = new Patient(); - p.addName().addFamily("FAMILY"); - String enc = ourCtx.newXmlParser().encodeResourceToString(p); - String expectedResponseContent = ""; - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); - httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_XML + "; charset=utf-8"))); - HttpResponse status = ourClient.execute(httpPost); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals(Constants.CT_FHIR_XML, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - assertEquals(expectedResponseContent, responseContent); - } - - @Test - public void testHttpTraceNotEnabled() throws Exception { - HttpTrace req = new HttpTrace("http://localhost:" + ourPort + "/Patient"); - CloseableHttpResponse status = ourClient.execute(req); - try { - ourLog.info(status.toString()); - assertEquals(400, status.getStatusLine().getStatusCode()); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - } - - @Test - public void testHttpTrackNotEnabled() throws Exception { - HttpRequestBase req = new HttpRequestBase() { - @Override - public String getMethod() { - return "TRACK"; - }}; - req.setURI(new URI("http://localhost:" + ourPort + "/Patient")); - - CloseableHttpResponse status = ourClient.execute(req); - try { - ourLog.info(status.toString()); - assertEquals(400, status.getStatusLine().getStatusCode()); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - } - - @Test - public void testCreateWithXmlNewNoAcceptHeader() throws Exception { - Patient p = new Patient(); - p.addName().addFamily("FAMILY"); - String enc = ourCtx.newXmlParser().encodeResourceToString(p); - String expectedResponseContent = ""; - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); - httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_XML+ "; charset=utf-8"))); - HttpResponse status = ourClient.execute(httpPost); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals(Constants.CT_FHIR_XML, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - assertEquals(expectedResponseContent, responseContent); - } - - @Test - public void testCreateWithXmlNewWithAcceptHeaderReturnsOperationOutcome() throws Exception { - Patient p = new Patient(); - p.addName().addFamily("FAMILY"); - String enc = ourCtx.newXmlParser().encodeResourceToString(p); - String expectedResponseContent = ""; - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); - httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_XML + "; charset=utf-8"))); - httpPost.addHeader(Constants.HEADER_ACCEPT, Constants.CT_FHIR_XML); - httpPost.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); - HttpResponse status = ourClient.execute(httpPost); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals(Constants.CT_FHIR_XML, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - assertEquals(expectedResponseContent, responseContent); - } - - @Test - public void testCreateWithJsonLegacyNoAcceptHeader() throws Exception { - Patient p = new Patient(); - p.addName().addFamily("FAMILY"); - String enc = ourCtx.newJsonParser().encodeResourceToString(p); - String expectedResponseContent = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\"},\"name\":[{\"family\":[\"FAMILY\"]}]}"; - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); - httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_JSON + "; charset=utf-8"))); - HttpResponse status = ourClient.execute(httpPost); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals(Constants.CT_FHIR_JSON, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - assertEquals(expectedResponseContent, responseContent); - } - - @Test - public void testCreateWithJsonNewNoAcceptHeaderReturnsOperationOutcome() throws Exception { - Patient p = new Patient(); - p.addName().addFamily("FAMILY"); - String enc = ourCtx.newJsonParser().encodeResourceToString(p); - String expectedResponseContent = "{\"resourceType\":\"OperationOutcome\",\"issue\":[{\"diagnostics\":\"FAMILY\"}]}"; - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); - httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_JSON+ "; charset=utf-8"))); - httpPost.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); - HttpResponse status = ourClient.execute(httpPost); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals(Constants.CT_FHIR_JSON, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - assertEquals(expectedResponseContent, responseContent); - } - - @Test - public void testCreateWithJsonNewWithAcceptHeader() throws Exception { - Patient p = new Patient(); - p.addName().addFamily("FAMILY"); - String enc = ourCtx.newJsonParser().encodeResourceToString(p); - String expectedResponseContent = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\"},\"name\":[{\"family\":[\"FAMILY\"]}]}"; - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); - httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_JSON + "; charset=utf-8"))); - httpPost.addHeader(Constants.HEADER_ACCEPT, Constants.CT_FHIR_JSON); - HttpResponse status = ourClient.execute(httpPost); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals(Constants.CT_FHIR_JSON, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - assertEquals(expectedResponseContent, responseContent); - } - - @Test - public void testSearchWithFormatXmlSimple() throws Exception { - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=xml"); - HttpResponse status = ourClient.execute(httpGet); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("")); - assertThat(responseContent, not(containsString("http://hl7.org/fhir/"))); - assertEquals(Constants.CT_FHIR_XML, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - } - - @Test - public void testSearchWithFormatXmlLegacy() throws Exception { - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_XML); - HttpResponse status = ourClient.execute(httpGet); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("")); - assertThat(responseContent, not(containsString("http://hl7.org/fhir/"))); - assertEquals(Constants.CT_FHIR_XML, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - } - - @Test - public void testSearchWithFormatXmlNew() throws Exception { - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_XML); - HttpResponse status = ourClient.execute(httpGet); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("")); - assertThat(responseContent, not(containsString("http://hl7.org/fhir/"))); - assertEquals(Constants.CT_FHIR_XML, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - } - - - - @Test - public void testSearchWithFormatJsonSimple() throws Exception { - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=json"); - HttpResponse status = ourClient.execute(httpGet); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("\"resourceType\"")); - assertEquals(Constants.CT_FHIR_JSON, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - } - - @Test - public void testSearchWithFormatJsonLegacy() throws Exception { - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_JSON); - HttpResponse status = ourClient.execute(httpGet); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("\"resourceType\"")); - assertEquals(Constants.CT_FHIR_JSON, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - } - - @Test - public void testSearchWithFormatJsonNew() throws Exception { - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_JSON); - HttpResponse status = ourClient.execute(httpGet); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("\"resourceType\"")); - assertEquals(Constants.CT_FHIR_JSON, status.getFirstHeader("content-type").getValue().replaceAll(";.*", "")); - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class PatientProvider implements IResourceProvider { - - @Create() - public MethodOutcome create(@ResourceParam Patient theIdParam) { - OperationOutcome oo = new OperationOutcome(); - oo.addIssue().setDiagnostics(theIdParam.getName().get(0).getFamilyAsSingleString()); - theIdParam.setId("1"); - theIdParam.getMeta().setVersionId("1"); - return new MethodOutcome(new IdType("Patient", "1"), true).setOperationOutcome(oo).setResource(theIdParam); - } - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Read() - public MyPatientWithExtensions read(@IdParam IdType theIdParam) { - MyPatientWithExtensions p0 = new MyPatientWithExtensions(); - p0.setId(theIdParam); - p0.setDateExt(new DateType("2011-01-01")); - return p0; - } - - @Search - public List search() { - ArrayList retVal = new ArrayList<>(); - - MyPatientWithExtensions p0 = new MyPatientWithExtensions(); - p0.setId(new IdType("Patient/0")); - p0.setDateExt(new DateType("2011-01-01")); - retVal.add(p0); - - Patient p1 = new Patient(); - p1.setId(new IdType("Patient/1")); - p1.addName().addFamily("The Family"); - retVal.add(p1); - - return retVal; - } - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerUsingOldTypesDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerUsingOldTypesDstu2_1Test.java index afe0e9b97e0..7a4c5855cee 100644 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerUsingOldTypesDstu2_1Test.java +++ b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ServerUsingOldTypesDstu2_1Test.java @@ -14,7 +14,7 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/UnclassifiedServerExceptionDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/UnclassifiedServerExceptionDstu2_1Test.java deleted file mode 100644 index 20b571725b5..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/UnclassifiedServerExceptionDstu2_1Test.java +++ /dev/null @@ -1,108 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.server.exceptions.UnclassifiedServerFailureException; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.OperationOutcome; -import org.hl7.fhir.dstu2016may.model.OperationOutcome.IssueType; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.instance.model.api.IBaseResource; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.stringContainsInOrder; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class UnclassifiedServerExceptionDstu2_1Test { - - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(UnclassifiedServerExceptionDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - public static UnclassifiedServerFailureException ourException; - - @Test - public void testSearch() throws Exception { - - OperationOutcome operationOutcome = new OperationOutcome(); - operationOutcome.addIssue().setCode(IssueType.BUSINESSRULE); - ourException = new UnclassifiedServerFailureException(477, "SOME MESSAGE", operationOutcome); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); - CloseableHttpResponse status = ourClient.execute(httpGet); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info(status.getStatusLine().toString()); - ourLog.info(responseContent); - assertEquals(477, status.getStatusLine().getStatusCode()); - //assertEquals("SOME MESSAGE", status.getStatusLine().getReasonPhrase()); - assertThat(responseContent, stringContainsInOrder("business-rule")); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Search() - public List search() { - throw ourException; - } - - } - -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/UpdateDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/UpdateDstu2_1Test.java deleted file mode 100644 index 6dbba1ac3d9..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/UpdateDstu2_1Test.java +++ /dev/null @@ -1,195 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.i18n.Msg; -import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.ResourceParam; -import ca.uhn.fhir.rest.annotation.Update; -import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.OperationOutcome; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -public class UpdateDstu2_1Test { - private static CloseableHttpClient ourClient; - private static String ourConditionalUrl; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static IdType ourId; - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(UpdateDstu2_1Test.class); - private static int ourPort; - private static Server ourServer; - - @BeforeEach - public void before() { - ourConditionalUrl = null; - ourId = null; - } - - @Test - public void testUpdateConditional() throws Exception { - - Patient patient = new Patient(); - patient.setId("001"); - patient.addIdentifier().setValue("002"); - - HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?_id=001"); - httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); - - CloseableHttpResponse status = ourClient.execute(httpPost); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info("Response was:\n{}", responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertEquals("Patient?_id=001",ourConditionalUrl); - assertEquals(null, ourId); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - @Test - public void testUpdateMissingIdInBody() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier().setValue("002"); - - HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/001"); - httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); - - HttpResponse status = ourClient.execute(httpPost); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(400, status.getStatusLine().getStatusCode()); - - OperationOutcome oo = ourCtx.newXmlParser().parseResource(OperationOutcome.class, responseContent); - assertEquals(Msg.code(419) + "Can not update resource, resource body must contain an ID element for update (PUT) operation", oo.getIssue().get(0).getDiagnostics()); - } - - @Test - public void testUpdateNormal() throws Exception { - - Patient patient = new Patient(); - patient.setId("001"); - patient.addIdentifier().setValue("002"); - - HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/001"); - httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); - - CloseableHttpResponse status = ourClient.execute(httpPost); - try { - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - ourLog.info("Response was:\n{}", responseContent); - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertNull(ourConditionalUrl); - assertEquals("Patient/001", ourId.getValue()); - } finally { - IOUtils.closeQuietly(status.getEntity().getContent()); - } - - } - - @Test - public void testUpdateWrongIdInBody() throws Exception { - - Patient patient = new Patient(); - patient.setId("Patient/3/_history/4"); - patient.addIdentifier().setValue("002"); - - HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/1/_history/2"); - httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); - - HttpResponse status = ourClient.execute(httpPost); - - String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - - ourLog.info("Response was:\n{}", responseContent); - - assertEquals(400, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("Resource body ID of "3" does not match")); - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(new PatientProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class PatientProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Update() - public MethodOutcome updatePatient(@IdParam IdType theId, @ResourceParam Patient thePatient, @ConditionalUrlParam String theConditionalUrl) { - ourId = theId; - ourConditionalUrl = theConditionalUrl; - IdType id = theId != null ? theId.withVersion(thePatient.getIdentifier().get(0).getValue()) : new IdType("Patient/1"); - OperationOutcome oo = new OperationOutcome(); - oo.addIssue().setDiagnostics("OODETAILS"); - if (id.getValueAsString().contains("CREATE")) { - return new MethodOutcome(id, oo, true); - } - - return new MethodOutcome(id, oo); - } - - } -} diff --git a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu2_1Test.java b/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu2_1Test.java deleted file mode 100644 index 9f928939725..00000000000 --- a/hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu2_1Test.java +++ /dev/null @@ -1,327 +0,0 @@ -package ca.uhn.fhir.rest.server; - -import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.rest.annotation.IdParam; -import ca.uhn.fhir.rest.annotation.ResourceParam; -import ca.uhn.fhir.rest.annotation.Validate; -import ca.uhn.fhir.rest.api.Constants; -import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.rest.api.ValidationModeEnum; -import ca.uhn.fhir.test.utilities.JettyUtil; -import ca.uhn.fhir.util.TestUtil; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -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.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu2016may.model.CodeType; -import org.hl7.fhir.dstu2016may.model.IdType; -import org.hl7.fhir.dstu2016may.model.OperationOutcome; -import org.hl7.fhir.dstu2016may.model.Organization; -import org.hl7.fhir.dstu2016may.model.Parameters; -import org.hl7.fhir.dstu2016may.model.Patient; -import org.hl7.fhir.dstu2016may.model.StringType; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.stringContainsInOrder; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class ValidateDstu2_1Test { - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ValidateDstu2_1Test.class); - public static Patient ourLastPatient; - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2_1(); - private static EncodingEnum ourLastEncoding; - private static IdType ourLastId; - private static ValidationModeEnum ourLastMode; - private static String ourLastProfile; - private static String ourLastResourceBody; - private static OperationOutcome ourOutcomeToReturn; - private static int ourPort; - - private static Server ourServer; - - @BeforeEach() - public void before() { - ourLastResourceBody = null; - ourLastEncoding = null; - ourOutcomeToReturn = null; - ourLastMode = null; - ourLastProfile = null; - } - - @Test - public void testValidate() throws Exception { - - Patient patient = new Patient(); - patient.addIdentifier().setValue("001"); - patient.addIdentifier().setValue("002"); - - Parameters params = new Parameters(); - params.addParameter().setName("resource").setResource(patient); - - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); - httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); - - HttpResponse status = ourClient.execute(httpPost); - String resp = IOUtils.toString(status.getEntity().getContent()); - IOUtils.closeQuietly(status.getEntity().getContent()); - - assertEquals(200, status.getStatusLine().getStatusCode()); - - assertThat(resp, stringContainsInOrder(" getResourceType() { - return Organization.class; - } - - @Validate() - public MethodOutcome validate(@ResourceParam String theResourceBody, @ResourceParam EncodingEnum theEncoding) { - ourLastResourceBody = theResourceBody; - ourLastEncoding = theEncoding; - - return new MethodOutcome(new IdType("001")); - } - - } - - public static class PatientProvider implements IResourceProvider { - - @Override - public Class getResourceType() { - return Patient.class; - } - - @Validate() - public MethodOutcome validatePatient(@ResourceParam Patient thePatient, @IdParam(optional = true) IdType theId, @Validate.Mode ValidationModeEnum theMode, @Validate.Profile String theProfile) { - - ourLastPatient = thePatient; - ourLastId = theId; - IdType id; - if (thePatient != null) { - id = new IdType(thePatient.getIdentifier().get(0).getValue()); - if (thePatient.getIdElement().isEmpty() == false) { - id = thePatient.getIdElement(); - } - } else { - id = new IdType("1"); - } - ourLastMode = theMode; - ourLastProfile = theProfile; - - MethodOutcome outcome = new MethodOutcome(id.withVersion("002")); - outcome.setOperationOutcome(ourOutcomeToReturn); - return outcome; - } - - } - - @AfterAll - public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); - TestUtil.randomizeLocaleAndTimezone(); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider, new OrganizationProvider()); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - -} diff --git a/hapi-fhir-structures-dstu2/pom.xml b/hapi-fhir-structures-dstu2/pom.xml index 94b617d3ad7..be3795ef8ba 100644 --- a/hapi-fhir-structures-dstu2/pom.xml +++ b/hapi-fhir-structures-dstu2/pom.xml @@ -4,7 +4,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -49,8 +49,8 @@
    - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api provided @@ -62,36 +62,6 @@ xmlunit-core test
    - - org.eclipse.jetty - jetty-servlets - test - - - org.eclipse.jetty - jetty-server - test - - - org.eclipse.jetty - jetty-servlet - test - - - org.eclipse.jetty - jetty-util - test - - - org.eclipse.jetty - jetty-webapp - test - - - org.eclipse.jetty - jetty-http - test - ch.qos.logback logback-classic @@ -112,18 +82,18 @@ - com.helger - ph-schematron + com.helger.schematron + ph-schematron-api test - javax.activation - javax.activation-api + com.helger.schematron + ph-schematron-xslt test - javax.xml.bind - jaxb-api + jakarta.activation + jakarta.activation-api test @@ -372,7 +342,7 @@ --> - javax.servlet*;resolution:=optional, + jakarta.servlet*;resolution:=optional, * diff --git a/hapi-fhir-structures-dstu2/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/ServerConformanceProvider.java b/hapi-fhir-structures-dstu2/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/ServerConformanceProvider.java index bedc07b6338..413c733a15d 100644 --- a/hapi-fhir-structures-dstu2/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/ServerConformanceProvider.java +++ b/hapi-fhir-structures-dstu2/src/main/java/ca/uhn/fhir/rest/server/provider/dstu2/ServerConformanceProvider.java @@ -45,14 +45,14 @@ import ca.uhn.fhir.rest.server.method.OperationMethodBinding.ReturnType; import ca.uhn.fhir.rest.server.*; import ca.uhn.fhir.rest.server.method.*; import ca.uhn.fhir.rest.server.util.BaseServerCapabilityStatementProvider; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IPrimitiveType; import java.util.Map.Entry; import java.util.*; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorDstu2Test.java index e809ef4a6bc..aab91a5c8c4 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorDstu2Test.java @@ -88,7 +88,7 @@ public class DefaultThymeleafNarrativeGeneratorDstu2Test { String parse = "\n" + " \n" + " \n" + - " \n" + + " \n" + " \n" + " \n" + " \n" + diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/apache/ApacheClientIntegrationTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/apache/ApacheClientIntegrationTest.java index b4a6be35be7..24f1cbd4f44 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/apache/ApacheClientIntegrationTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/client/apache/ApacheClientIntegrationTest.java @@ -5,21 +5,19 @@ import ca.uhn.fhir.model.dstu2.resource.Bundle; import ca.uhn.fhir.model.dstu2.resource.Patient; import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.rest.client.api.IGenericClient; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.StringParam; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; -import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.interceptor.VerboseLoggingInterceptor; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -28,12 +26,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class ApacheClientIntegrationTest { - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static String ourLastMethod; private static StringParam ourLastName; - private static int ourPort; - private static Server ourServer; - private static String ourBase; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .registerInterceptor(new VerboseLoggingInterceptor()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -43,11 +49,8 @@ public class ApacheClientIntegrationTest { @Test - public void testSearchWithParam() throws Exception { - - IGenericClient client = ourCtx.newRestfulGenericClient(ourBase); - - Bundle response = client.search().forResource(Patient.class).where(Patient.NAME.matches().value("FOO")).returnBundle(Bundle.class).execute(); + public void testSearchWithParam() { + Bundle response = ourServer.getFhirClient().search().forResource(Patient.class).where(Patient.NAME.matches().value("FOO")).returnBundle(Bundle.class).execute(); assertEquals("search", ourLastMethod); assertEquals("FOO", ourLastName.getValue()); assertEquals(1, response.getEntry().size()); @@ -56,29 +59,9 @@ public class ApacheClientIntegrationTest { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.registerInterceptor(new VerboseLoggingInterceptor()); - - servlet.setResourceProviders(new DummyPatientResourceProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - ourBase = "http://localhost:" + ourPort; - } - public static class DummyPatientResourceProvider implements IResourceProvider { //@formatter:off @@ -87,7 +70,7 @@ public class ApacheClientIntegrationTest { ourLastMethod = "search"; ourLastName = theName; - List retVal = new ArrayList(); + List retVal = new ArrayList<>(); Patient patient = new Patient(); patient.setId("123"); patient.addName().addGiven("GIVEN"); diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryDstu2Test.java index 4724e1c3e55..f96792ca743 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryDstu2Test.java @@ -13,7 +13,9 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.config.RequestConfig; @@ -27,12 +29,13 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -52,12 +55,18 @@ import static org.junit.jupiter.api.Assertions.assertNull; public class BinaryDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BinaryDstu2Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static Binary ourLast; - private static int ourPort; - private static Server ourServer; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new ResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -66,7 +75,7 @@ public class BinaryDstu2Test { @Test public void testReadWithExplicitTypeXml() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary/foo?_format=xml"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Binary/foo?_format=xml"); try (CloseableHttpResponse response = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); IOUtils.closeQuietly(response.getEntity().getContent()); @@ -84,7 +93,7 @@ public class BinaryDstu2Test { @Test public void testReadWithExplicitTypeJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary/foo?_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Binary/foo?_format=json"); try (CloseableHttpResponse response = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); IOUtils.closeQuietly(response.getEntity().getContent()); @@ -103,7 +112,7 @@ public class BinaryDstu2Test { // posts Binary directly @Test public void testPostBinary() throws Exception { - HttpPost http = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost http = new HttpPost(ourServer.getBaseUrl() + "/Binary"); http.setEntity(new ByteArrayEntity(new byte[]{1, 2, 3, 4}, ContentType.create("foo/bar", "UTF-8"))); try (CloseableHttpResponse response = ourClient.execute(http)) { @@ -122,7 +131,7 @@ public class BinaryDstu2Test { res.setContentType("text/plain"); String stringContent = ourCtx.newJsonParser().encodeResourceToString(res); - HttpPost http = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost http = new HttpPost(ourServer.getBaseUrl() + "/Binary"); http.setEntity(new StringEntity(stringContent, ContentType.create(Constants.CT_FHIR_JSON, "UTF-8"))); try (CloseableHttpResponse response = ourClient.execute(http)) { @@ -134,14 +143,14 @@ public class BinaryDstu2Test { @Test public void testBinaryReadAcceptMissing() throws Exception { - HttpGet http = new HttpGet("http://localhost:" + ourPort + "/Binary/foo"); + HttpGet http = new HttpGet(ourServer.getBaseUrl() + "/Binary/foo"); binaryRead(http); } @Test public void testBinaryReadAcceptBrowser() throws Exception { - HttpGet http = new HttpGet("http://localhost:" + ourPort + "/Binary/foo"); + HttpGet http = new HttpGet(ourServer.getBaseUrl() + "/Binary/foo"); http.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"); http.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); @@ -161,7 +170,7 @@ public class BinaryDstu2Test { @Test public void testBinaryReadAcceptFhirJson() throws Exception { - HttpGet http = new HttpGet("http://localhost:" + ourPort + "/Binary/foo"); + HttpGet http = new HttpGet(ourServer.getBaseUrl() + "/Binary/foo"); http.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"); http.addHeader("Accept", Constants.CT_FHIR_JSON); @@ -177,7 +186,7 @@ public class BinaryDstu2Test { @Test public void testSearchJson() throws Exception { - HttpGet http = new HttpGet("http://localhost:" + ourPort + "/Binary?_pretty=true&_format=json"); + HttpGet http = new HttpGet(ourServer.getBaseUrl() + "/Binary?_pretty=true&_format=json"); try (CloseableHttpResponse response = ourClient.execute(http)) { String responseContent = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(response.getEntity().getContent()); @@ -196,7 +205,7 @@ public class BinaryDstu2Test { @Test public void testSearchXml() throws Exception { - HttpGet http = new HttpGet("http://localhost:" + ourPort + "/Binary?_pretty=true"); + HttpGet http = new HttpGet(ourServer.getBaseUrl() + "/Binary?_pretty=true"); try (CloseableHttpResponse response = ourClient.execute(http)) { String responseContent = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(response.getEntity().getContent()); @@ -247,38 +256,7 @@ public class BinaryDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ResourceProvider binaryProvider = new ResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(binaryProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - - int timeout = 60; - RequestConfig config = RequestConfig.custom() - .setConnectTimeout(timeout * 1000) - .setConnectionRequestTimeout(timeout * 1000) - .setSocketTimeout(timeout * 1000).build(); - - builder.setConnectionManager(connectionManager); - ourClient = builder.setDefaultRequestConfig(config).build(); - - } } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseTest.java index d0608fb2839..dd6bb801858 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseTest.java @@ -8,7 +8,9 @@ import ca.uhn.fhir.model.dstu2.valueset.BundleTypeEnum; import ca.uhn.fhir.narrative.DefaultThymeleafNarrativeGenerator; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -17,11 +19,12 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -34,16 +37,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; */ public class BundleTypeInResponseTest { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BundleTypeInResponseTest.class); - private static int ourPort; - private static Server ourServer; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -60,35 +69,9 @@ public class BundleTypeInResponseTest { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.getFhirContext().setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator()); - servlet.setResourceProviders(patientProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Search diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/CompartmentDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/CompartmentDstu2Test.java index 96d6cc85f09..1e07325b03c 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/CompartmentDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/CompartmentDstu2Test.java @@ -10,7 +10,9 @@ import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -19,12 +21,13 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -39,15 +42,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * Created by dsotnikov on 2/25/2014. */ public class CompartmentDstu2Test { - private static CloseableHttpClient ourClient; - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CompartmentDstu2Test.class); - private static int ourPort; - private static Server ourServer; private static String ourLastMethod; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static IdDt ourLastId; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new TempPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); + @AfterAll public static void afterClassClearContext() { TestUtil.randomizeLocaleAndTimezone(); @@ -63,9 +72,7 @@ public class CompartmentDstu2Test { @Test public void testReadFirst() throws Exception { - init(new TempPatientResourceProvider()); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -78,9 +85,7 @@ public class CompartmentDstu2Test { @Test public void testCompartmentSecond() throws Exception { - init(new TempPatientResourceProvider()); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/Encounter"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/Encounter"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -94,9 +99,7 @@ public class CompartmentDstu2Test { @Test public void testCompartmentSecond2() throws Exception { - init(new TempPatientResourceProvider()); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/Observation"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/Observation"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -108,33 +111,6 @@ public class CompartmentDstu2Test { assertThat(responseContent, containsString(" getResourceType() { @@ -178,4 +154,5 @@ public class CompartmentDstu2Test { } + } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/CreateConditionalTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/CreateConditionalTest.java index 60e487dbf19..96be8d7097c 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/CreateConditionalTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/CreateConditionalTest.java @@ -12,8 +12,11 @@ import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -25,12 +28,13 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -40,21 +44,24 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Created by dsotnikov on 2/25/2014. - */ public class CreateConditionalTest { - private static CloseableHttpClient ourClient; - - private static FhirContext ourCtx = FhirContext.forDstu2(); + + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static String ourLastConditionalUrl; private static IdDt ourLastId; private static IdDt ourLastIdParam; private static boolean ourLastRequestWasSearch; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CreateConditionalTest.class); - private static int ourPort; - private static Server ourServer; - + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -72,7 +79,7 @@ public class CreateConditionalTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?identifier=system%7C001"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -84,8 +91,8 @@ public class CreateConditionalTest { ourLog.info("Response was:\n{}", responseContent); assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); assertNull(ourLastId.getValue()); assertNull(ourLastIdParam); @@ -99,7 +106,7 @@ public class CreateConditionalTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient?_format=true&_pretty=true"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient?_format=true&_pretty=true"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -110,8 +117,8 @@ public class CreateConditionalTest { ourLog.info("Response was:\n{}", responseContent); assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); assertEquals(null, ourLastId.toUnqualified().getValue()); assertEquals(null, ourLastIdParam); @@ -125,7 +132,7 @@ public class CreateConditionalTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_pretty=true"); HttpResponse status = ourClient.execute(httpGet); @@ -144,33 +151,10 @@ public class CreateConditionalTest { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Create() diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/DeleteDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/DeleteDstu2Test.java index 13c9a918b6f..20104a2fa79 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/DeleteDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/DeleteDstu2Test.java @@ -8,8 +8,11 @@ import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; import ca.uhn.fhir.rest.annotation.Delete; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; @@ -17,12 +20,13 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -30,14 +34,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; public class DeleteDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static boolean ourInvoked; private static String ourLastConditionalUrl; private static IdDt ourLastIdParam; - private static int ourPort; - private static Server ourServer; - + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { @@ -53,7 +64,7 @@ public class DeleteDstu2Test { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpDelete httpPost = new HttpDelete("http://localhost:" + ourPort + "/Patient?identifier=system%7C001"); + HttpDelete httpPost = new HttpDelete(ourServer.getBaseUrl() + "/Patient?identifier=system%7C001"); HttpResponse status = ourClient.execute(httpPost); @@ -68,7 +79,7 @@ public class DeleteDstu2Test { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpDelete httpPost = new HttpDelete("http://localhost:" + ourPort + "/Patient/2"); + HttpDelete httpPost = new HttpDelete(ourServer.getBaseUrl() + "/Patient/2"); HttpResponse status = ourClient.execute(httpPost); @@ -82,33 +93,10 @@ public class DeleteDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Delete() diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ETagServerTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ETagServerTest.java index 73dccb78629..7e6188e0eec 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ETagServerTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ETagServerTest.java @@ -15,7 +15,8 @@ import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.server.exceptions.PreconditionFailedException; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.Header; @@ -25,35 +26,33 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.io.IOException; import java.util.Date; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; public class ETagServerTest { - private static CloseableHttpClient ourClient; - private static PoolingHttpClientConnectionManager ourConnectionManager; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static IdDt ourLastId; private static Date ourLastModifiedDate; - private static int ourPort; - private static Server ourServer; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach @@ -65,7 +64,7 @@ public class ETagServerTest { public void testAutomaticNotModified() throws Exception { ourLastModifiedDate = new InstantDt("2012-11-25T02:34:45.2222Z").getValue(); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/2"); httpGet.addHeader(Constants.HEADER_IF_NONE_MATCH, "\"222\""); HttpResponse status = ourClient.execute(httpGet); try { @@ -82,7 +81,7 @@ public class ETagServerTest { public void testETagHeader() throws Exception { ourLastModifiedDate = new InstantDt("2012-11-25T02:34:45.2222Z").getValue(); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/_history/3"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/2/_history/3"); HttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -104,7 +103,7 @@ public class ETagServerTest { public void testLastModifiedHeader() throws Exception { ourLastModifiedDate = new InstantDt("2012-11-25T02:34:45.222Z").getValue(); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/_history/3"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/2/_history/3"); HttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -132,7 +131,7 @@ public class ETagServerTest { String resBody = ourCtx.newXmlParser().encodeResourceToString(p); HttpPut http; - http = new HttpPut("http://localhost:" + ourPort + "/Patient/2"); + http = new HttpPut(ourServer.getBaseUrl() + "/Patient/2"); http.setEntity(new StringEntity(resBody, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); http.addHeader(Constants.HEADER_IF_MATCH, "\"221\""); CloseableHttpResponse status = ourClient.execute(http); @@ -154,7 +153,7 @@ public class ETagServerTest { String resBody = ourCtx.newXmlParser().encodeResourceToString(p); HttpPut http; - http = new HttpPut("http://localhost:" + ourPort + "/Patient/2"); + http = new HttpPut(ourServer.getBaseUrl() + "/Patient/2"); http.setEntity(new StringEntity(resBody, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); http.addHeader(Constants.HEADER_IF_MATCH, "\"222\""); CloseableHttpResponse status = ourClient.execute(http); @@ -176,7 +175,7 @@ public class ETagServerTest { String resBody = ourCtx.newXmlParser().encodeResourceToString(p); HttpPut http; - http = new HttpPut("http://localhost:" + ourPort + "/Patient/2"); + http = new HttpPut(ourServer.getBaseUrl() + "/Patient/2"); http.setEntity(new StringEntity(resBody, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(http); try { @@ -191,34 +190,9 @@ public class ETagServerTest { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(FhirContext.forDstu2()); - ourCtx = servlet.getFhirContext(); - servlet.setResourceProviders(patientProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - ourConnectionManager = new PoolingHttpClientConnectionManager(50000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(ourConnectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Read(version = true) diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeAndRevincludeParameterTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeAndRevincludeParameterTest.java index 9627fcc509f..cd3aa5a55ad 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeAndRevincludeParameterTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeAndRevincludeParameterTest.java @@ -7,7 +7,10 @@ import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.model.dstu2.resource.Patient; import ca.uhn.fhir.rest.annotation.IncludeParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -16,12 +19,13 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -38,13 +42,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; */ public class IncludeAndRevincludeParameterTest { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static Set ourIncludes; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(IncludeAndRevincludeParameterTest.class); - private static int ourPort; private static Set ourReverseIncludes; - private static Server ourServer; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -55,7 +66,7 @@ public class IncludeAndRevincludeParameterTest { @Test public void testNoIncludes() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=normalInclude"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=normalInclude"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -67,7 +78,7 @@ public class IncludeAndRevincludeParameterTest { @Test public void testWithBoth() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=normalInclude&_include=A.a&_include=B.b&_revinclude=C.c&_revinclude=D.d"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=normalInclude&_include=A.a&_include=B.b&_revinclude=C.c&_revinclude=D.d"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -82,33 +93,9 @@ public class IncludeAndRevincludeParameterTest { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - - @BeforeAll - public static void beforeClass() throws Exception { - - ourCtx = FhirContext.forDstu2(); - ourServer = new Server(ourPort); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(new DummyPatientResourceProvider()); - servlet.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - + public static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeDstu2Test.java index 03f226af1f9..cf19e290f8c 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeDstu2Test.java @@ -21,7 +21,9 @@ import ca.uhn.fhir.rest.annotation.IncludeParam; import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.BundleUtil; import ca.uhn.fhir.util.ElementUtil; import ca.uhn.fhir.util.TestUtil; @@ -32,12 +34,13 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.Arrays; @@ -54,14 +57,23 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class IncludeDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(IncludeDstu2Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; - private static int ourPort; - private static Server ourServer; + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .registerProvider(new DummyDiagnosticReportResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .withServer(s->s.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testBadInclude() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo&_include=baz"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo&_include=baz"); HttpResponse status = ourClient.execute(httpGet); assertEquals(400, status.getStatusLine().getStatusCode()); } @@ -69,7 +81,7 @@ public class IncludeDstu2Test { @Test public void testIIncludedResourcesNonContained() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=normalInclude&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=normalInclude&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -96,7 +108,7 @@ public class IncludeDstu2Test { @Test public void testIIncludedResourcesNonContainedInDeclaredExtension() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=declaredExtInclude&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=declaredExtInclude&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -124,7 +136,7 @@ public class IncludeDstu2Test { @Test public void testIIncludedResourcesNonContainedInExtension() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=extInclude&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=extInclude&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -150,7 +162,7 @@ public class IncludeDstu2Test { @Test public void testIIncludedResourcesNonContainedInExtensionJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=extInclude&_pretty=true&_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=extInclude&_pretty=true&_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -177,7 +189,7 @@ public class IncludeDstu2Test { @Test @Disabled public void testMixedContainedAndNonContained() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?_query=stitchedInclude&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/DiagnosticReport?_query=stitchedInclude&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -191,7 +203,7 @@ public class IncludeDstu2Test { @Test public void testNoIncludes() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -207,7 +219,7 @@ public class IncludeDstu2Test { @Test public void testOneIncludeJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo&_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo&_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -227,7 +239,7 @@ public class IncludeDstu2Test { @Test public void testOneIncludeXml() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -247,7 +259,7 @@ public class IncludeDstu2Test { @Test public void testTwoInclude() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo&_include=bar&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo&_include=bar&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -451,34 +463,8 @@ public class IncludeDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - - ourCtx = FhirContext.forDstu2(); - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider, new DummyDiagnosticReportResourceProvider()); - servlet.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationDuplicateServerDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationDuplicateServerDstu2Test.java index caeac0d1e9b..c8534a9bdc4 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationDuplicateServerDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationDuplicateServerDstu2Test.java @@ -10,7 +10,9 @@ import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -19,29 +21,39 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; public class OperationDuplicateServerDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationDuplicateServerDstu2Test.class); - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .registerProvider(new OrganizationProvider()) + .registerProvider(new PlainProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testOperationsAreCollapsed() throws Exception { // Metadata { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/metadata?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/metadata?_pretty=true"); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -57,7 +69,7 @@ public class OperationDuplicateServerDstu2Test { // OperationDefinition { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/OperationDefinition/OrganizationPatient-ts-myoperation?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/OperationDefinition/OrganizationPatient-ts-myoperation?_pretty=true"); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -78,37 +90,9 @@ public class OperationDuplicateServerDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu2(); - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); - - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(new PatientProvider(), new OrganizationProvider()); - servlet.setPlainProviders(new PlainProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class BaseProvider { @Operation(name = "$myoperation", idempotent = true) diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu2Test.java index 388db6332fe..36236934379 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu2Test.java @@ -21,9 +21,8 @@ import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.IBundleProvider; -import ca.uhn.fhir.rest.client.api.IGenericClient; -import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -32,21 +31,14 @@ import org.apache.http.client.methods.HttpGet; 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.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.blankOrNullString; @@ -59,8 +51,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; public class OperationServerDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static IdDt ourLastId; private static String ourLastMethod; @@ -70,9 +61,17 @@ public class OperationServerDstu2Test { private static MoneyDt ourLastParamMoney1; private static UnsignedIntDt ourLastParamUnsignedInt1; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationServerDstu2Test.class); - private static int ourPort; - private static Server ourServer; - private IGenericClient myFhirClient; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .registerProvider(new PlainProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -83,23 +82,17 @@ public class OperationServerDstu2Test { ourLastParamMoney1 = null; ourLastId = null; ourLastMethod = ""; - - myFhirClient = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); } @Test public void testConformance() throws Exception { - LoggingInterceptor loggingInterceptor = new LoggingInterceptor(); - loggingInterceptor.setLogResponseBody(true); - myFhirClient.registerInterceptor(loggingInterceptor); - - Conformance p = myFhirClient.fetchConformance().ofType(Conformance.class).prettyPrint().execute(); + Conformance p = ourServer.getFhirClient().fetchConformance().ofType(Conformance.class).prettyPrint().execute(); List ops = p.getRest().get(0).getOperation(); assertThat(ops.size(), greaterThan(1)); assertNull(ops.get(0).getDefinition().getReference().getBaseUrl()); assertThat(ops.get(0).getDefinition().getReference().getValue(), startsWith("OperationDefinition/")); - OperationDefinition def = myFhirClient.read().resource(OperationDefinition.class).withId(ops.get(0).getDefinition().getReference()).execute(); + OperationDefinition def = ourServer.getFhirClient().read().resource(OperationDefinition.class).withId(ops.get(0).getDefinition().getReference()).execute(); assertThat(def.getCode(), not(blankOrNullString())); List opNames = toOpNames(ops); @@ -113,7 +106,7 @@ public class OperationServerDstu2Test { */ @Test public void testOperationDefinition() { - OperationDefinition def = myFhirClient.read().resource(OperationDefinition.class).withId("OperationDefinition/Patient-t-OP_TYPE").execute(); + OperationDefinition def = ourServer.getFhirClient().read().resource(OperationDefinition.class).withId("OperationDefinition/Patient-t-OP_TYPE").execute(); ourLog.debug(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(def)); @@ -158,7 +151,7 @@ public class OperationServerDstu2Test { public void testInstanceEverythingGet() throws Exception { // Try with a GET - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$everything"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/$everything"); CloseableHttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -173,7 +166,7 @@ public class OperationServerDstu2Test { @Test public void testInstanceEverythingHapiClient() throws Exception { - Parameters p = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort).operation().onInstance(new IdDt("Patient/123")).named("$everything").withParameters(new Parameters()).execute(); + Parameters p = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl()).operation().onInstance(new IdDt("Patient/123")).named("$everything").withParameters(new Parameters()).execute(); Bundle b = (Bundle) p.getParameterFirstRep().getResource(); assertEquals("instance $everything", ourLastMethod); @@ -186,7 +179,7 @@ public class OperationServerDstu2Test { String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(new Parameters()); // Try with a POST - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$everything"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$everything"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -202,7 +195,7 @@ public class OperationServerDstu2Test { @Test public void testOperationCantUseGetIfItIsntIdempotent() throws Exception { - HttpGet httpPost = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE"); + HttpGet httpPost = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); HttpResponse status = ourClient.execute(httpPost); assertEquals(Constants.STATUS_HTTP_405_METHOD_NOT_ALLOWED, status.getStatusLine().getStatusCode()); @@ -219,7 +212,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM1").setValue(new IntegerDt(123)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); CloseableHttpResponse status = ourClient.execute(httpPost); try { @@ -238,7 +231,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -258,7 +251,7 @@ public class OperationServerDstu2Test { * Against type should fail */ - httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_INSTANCE"); + httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); status = ourClient.execute(httpPost); @@ -276,7 +269,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE_OR_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE_OR_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -301,7 +294,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_INSTANCE_OR_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_INSTANCE_OR_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); CloseableHttpResponse status = ourClient.execute(httpPost); @@ -325,7 +318,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/$OP_SERVER"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/$OP_SERVER"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -348,7 +341,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -371,7 +364,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_TYPE_RET_BUNDLE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_TYPE_RET_BUNDLE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -389,7 +382,7 @@ public class OperationServerDstu2Test { @Test public void testOperationWithBundleProviderResponse() throws Exception { - HttpGet httpPost = new HttpGet("http://localhost:" + ourPort + "/$OP_INSTANCE_BUNDLE_PROVIDER?_pretty=true"); + HttpGet httpPost = new HttpGet(ourServer.getBaseUrl() + "/$OP_INSTANCE_BUNDLE_PROVIDER?_pretty=true"); HttpResponse status = ourClient.execute(httpPost); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -402,7 +395,7 @@ public class OperationServerDstu2Test { @Test public void testOperationWithGetUsingParams() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$OP_TYPE?PARAM1=PARAM1val"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$OP_TYPE?PARAM1=PARAM1val"); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -419,7 +412,7 @@ public class OperationServerDstu2Test { @Test public void testOperationWithGetUsingParamsFailsWithNonPrimitive() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$OP_TYPE?PARAM1=PARAM1val&PARAM2=foo"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$OP_TYPE?PARAM1=PARAM1val&PARAM2=foo"); HttpResponse status = ourClient.execute(httpGet); assertEquals(405, status.getStatusLine().getStatusCode()); @@ -438,7 +431,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM3").setValue(new StringDt("PARAM3val2")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/$OP_SERVER_LIST_PARAM"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/$OP_SERVER_LIST_PARAM"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -463,7 +456,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM1").setValue(new IntegerDt("123")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_PROFILE_DT"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_PROFILE_DT"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -484,7 +477,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM1").setValue(money); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_PROFILE_DT2"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_PROFILE_DT2"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -499,7 +492,7 @@ public class OperationServerDstu2Test { @Test public void testOperationWithProfileDatatypeUrl() throws Exception { - HttpGet httpPost = new HttpGet("http://localhost:" + ourPort + "/Patient/$OP_PROFILE_DT?PARAM1=123"); + HttpGet httpPost = new HttpGet(ourServer.getBaseUrl() + "/Patient/$OP_PROFILE_DT?PARAM1=123"); HttpResponse status = ourClient.execute(httpPost); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -516,7 +509,7 @@ public class OperationServerDstu2Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -532,7 +525,7 @@ public class OperationServerDstu2Test { @Test public void testReadWithOperations() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123"); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -543,38 +536,9 @@ public class OperationServerDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu2(); - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); - - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(new PatientProvider()); - servlet.setPlainProviders(new PlainProvider()); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu2Test.java index 441964a2290..34c99f7cfec 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu2Test.java @@ -10,6 +10,7 @@ import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.param.StringAndListParam; import ca.uhn.fhir.rest.param.StringOrListParam; @@ -20,7 +21,9 @@ import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.rest.param.TokenParamModifier; import ca.uhn.fhir.rest.server.provider.dstu2.ServerConformanceProvider; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; import org.apache.commons.io.IOUtils; @@ -33,16 +36,18 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.servlet.ServletConfig; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.extension.RegisterExtension; + import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; @@ -55,15 +60,22 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class OperationServerWithSearchParamTypesDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static String ourLastMethod; private static List ourLastParamValStr; private static List ourLastParamValTok; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationServerWithSearchParamTypesDstu2Test.class); - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -97,7 +109,7 @@ public class OperationServerWithSearchParamTypesDstu2Test { p.addParameter().setName("valtok").setValue(new StringDt("VALTOK2A|VALTOK2B")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$andlist"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$andlist"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -123,7 +135,7 @@ public class OperationServerWithSearchParamTypesDstu2Test { @Test public void testAndListWithUrl() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$andlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$andlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); HttpResponse status = ourClient.execute(httpGet); @@ -206,7 +218,7 @@ public class OperationServerWithSearchParamTypesDstu2Test { p.addParameter().setName("valtok").setValue(new StringDt("VALTOKA|VALTOKB")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$nonrepeating"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$nonrepeating"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -227,7 +239,7 @@ public class OperationServerWithSearchParamTypesDstu2Test { @Test public void testNonRepeatingWithUrl() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$nonrepeating?valstr=VALSTR&valtok=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$nonrepeating?valstr=VALSTR&valtok=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -247,7 +259,7 @@ public class OperationServerWithSearchParamTypesDstu2Test { @Test public void testNonRepeatingWithUrlQualified() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$nonrepeating?valstr:exact=VALSTR&valtok:not=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$nonrepeating?valstr:exact=VALSTR&valtok:not=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -276,7 +288,7 @@ public class OperationServerWithSearchParamTypesDstu2Test { p.addParameter().setName("valtok").setValue(new StringDt("VALTOK2A|VALTOK2B")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$orlist"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$orlist"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -302,7 +314,7 @@ public class OperationServerWithSearchParamTypesDstu2Test { @Test public void testOrListWithUrl() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$orlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$orlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); HttpResponse status = ourClient.execute(httpGet); @@ -328,35 +340,9 @@ public class OperationServerWithSearchParamTypesDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu2(); - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); - - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(new PatientProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Operation(name = "$andlist", idempotent = true) diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/PatientResourceProvider.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/PatientResourceProvider.java index 07079f0e3e2..e41f47492a1 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/PatientResourceProvider.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/PatientResourceProvider.java @@ -27,7 +27,7 @@ public class PatientResourceProvider implements IResourceProvider //@formatter:off @Search() public IBundleProvider search( - javax.servlet.http.HttpServletRequest theServletRequest, + jakarta.servlet.http.HttpServletRequest theServletRequest, @Description(shortDefinition="The resource identity") @OptionalParam(name="_id") diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ReadDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ReadDstu2Test.java index 300dacfa4d3..74fda07024c 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ReadDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ReadDstu2Test.java @@ -12,7 +12,9 @@ import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.DateUtils; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; @@ -23,12 +25,13 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -41,13 +44,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class ReadDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ReadDstu2Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static boolean ourInitializeProfileList; private static IdDt ourLastId; - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -65,7 +75,7 @@ public class ReadDstu2Test { // Fixture was last modified at 2012-01-01T12:12:12Z // thus it has changed before the later time of 2012-01-01T13:00:00Z // so we expect a 304 - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/2"); httpGet.addHeader(Constants.HEADER_IF_MODIFIED_SINCE, DateUtils.formatDate(new InstantDt("2012-01-01T13:00:00Z").getValue())); status = ourClient.execute(httpGet); try { @@ -77,7 +87,7 @@ public class ReadDstu2Test { // Fixture was last modified at 2012-01-01T12:12:12Z // thus it has changed at the same time of 2012-01-01T12:12:12Z // so we expect a 304 - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/2"); httpGet.addHeader(Constants.HEADER_IF_MODIFIED_SINCE, DateUtils.formatDate(new InstantDt("2012-01-01T12:12:12Z").getValue())); status = ourClient.execute(httpGet); try { @@ -89,7 +99,7 @@ public class ReadDstu2Test { // Fixture was last modified at 2012-01-01T12:12:12Z // thus it has changed after the earlier time of 2012-01-01T10:00:00Z // so we expect a 200 - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/2"); httpGet.addHeader(Constants.HEADER_IF_MODIFIED_SINCE, DateUtils.formatDate(new InstantDt("2012-01-01T10:00:00Z").getValue())); status = ourClient.execute(httpGet); try { @@ -107,7 +117,7 @@ public class ReadDstu2Test { public void testAddProfile() throws Exception { ourCtx.setAddProfileTagWhenEncoding(AddProfileTagEnum.ONLY_FOR_CUSTOM); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=xml"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123?_format=xml"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Constants.CHARSET_UTF8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -130,7 +140,7 @@ public class ReadDstu2Test { ourInitializeProfileList = true; ourCtx.setAddProfileTagWhenEncoding(AddProfileTagEnum.ONLY_FOR_CUSTOM); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123&_format=xml"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123&_format=xml"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Constants.CHARSET_UTF8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -150,7 +160,7 @@ public class ReadDstu2Test { public void testReadJson() throws Exception { ourCtx.setAddProfileTagWhenEncoding(AddProfileTagEnum.ONLY_FOR_CUSTOM); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123?_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Constants.CHARSET_UTF8); ourLog.info(responseContent); @@ -167,7 +177,7 @@ public class ReadDstu2Test { */ @Test public void testReadXml() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123&_format=xml"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123&_format=xml"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Constants.CHARSET_UTF8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -183,7 +193,7 @@ public class ReadDstu2Test { public void testVread() throws Exception { ourCtx.setAddProfileTagWhenEncoding(AddProfileTagEnum.ONLY_FOR_CUSTOM); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/_history/1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/_history/1"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Constants.CHARSET_UTF8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -234,33 +244,7 @@ public class ReadDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setFhirContext(ourCtx); - ourServlet.setResourceProviders(patientProvider); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeDstu2Test.java index 8e330e82ddc..8186316569b 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeDstu2Test.java @@ -11,8 +11,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu2Test.java index e8a575a9833..f9167179b46 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu2Test.java @@ -8,7 +8,9 @@ import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.TokenParam; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -17,13 +19,14 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -35,14 +38,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchCountParamDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchCountParamDstu2Test.class); - private static int ourPort; - private static Server ourServer; private static String ourLastMethod; private static Integer ourLastParam; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -51,23 +61,23 @@ public class SearchCountParamDstu2Test { @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_count=2"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_count=2"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); ourLog.info(responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals("search", ourLastMethod); - assertEquals(new Integer(2), ourLastParam); + assertEquals(Integer.valueOf(2), ourLastParam); assertThat(responseContent, stringContainsInOrder( "", "", - "", + "", "", "", "", - "", + "", "")); } finally { @@ -81,7 +91,7 @@ public class SearchCountParamDstu2Test { */ @Test public void testSearchWithNoCountParam() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithNoCountParam&_count=2"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithNoCountParam&_count=2"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -94,11 +104,11 @@ public class SearchCountParamDstu2Test { assertThat(responseContent, stringContainsInOrder( "", "", - "", + "", "", "", "", - "", + "", "")); //@formatter:on @@ -110,35 +120,9 @@ public class SearchCountParamDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchDstu2Test.java index d28dbf5505b..1235ae59f4d 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchDstu2Test.java @@ -22,7 +22,9 @@ import ca.uhn.fhir.rest.param.ParamPrefixEnum; import ca.uhn.fhir.rest.param.QuantityParam; import ca.uhn.fhir.rest.param.ReferenceParam; import ca.uhn.fhir.rest.param.StringParam; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; @@ -40,13 +42,14 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import javax.annotation.Nonnull; import java.nio.charset.Charset; @@ -66,17 +69,24 @@ import static org.junit.jupiter.api.Assertions.assertNull; public class SearchDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static DateAndListParam ourLastDateAndList; private static String ourLastMethod; private static QuantityParam ourLastQuantity; private static ReferenceParam ourLastRef; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchDstu2Test.class); - private static int ourPort; private static InstantDt ourReturnPublished; - private static Server ourServer; - private static RestfulServer ourServlet; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .registerProvider(new DummyPatientResourceNoIdProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -84,13 +94,13 @@ public class SearchDstu2Test { ourLastDateAndList = null; ourLastRef = null; ourLastQuantity = null; - ourServlet.setIgnoreServerParsedRequestParameters(true); + ourServer.getRestfulServer().setIgnoreServerParsedRequestParameters(true); } @Test public void testSearchWithInvalidPostUrl() throws Exception { // should end with _search - HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient?name=Central"); + HttpPost filePost = new HttpPost(ourServer.getBaseUrl() + "/Patient?name=Central"); // add parameters to the post method List parameters = new ArrayList(); @@ -110,7 +120,7 @@ public class SearchDstu2Test { @Test public void testEncodeConvertsReferencesToRelative() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithRef"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithRef"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -127,7 +137,7 @@ public class SearchDstu2Test { @Test public void testEncodeConvertsReferencesToRelativeJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithRef&_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithRef&_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -146,7 +156,7 @@ public class SearchDstu2Test { public void testResultBundleHasUpdateTime() throws Exception { ourReturnPublished = new InstantDt("2011-02-03T11:22:33Z"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithBundleProvider&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithBundleProvider&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -157,7 +167,7 @@ public class SearchDstu2Test { @Test public void testResultBundleHasUuid() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithRef"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithRef"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -169,7 +179,7 @@ public class SearchDstu2Test { @Test public void testSearchBlacklist01Failing() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchBlacklist01&ref.black1=value"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchBlacklist01&ref.black1=value"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -179,7 +189,7 @@ public class SearchDstu2Test { @Test public void testSearchBlacklist01Passing() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchBlacklist01&ref.white1=value"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchBlacklist01&ref.white1=value"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -190,7 +200,7 @@ public class SearchDstu2Test { @Test public void testSearchByPost() throws Exception { - HttpPost httpGet = new HttpPost("http://localhost:" + ourPort + "/Patient/_search"); + HttpPost httpGet = new HttpPost(ourServer.getBaseUrl() + "/Patient/_search"); StringEntity entity = new StringEntity("searchDateAndList=2001,2002&searchDateAndList=2003,2004", ContentType.APPLICATION_FORM_URLENCODED); httpGet.setEntity(entity); @@ -209,7 +219,7 @@ public class SearchDstu2Test { @Test public void testSearchMethodReturnsNull() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchReturnNull"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchReturnNull"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -221,7 +231,7 @@ public class SearchDstu2Test { @Test public void testSearchByPostWithBodyAndUrlParams() throws Exception { - HttpPost httpGet = new HttpPost("http://localhost:" + ourPort + "/Patient/_search?_format=json"); + HttpPost httpGet = new HttpPost(ourServer.getBaseUrl() + "/Patient/_search?_format=json"); StringEntity entity = new StringEntity("searchDateAndList=2001,2002&searchDateAndList=2003,2004", ContentType.APPLICATION_FORM_URLENCODED); httpGet.setEntity(entity); @@ -241,9 +251,9 @@ public class SearchDstu2Test { @Test public void testSearchByPostWithBodyAndUrlParamsNoManual() throws Exception { - ourServlet.setIgnoreServerParsedRequestParameters(false); + ourServer.getRestfulServer().setIgnoreServerParsedRequestParameters(false); - HttpPost httpGet = new HttpPost("http://localhost:" + ourPort + "/Patient/_search?_format=json"); + HttpPost httpGet = new HttpPost(ourServer.getBaseUrl() + "/Patient/_search?_format=json"); StringEntity entity = new StringEntity("searchDateAndList=2001,2002&searchDateAndList=2003,2004", ContentType.APPLICATION_FORM_URLENCODED); httpGet.setEntity(entity); @@ -263,7 +273,7 @@ public class SearchDstu2Test { @Test public void testSearchByPut() throws Exception { - HttpPut httpGet = new HttpPut("http://localhost:" + ourPort + "/Patient/_search"); + HttpPut httpGet = new HttpPut(ourServer.getBaseUrl() + "/Patient/_search"); StringEntity entity = new StringEntity("searchDateAndList=2001,2002&searchDateAndList=2003,2004", ContentType.APPLICATION_FORM_URLENCODED); httpGet.setEntity(entity); @@ -276,7 +286,7 @@ public class SearchDstu2Test { @Test public void testSearchDateAndList() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?searchDateAndList=2001,2002&searchDateAndList=2003,2004"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?searchDateAndList=2001,2002&searchDateAndList=2003,2004"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -296,7 +306,7 @@ public class SearchDstu2Test { public void testSearchPagesAllHaveCorrectBundleType() throws Exception { Bundle resp; { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?searchHugeResults=yes&_count=10&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?searchHugeResults=yes&_count=10&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -341,7 +351,7 @@ public class SearchDstu2Test { */ @Test public void testSearchQuantityMissingTrue() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?quantity:missing=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?quantity:missing=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -355,7 +365,7 @@ public class SearchDstu2Test { */ @Test public void testSearchQuantityValue() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?quantity=gt100"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?quantity=gt100"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -368,7 +378,7 @@ public class SearchDstu2Test { @Test public void testSearchReferenceParams01() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchNoList&ref=123"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchNoList&ref=123"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -381,7 +391,7 @@ public class SearchDstu2Test { @Test public void testSearchReferenceParams02() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchNoList&ref=Patient/123"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchNoList&ref=Patient/123"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -394,7 +404,7 @@ public class SearchDstu2Test { @Test public void testSearchReferenceParams03() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchNoList&ref:Patient=Patient/123"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchNoList&ref:Patient=Patient/123"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -407,7 +417,7 @@ public class SearchDstu2Test { @Test public void testSearchReferenceParams04() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchNoList&ref:Patient=123"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchNoList&ref:Patient=123"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -423,7 +433,7 @@ public class SearchDstu2Test { */ @Test public void testSearchByIdExact() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id:exact=aaa&reference=value"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_id:exact=aaa&reference=value"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -435,7 +445,7 @@ public class SearchDstu2Test { @Test public void testSearchByQualifiedIdQualifiedString() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id:exact=aaa&stringParam:exact=value"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_id:exact=aaa&stringParam:exact=value"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -447,7 +457,7 @@ public class SearchDstu2Test { @Test public void testSearchByQualifiedString() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=aaa&stringParam:exact=value"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_id=aaa&stringParam:exact=value"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -459,7 +469,7 @@ public class SearchDstu2Test { @Test public void testSearchByQualifiedIdString() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id:exact=aaa&stringParam=value"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_id:exact=aaa&stringParam=value"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -471,7 +481,7 @@ public class SearchDstu2Test { @Test public void testSearchByIdString() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=aaa&stringParam=value"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_id=aaa&stringParam=value"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -484,7 +494,7 @@ public class SearchDstu2Test { @Test public void testSearchWhitelist01Failing() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWhitelist01&ref=value"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWhitelist01&ref=value"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -494,7 +504,7 @@ public class SearchDstu2Test { @Test public void testSearchWhitelist01Passing() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWhitelist01&ref.white1=value"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWhitelist01&ref.white1=value"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -505,36 +515,9 @@ public class SearchDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - DummyPatientResourceNoIdProvider patientResourceNoIdProviderProvider = new DummyPatientResourceNoIdProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - ourServlet.setResourceProviders(patientResourceNoIdProviderProvider, patientProvider); - - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceNoIdProvider implements IResourceProvider { @Override @@ -698,7 +681,7 @@ public class SearchDstu2Test { public Patient searchWithRef() { Patient patient = new Patient(); patient.setId("Patient/1/_history/1"); - patient.getManagingOrganization().setReference("http://localhost:" + ourPort + "/Organization/555/_history/666"); + patient.getManagingOrganization().setReference(ourServer.getBaseUrl() + "/Organization/555/_history/666"); return patient; } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchReturningProfiledResourceDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchReturningProfiledResourceDstu2Test.java index c04e524443f..52f0bb07be2 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchReturningProfiledResourceDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchReturningProfiledResourceDstu2Test.java @@ -1,6 +1,7 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.context.api.AddProfileTagEnum; import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.dstu2.resource.Bundle; @@ -14,7 +15,9 @@ import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.rest.server.interceptor.ResponseHighlighterInterceptor; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.validation.PatientProfileDstu2; import org.apache.commons.io.IOUtils; @@ -24,12 +27,15 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.Collections; @@ -43,16 +49,34 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchReturningProfiledResourceDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchReturningProfiledResourceDstu2Test.class); - private static int ourPort; - private static Server ourServer; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .registerInterceptor(new ResponseHighlighterInterceptor()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); + + @BeforeEach + public void before() { + ourCtx.setAddProfileTagWhenEncoding(AddProfileTagEnum.ONLY_FOR_CUSTOM); + } + + @AfterEach + public void after() { + ourCtx.setDefaultTypeForProfile("http://ahr.copa.inso.tuwien.ac.at/StructureDefinition/Patient", null); + } + + @Test public void testClientTypedRequest() throws Exception { - ourCtx = FhirContext.forDstu2(); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/"); Bundle bundle = client.search().forResource(PatientProfileDstu2.class).returnBundle(Bundle.class).execute(); assertEquals(PatientProfileDstu2.class, bundle.getEntry().get(0).getResource().getClass()); @@ -60,9 +84,8 @@ public class SearchReturningProfiledResourceDstu2Test { @Test public void testClientUntypedRequestWithHint() throws Exception { - ourCtx = FhirContext.forDstu2(); ourCtx.setDefaultTypeForProfile("http://ahr.copa.inso.tuwien.ac.at/StructureDefinition/Patient", PatientProfileDstu2.class); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/"); Bundle bundle = client.search().forResource(Patient.class).returnBundle(Bundle.class).execute(); assertEquals(PatientProfileDstu2.class, bundle.getEntry().get(0).getResource().getClass()); @@ -70,8 +93,7 @@ public class SearchReturningProfiledResourceDstu2Test { @Test public void testClientUntypedRequestWithoutHint() throws Exception { - ourCtx = FhirContext.forDstu2(); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/"); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl() + "/"); Bundle bundle = client.search().forResource(Patient.class).returnBundle(Bundle.class).execute(); assertEquals(Patient.class, bundle.getEntry().get(0).getResource().getClass()); @@ -79,7 +101,7 @@ public class SearchReturningProfiledResourceDstu2Test { @Test public void testProfilesGetAdded() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -93,7 +115,7 @@ public class SearchReturningProfiledResourceDstu2Test { @Test public void testProfilesGetAddedHtml() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=html"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=html"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -107,34 +129,9 @@ public class SearchReturningProfiledResourceDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.registerInterceptor(new ResponseHighlighterInterceptor()); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(new DummyPatientResourceProvider()); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithDstu2BundleTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithDstu2BundleTest.java index f609c3583a1..9a5b91e2228 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithDstu2BundleTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithDstu2BundleTest.java @@ -5,7 +5,10 @@ import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.dstu2.resource.Bundle; import ca.uhn.fhir.model.dstu2.resource.Patient; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -14,11 +17,12 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -28,15 +32,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchWithDstu2BundleTest { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithDstu2BundleTest.class); - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=xml&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=xml&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -52,7 +63,7 @@ public class SearchWithDstu2BundleTest { "", "" , "", - "", + "", "" , "" , "" , @@ -65,33 +76,9 @@ public class SearchWithDstu2BundleTest { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - /** * Created by dsotnikov on 2/25/2014. */ diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu2Test.java index 1cd0e34a250..8cc362ad2bd 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu2Test.java @@ -8,25 +8,19 @@ import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -34,12 +28,19 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchWithGenericListDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static String ourLastMethod; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithGenericListDstu2Test.class); - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -51,7 +52,7 @@ public class SearchWithGenericListDstu2Test { */ @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier=foo&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -59,42 +60,16 @@ public class SearchWithGenericListDstu2Test { assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals("searchByIdentifier", ourLastMethod); assertThat(responseContent, containsString("")); + assertThat(responseContent, containsString("")); } @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerConformanceProviderDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerConformanceProviderDstu2Test.java index 4e034ac93dc..2bb11ab7f97 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerConformanceProviderDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerConformanceProviderDstu2Test.java @@ -60,9 +60,9 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -731,7 +731,7 @@ public class ServerConformanceProviderDstu2Test { public static class MultiTypeEncounterProvider implements IResourceProvider { @Operation(name = "someOp") - public IBundleProvider everything(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdDt theId, + public IBundleProvider everything(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdDt theId, @OperationParam(name = "someOpParam1") DateDt theStart, @OperationParam(name = "someOpParam2") Encounter theEnd) { return null; } @@ -742,7 +742,7 @@ public class ServerConformanceProviderDstu2Test { } @Validate - public IBundleProvider validate(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdDt theId, @ResourceParam Encounter thePatient) { + public IBundleProvider validate(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdDt theId, @ResourceParam Encounter thePatient) { return null; } @@ -751,7 +751,7 @@ public class ServerConformanceProviderDstu2Test { public static class MultiTypePatientProvider implements IResourceProvider { @Operation(name = "someOp") - public IBundleProvider everything(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdDt theId, + public IBundleProvider everything(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdDt theId, @OperationParam(name = "someOpParam1") DateDt theStart, @OperationParam(name = "someOpParam2") Patient theEnd) { return null; } @@ -762,7 +762,7 @@ public class ServerConformanceProviderDstu2Test { } @Validate - public IBundleProvider validate(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdDt theId, @ResourceParam Patient thePatient) { + public IBundleProvider validate(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdDt theId, @ResourceParam Patient thePatient) { return null; } @@ -795,7 +795,7 @@ public class ServerConformanceProviderDstu2Test { public static class PlainProviderWithExtendedOperationOnNoType { @Operation(name = "plain", idempotent = true, returnParameters = {@OperationParam(min = 1, max = 2, name = "out1", type = StringDt.class)}) - public IBundleProvider everything(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam ca.uhn.fhir.model.primitive.IdDt theId, @OperationParam(name = "start") DateDt theStart, @OperationParam(name = "end") DateDt theEnd) { + public IBundleProvider everything(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam ca.uhn.fhir.model.primitive.IdDt theId, @OperationParam(name = "start") DateDt theStart, @OperationParam(name = "end") DateDt theEnd) { return null; } @@ -804,7 +804,7 @@ public class ServerConformanceProviderDstu2Test { public static class ProviderWithExtendedOperationReturningBundle implements IResourceProvider { @Operation(name = "everything", idempotent = true) - public IBundleProvider everything(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam ca.uhn.fhir.model.primitive.IdDt theId, @OperationParam(name = "start") DateDt theStart, @OperationParam(name = "end") DateDt theEnd) { + public IBundleProvider everything(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam ca.uhn.fhir.model.primitive.IdDt theId, @OperationParam(name = "start") DateDt theStart, @OperationParam(name = "end") DateDt theEnd) { return null; } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerFeaturesDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerFeaturesDstu2Test.java index 03e45b6bafe..1492d1f9810 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerFeaturesDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerFeaturesDstu2Test.java @@ -7,7 +7,9 @@ import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -18,11 +20,12 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -38,17 +41,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; */ public class ServerFeaturesDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ServerFeaturesDstu2Test.class); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testOptions() throws Exception { - HttpOptions httpGet = new HttpOptions("http://localhost:" + ourPort + ""); + HttpOptions httpGet = new HttpOptions(ourServer.getBaseUrl() + ""); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -60,7 +68,7 @@ public class ServerFeaturesDstu2Test { * Now with a leading / */ - httpGet = new HttpOptions("http://localhost:" + ourPort + "/"); + httpGet = new HttpOptions(ourServer.getBaseUrl() + "/"); status = ourClient.execute(httpGet); responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -76,7 +84,7 @@ public class ServerFeaturesDstu2Test { */ @Test public void testOptionsForNonBasePath1() throws Exception { - HttpOptions httpGet = new HttpOptions("http://localhost:" + ourPort + "/Foo"); + HttpOptions httpGet = new HttpOptions(ourServer.getBaseUrl() + "/Foo"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -90,7 +98,7 @@ public class ServerFeaturesDstu2Test { */ @Test public void testOptionsForNonBasePath2() throws Exception { - HttpOptions httpGet = new HttpOptions("http://localhost:" + ourPort + "/Patient/1"); + HttpOptions httpGet = new HttpOptions(ourServer.getBaseUrl() + "/Patient/1"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -104,7 +112,7 @@ public class ServerFeaturesDstu2Test { */ @Test public void testOptionsForNonBasePath3() throws Exception { - HttpOptions httpGet = new HttpOptions("http://localhost:" + ourPort + "/metadata"); + HttpOptions httpGet = new HttpOptions(ourServer.getBaseUrl() + "/metadata"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -115,7 +123,7 @@ public class ServerFeaturesDstu2Test { @Test public void testOptionsJson() throws Exception { - HttpOptions httpGet = new HttpOptions("http://localhost:" + ourPort + "?_format=json"); + HttpOptions httpGet = new HttpOptions(ourServer.getBaseUrl() + "?_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -126,7 +134,7 @@ public class ServerFeaturesDstu2Test { @Test public void testHeadJson() throws Exception { - HttpHead httpGet = new HttpHead("http://localhost:" + ourPort + "/Patient/123"); + HttpHead httpGet = new HttpHead(ourServer.getBaseUrl() + "/Patient/123"); HttpResponse status = ourClient.execute(httpGet); assertEquals(null, status.getEntity()); @@ -138,60 +146,45 @@ public class ServerFeaturesDstu2Test { @Test public void testRegisterAndUnregisterResourceProviders() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); assertThat(responseContent, containsString("PRP1")); - Collection providers = new ArrayList(ourServlet.getResourceProviders()); - for (IResourceProvider provider : providers) { - ourServlet.unregisterProvider(provider); + Collection originalProviders = new ArrayList<>(ourServer.getRestfulServer().getResourceProviders()); + DummyPatientResourceProvider2 newProvider = new DummyPatientResourceProvider2(); + try { + + // Replace provider + for (IResourceProvider provider : originalProviders) { + ourServer.getRestfulServer().unregisterProvider(provider); + } + ourServer.getRestfulServer().registerProvider(newProvider); + + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); + status = ourClient.execute(httpGet); + responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); + IOUtils.closeQuietly(status.getEntity().getContent()); + assertEquals(200, status.getStatusLine().getStatusCode()); + assertThat(responseContent, containsString("PRP2")); + + } finally { + + // Restore providers + ourServer.getRestfulServer().unregisterProvider(newProvider); + originalProviders.forEach(p->ourServer.getRestfulServer().registerProvider(p)); + } - - ourServlet.registerProvider(new DummyPatientResourceProvider2()); - - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); - status = ourClient.execute(httpGet); - responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); - IOUtils.closeQuietly(status.getEntity().getContent()); - assertEquals(200, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("PRP2")); - } @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setFhirContext(ourCtx); - ourServlet.setResourceProviders(patientProvider); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } public static class DummyPatientResourceProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerSearchDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerSearchDstu2Test.java index 4aa3af0638f..57f4072b97a 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerSearchDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerSearchDstu2Test.java @@ -4,42 +4,44 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.dstu2.resource.Patient; import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.ReferenceParam; import ca.uhn.fhir.rest.param.StringParam; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; public class ServerSearchDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static String ourLastMethod; private static StringParam ourLastRef; private static ReferenceParam ourLastRef2; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ServerSearchDstu2Test.class); - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -50,7 +52,7 @@ public class ServerSearchDstu2Test { @Test public void testReferenceParamMissingFalse() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/?param3:missing=false"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/?param3:missing=false"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -61,7 +63,7 @@ public class ServerSearchDstu2Test { @Test public void testReferenceParamMissingTrue() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/?param3:missing=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/?param3:missing=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -72,7 +74,7 @@ public class ServerSearchDstu2Test { @Test public void testSearchParam1() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/?param1=param1value"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/?param1=param1value"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -83,7 +85,7 @@ public class ServerSearchDstu2Test { @Test public void testSearchParam2() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/?param2=param2value&foo=bar"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/?param2=param2value&foo=bar"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -94,7 +96,7 @@ public class ServerSearchDstu2Test { @Test public void testSearchParamWithSpace() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/?param2=param+value&foo=bar"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/?param2=param+value&foo=bar"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -105,7 +107,7 @@ public class ServerSearchDstu2Test { @Test public void testSearchWithEncodedValue() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/?param1=" + UrlUtil.escapeUrlParam("Jernelöv")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/?param1=" + UrlUtil.escapeUrlParam("Jernelöv")); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -116,7 +118,7 @@ public class ServerSearchDstu2Test { @Test public void testUnknownSearchParam() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/?foo=bar"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/?foo=bar"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -126,33 +128,9 @@ public class ServerSearchDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setPlainProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider { @Search(allowUnknownParams=true) diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SummaryParamDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SummaryParamDstu2Test.java index bf6cfdb4da7..a1e4e2bac42 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SummaryParamDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/SummaryParamDstu2Test.java @@ -13,7 +13,9 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.SummaryEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -22,13 +24,14 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.Arrays; import java.util.List; @@ -44,13 +47,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SummaryParamDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SummaryParamDstu2Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static SummaryEnum ourLastSummary; private static List ourLastSummaryList; - private static int ourPort; - private static Server ourServer; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .registerProvider(new DummyMedicationOrderProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -60,7 +70,7 @@ public class SummaryParamDstu2Test { @Test public void testReadSummaryData() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1?_summary=" + SummaryEnum.DATA.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1?_summary=" + SummaryEnum.DATA.getCode()); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -79,7 +89,7 @@ public class SummaryParamDstu2Test { @Test public void testReadSummaryText() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1?_summary=" + SummaryEnum.TEXT.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1?_summary=" + SummaryEnum.TEXT.getCode()); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -96,7 +106,7 @@ public class SummaryParamDstu2Test { @Test public void testReadSummaryTextWithMandatory() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/MedicationOrder/1?_summary=" + SummaryEnum.TEXT.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/MedicationOrder/1?_summary=" + SummaryEnum.TEXT.getCode()); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -113,7 +123,7 @@ public class SummaryParamDstu2Test { @Test public void testReadSummaryTrue() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1?_summary=" + SummaryEnum.TRUE.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1?_summary=" + SummaryEnum.TRUE.getCode()); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -131,7 +141,7 @@ public class SummaryParamDstu2Test { @Test public void testSearchSummaryCount() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true&_summary=" + SummaryEnum.COUNT.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_pretty=true&_summary=" + SummaryEnum.COUNT.getCode()); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -148,7 +158,7 @@ public class SummaryParamDstu2Test { @Test public void testSearchSummaryData() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_summary=" + SummaryEnum.DATA.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_summary=" + SummaryEnum.DATA.getCode()); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -164,7 +174,7 @@ public class SummaryParamDstu2Test { @Test public void testSearchSummaryFalse() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_summary=false"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_summary=false"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -180,7 +190,7 @@ public class SummaryParamDstu2Test { @Test public void testSearchSummaryText() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_summary=" + SummaryEnum.TEXT.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_summary=" + SummaryEnum.TEXT.getCode()); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -197,7 +207,7 @@ public class SummaryParamDstu2Test { @Test public void testSearchSummaryTextWithMandatory() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/MedicationOrder?_summary=" + SummaryEnum.TEXT.getCode() + "&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/MedicationOrder?_summary=" + SummaryEnum.TEXT.getCode() + "&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -213,7 +223,7 @@ public class SummaryParamDstu2Test { @Test public void testSearchSummaryTextMulti() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=multi&_summary=" + SummaryEnum.TEXT.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=multi&_summary=" + SummaryEnum.TEXT.getCode()); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -230,7 +240,7 @@ public class SummaryParamDstu2Test { @Test public void testSearchSummaryTrue() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_summary=" + SummaryEnum.TRUE.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_summary=" + SummaryEnum.TRUE.getCode()); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -246,7 +256,7 @@ public class SummaryParamDstu2Test { @Test public void testSearchSummaryWithTextAndOthers() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_summary=text&_summary=data"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_summary=text&_summary=data"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -280,7 +290,7 @@ public class SummaryParamDstu2Test { } - public static class DummyPatientResourceProvider implements IResourceProvider { + private static class DummyPatientResourceProvider implements IResourceProvider { @Override public Class getResourceType() { @@ -324,31 +334,8 @@ public class SummaryParamDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(new DummyPatientResourceProvider(), new DummyMedicationOrderProvider()); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithBundleResourceParamTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithBundleResourceParamTest.java index f0930d2f5ef..c0ccc0f1191 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithBundleResourceParamTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithBundleResourceParamTest.java @@ -26,7 +26,7 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -232,7 +232,7 @@ public class TransactionWithBundleResourceParamTest { RestfulServer server = new RestfulServer(ourCtx); server.setProviders(patientProvider); - org.eclipse.jetty.servlet.ServletContextHandler proxyHandler = new org.eclipse.jetty.servlet.ServletContextHandler(); + org.eclipse.jetty.ee10.servlet.ServletContextHandler proxyHandler = new org.eclipse.jetty.ee10.servlet.ServletContextHandler(); proxyHandler.setContextPath("/"); ServletHolder handler = new ServletHolder(); diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithVersionlessBundleResourceParamTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithVersionlessBundleResourceParamTest.java index ce1263d5831..771c77140c7 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithVersionlessBundleResourceParamTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithVersionlessBundleResourceParamTest.java @@ -22,7 +22,7 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -96,7 +96,7 @@ public class TransactionWithVersionlessBundleResourceParamTest { RestfulServer server = new RestfulServer(ourCtx); server.setProviders(patientProvider); - org.eclipse.jetty.servlet.ServletContextHandler proxyHandler = new org.eclipse.jetty.servlet.ServletContextHandler(); + org.eclipse.jetty.ee10.servlet.ServletContextHandler proxyHandler = new org.eclipse.jetty.ee10.servlet.ServletContextHandler(); proxyHandler.setContextPath("/"); ServletHolder handler = new ServletHolder(); diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/UpdateDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/UpdateDstu2Test.java index 3db6f7cd78e..29fc3ad5ead 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/UpdateDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/UpdateDstu2Test.java @@ -14,8 +14,11 @@ import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.annotation.Update; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -27,12 +30,13 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -43,17 +47,24 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class UpdateDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static String ourLastConditionalUrl; private static IdDt ourLastId; private static IdDt ourLastIdParam; private static boolean ourLastRequestWasSearch; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(UpdateDstu2Test.class); - private static int ourPort; - private static Server ourServer; private static InstantDt ourSetLastUpdated; - + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { @@ -71,7 +82,7 @@ public class UpdateDstu2Test { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_pretty=true"); HttpResponse status = ourClient.execute(httpGet); @@ -93,7 +104,7 @@ public class UpdateDstu2Test { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?identifier=system%7C001"); + HttpPut httpPost = new HttpPut(ourServer.getBaseUrl() + "/Patient?identifier=system%7C001"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -105,7 +116,7 @@ public class UpdateDstu2Test { assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals(null, status.getFirstHeader("location")); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); assertNull(ourLastId.getValue()); assertNull(ourLastIdParam); @@ -121,7 +132,7 @@ public class UpdateDstu2Test { patient.setId("2"); patient.addIdentifier().setValue("002"); - HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/2"); + HttpPut httpPost = new HttpPut(ourServer.getBaseUrl() + "/Patient/2"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -133,7 +144,7 @@ public class UpdateDstu2Test { assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals(null, status.getFirstHeader("location")); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); assertEquals("Patient/2", ourLastId.toUnqualified().getValue()); assertEquals("Patient/2", ourLastIdParam.toUnqualified().getValue()); @@ -144,32 +155,10 @@ public class UpdateDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } public static class PatientProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu2Test.java index d3738f289e0..ac9791d0550 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu2Test.java @@ -15,7 +15,9 @@ import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.ValidationModeEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -26,12 +28,13 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -40,15 +43,23 @@ import static org.hamcrest.Matchers.stringContainsInOrder; import static org.junit.jupiter.api.Assertions.assertEquals; public class ValidateDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static EncodingEnum ourLastEncoding; private static ValidationModeEnum ourLastMode; private static String ourLastProfile; private static String ourLastResourceBody; private static BaseOperationOutcome ourOutcomeToReturn; - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .registerProvider(new OrganizationProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -70,7 +81,7 @@ public class ValidateDstu2Test { Parameters params = new Parameters(); params.addParameter().setName("resource").setResource(patient); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -92,7 +103,7 @@ public class ValidateDstu2Test { Parameters params = new Parameters(); params.addParameter().setName("resource").setResource(org); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Organization/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Organization/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_JSON, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -115,7 +126,7 @@ public class ValidateDstu2Test { params.addParameter().setName("profile").setValue(new StringDt("http://foo")); params.addParameter().setName("mode").setValue(new StringDt(ValidationModeEnum.CREATE.getCode())); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -142,7 +153,7 @@ public class ValidateDstu2Test { Parameters params = new Parameters(); params.addParameter().setName("resource").setResource(patient); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -156,32 +167,9 @@ public class ValidateDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider, new OrganizationProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class OrganizationProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/InterceptorUserDataMapDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/InterceptorUserDataMapDstu2Test.java index 8209c5c1ee5..7aacbea52d6 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/InterceptorUserDataMapDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/InterceptorUserDataMapDstu2Test.java @@ -19,12 +19,17 @@ import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.RequestDetails; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; +import ca.uhn.fhir.rest.server.SummaryParamDstu2Test; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -33,12 +38,13 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.Collections; @@ -60,20 +66,27 @@ import static org.junit.jupiter.api.Assertions.assertSame; public class InterceptorUserDataMapDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(InterceptorUserDataMapDstu2Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); - private static int ourPort; - private static Server ourServer; - private static RestfulServer servlet; + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private final Object myKey = "KEY"; private final Object myValue = "VALUE"; private Map myMap; private Set myMapCheckMethods; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .registerProvider(new DummyPatientResourceProvider()) + .registerProvider(new PlainProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { - servlet.getInterceptorService().unregisterAllInterceptors(); - servlet.getInterceptorService().registerInterceptor(new MyInterceptor()); + ourServer.getInterceptorService().unregisterAllInterceptors(); + ourServer.getInterceptorService().registerInterceptor(new MyInterceptor()); } @@ -87,7 +100,7 @@ public class InterceptorUserDataMapDstu2Test { @Test public void testException() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=foo"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_id=foo"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { assertEquals(400, status.getStatusLine().getStatusCode()); } @@ -98,7 +111,7 @@ public class InterceptorUserDataMapDstu2Test { @Test public void testRead() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { @@ -269,31 +282,7 @@ public class InterceptorUserDataMapDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - servlet = new RestfulServer(ourCtx); - - servlet.setResourceProviders(new DummyPatientResourceProvider()); - servlet.setPlainProviders(new PlainProvider()); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptorDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptorDstu2Test.java index 41fdd43c6bd..9a64c21a654 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptorDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptorDstu2Test.java @@ -19,11 +19,16 @@ import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; +import ca.uhn.fhir.rest.server.SummaryParamDstu2Test; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -35,13 +40,14 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hamcrest.core.StringContains; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; @@ -62,17 +68,24 @@ import static org.mockito.Mockito.verify; public class LoggingInterceptorDstu2Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); - private static int ourPort; - private static Server ourServer; - private static RestfulServer servlet; + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); private static int ourDelayMs; private static Exception ourThrowException; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .registerProvider(new PlainProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { - servlet.getInterceptorService().unregisterAllInterceptors(); + ourServer.getInterceptorService().unregisterAllInterceptors(); ourThrowException = null; ourDelayMs=0; } @@ -86,30 +99,30 @@ public class LoggingInterceptorDstu2Test { interceptor.setErrorMessageFormat("ERROR - ${requestVerb} ${requestUrl}"); assertEquals("ERROR - ${requestVerb} ${requestUrl}", interceptor.getErrorMessageFormat()); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/EX"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/EX"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(logger, timeout(1000).times(1)).info(captor.capture()); - assertThat(captor.getAllValues().get(0), StringContains.containsString("ERROR - GET http://localhost:" + ourPort + "/Patient/EX")); + assertThat(captor.getAllValues().get(0), StringContains.containsString("ERROR - GET " + ourServer.getBaseUrl() + "/Patient/EX")); } @Test public void testMetadata() throws Exception { LoggingInterceptor interceptor = new LoggingInterceptor(); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/metadata"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/metadata"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -125,12 +138,12 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${operationType} - ${operationName} - ${idOrResourceName}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$everything"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/$everything"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -147,12 +160,12 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${operationType} - ${operationName} - ${idOrResourceName} - ${requestBodyFhir}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -167,12 +180,12 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${requestId}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -187,12 +200,12 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${operationType} - ${processingTimeMillis}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -209,12 +222,12 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${processingTimeMillis}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -231,12 +244,12 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${operationType} - ${operationName} - ${idOrResourceName} - ${requestBodyFhir}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); httpGet.addHeader(Constants.HEADER_CONTENT_TYPE, Constants.CT_FHIR_XML); HttpResponse status = ourClient.execute(httpGet); @@ -252,7 +265,7 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${operationType} - ${operationName} - ${idOrResourceName} - ${requestBodyFhir}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); @@ -261,7 +274,7 @@ public class LoggingInterceptorDstu2Test { p.addIdentifier().setValue("VAL"); String input = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(input, ContentType.parse(Constants.CT_FHIR_XML + ";charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -280,7 +293,7 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${operationType} - ${operationName} - ${idOrResourceName} - ${requestBodyFhir}"); interceptor.setErrorMessageFormat("ERROR - ${operationType} - ${operationName} - ${idOrResourceName} - ${requestBodyFhir}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); @@ -291,7 +304,7 @@ public class LoggingInterceptorDstu2Test { ourThrowException = new NullPointerException("FOO"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(input, ContentType.parse(Constants.CT_FHIR_XML + ";charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -309,12 +322,12 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${operationType} - ${operationName} - ${idOrResourceName}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/$everything"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/$everything"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -330,12 +343,12 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${operationType} - ${operationName} - ${idOrResourceName}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$everything"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$everything"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -350,12 +363,12 @@ public class LoggingInterceptorDstu2Test { public void testRead() throws Exception { LoggingInterceptor interceptor = new LoggingInterceptor(); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -371,12 +384,12 @@ public class LoggingInterceptorDstu2Test { LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setMessageFormat("${operationType} - ${idOrResourceName} - ${requestParameters}"); - servlet.getInterceptorService().registerInterceptor(interceptor); + ourServer.getInterceptorService().registerInterceptor(interceptor); Logger logger = mock(Logger.class); interceptor.setLogger(logger); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_id=1"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -389,33 +402,9 @@ public class LoggingInterceptorDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - servlet = new RestfulServer(ourCtx); - - servlet.setResourceProviders(new DummyPatientResourceProvider()); - servlet.setPlainProviders(new PlainProvider()); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - /** * Created by dsotnikov on 2/25/2014. */ @@ -436,7 +425,7 @@ public class LoggingInterceptorDstu2Test { } public Map getIdToPatient() { - Map idToPatient = new HashMap(); + Map idToPatient = new HashMap<>(); { Patient patient = createPatient1(); idToPatient.put("1", patient); @@ -538,4 +527,5 @@ public class LoggingInterceptorDstu2Test { } + } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/ServerActionInterceptorTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/ServerActionInterceptorTest.java index 48b2924cf7f..1fe3ded49cf 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/ServerActionInterceptorTest.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/rest/server/interceptor/ServerActionInterceptorTest.java @@ -1,7 +1,6 @@ package ca.uhn.fhir.rest.server.interceptor; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.context.api.BundleInclusionRule; import ca.uhn.fhir.model.dstu2.resource.Observation; import ca.uhn.fhir.model.dstu2.resource.Patient; import ca.uhn.fhir.model.primitive.IdDt; @@ -16,61 +15,79 @@ import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.api.server.ResponseDetails; -import ca.uhn.fhir.rest.client.api.IGenericClient; -import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; -import ca.uhn.fhir.rest.server.RestfulServer; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentCaptor; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.util.Collections; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ServerActionInterceptorTest { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2(); - private static int ourPort; - private static Server ourServer; - private static IServerInterceptor ourInterceptor; - private static IGenericClient ourFhirClient; + private static final FhirContext ourCtx = FhirContext.forDstu2Cached(); + private IServerInterceptor myInterceptor; + + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerInterceptor(new ResponseHighlighterInterceptor()) + .registerProvider(new DummyPatientResourceProvider()) + .registerProvider(new DummyObservationResourceProvider()) + .registerProvider(new PlainProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); + + @BeforeEach + public void before() { + myInterceptor = mock(InterceptorAdapter.class); + ourServer.registerInterceptor(myInterceptor); + + when(myInterceptor.incomingRequestPreProcessed(any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); + when(myInterceptor.incomingRequestPostProcessed(any(RequestDetails.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); + when(myInterceptor.outgoingResponse(any(RequestDetails.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); + when(myInterceptor.outgoingResponse(any(RequestDetails.class), any(IBaseResource.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); + when(myInterceptor.outgoingResponse(any(RequestDetails.class), any(ResponseDetails.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); + } + + @AfterEach + public void after() { + ourServer.unregisterInterceptor(myInterceptor); + } @Test public void testRead() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123"); CloseableHttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); ArgumentCaptor detailsCapt = ArgumentCaptor.forClass(RequestDetails.class); - verify(ourInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.READ), detailsCapt.capture()); + verify(myInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.READ), detailsCapt.capture()); RequestDetails details = detailsCapt.getValue(); assertEquals("Patient/123", details.getId().getValue()); @@ -78,14 +95,14 @@ public class ServerActionInterceptorTest { @Test public void testVRead() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/_history/456"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/_history/456"); CloseableHttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); ArgumentCaptor detailsCapt = ArgumentCaptor.forClass(RequestDetails.class); - verify(ourInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.VREAD), detailsCapt.capture()); + verify(myInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.VREAD), detailsCapt.capture()); RequestDetails details = detailsCapt.getValue(); assertEquals("Patient/123/_history/456", details.getId().getValue()); @@ -95,10 +112,10 @@ public class ServerActionInterceptorTest { public void testCreate() throws Exception { Patient patient = new Patient(); patient.addName().addFamily("FAMILY"); - ourFhirClient.create().resource(patient).execute(); + ourServer.getFhirClient().create().resource(patient).execute(); ArgumentCaptor detailsCapt = ArgumentCaptor.forClass(RequestDetails.class); - verify(ourInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.CREATE), detailsCapt.capture()); + verify(myInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.CREATE), detailsCapt.capture()); RequestDetails details = detailsCapt.getValue(); assertEquals("Patient", details.getResourceName()); @@ -110,10 +127,10 @@ public class ServerActionInterceptorTest { public void testCreateWhereMethodHasNoResourceParam() throws Exception { Observation observation = new Observation(); observation.getCode().setText("OBSCODE"); - ourFhirClient.create().resource(observation).execute(); + ourServer.getFhirClient().create().resource(observation).execute(); ArgumentCaptor detailsCapt = ArgumentCaptor.forClass(RequestDetails.class); - verify(ourInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.CREATE), detailsCapt.capture()); + verify(myInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.CREATE), detailsCapt.capture()); RequestDetails details = detailsCapt.getValue(); assertEquals("Observation", details.getResourceName()); @@ -126,10 +143,10 @@ public class ServerActionInterceptorTest { Patient patient = new Patient(); patient.addName().addFamily("FAMILY"); patient.setId("Patient/123"); - ourFhirClient.update().resource(patient).execute(); + ourServer.getFhirClient().update().resource(patient).execute(); ArgumentCaptor detailsCapt = ArgumentCaptor.forClass(RequestDetails.class); - verify(ourInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.UPDATE), detailsCapt.capture()); + verify(myInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.UPDATE), detailsCapt.capture()); RequestDetails details = detailsCapt.getValue(); assertEquals("Patient", details.getResourceName()); @@ -141,91 +158,48 @@ public class ServerActionInterceptorTest { @Test public void testHistorySystem() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/_history"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/_history"); CloseableHttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); ArgumentCaptor detailsCapt = ArgumentCaptor.forClass(RequestDetails.class); - verify(ourInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.HISTORY_SYSTEM), detailsCapt.capture()); + verify(myInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.HISTORY_SYSTEM), detailsCapt.capture()); } @Test public void testHistoryType() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/_history"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/_history"); CloseableHttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); ArgumentCaptor detailsCapt = ArgumentCaptor.forClass(RequestDetails.class); - verify(ourInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.HISTORY_TYPE), detailsCapt.capture()); + verify(myInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.HISTORY_TYPE), detailsCapt.capture()); assertEquals("Patient", detailsCapt.getValue().getResourceName()); } @Test public void testHistoryInstance() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/_history"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/_history"); CloseableHttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); ArgumentCaptor detailsCapt = ArgumentCaptor.forClass(RequestDetails.class); - verify(ourInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.HISTORY_INSTANCE), detailsCapt.capture()); + verify(myInterceptor).incomingRequestPreHandled(eq(RestOperationTypeEnum.HISTORY_INSTANCE), detailsCapt.capture()); assertEquals("Patient", detailsCapt.getValue().getResourceName()); assertEquals("Patient/123", detailsCapt.getValue().getId().getValue()); } - @BeforeEach - public void before() { - reset(ourInterceptor); - - when(ourInterceptor.incomingRequestPreProcessed(any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); - when(ourInterceptor.incomingRequestPostProcessed(any(RequestDetails.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); - when(ourInterceptor.outgoingResponse(any(RequestDetails.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); - when(ourInterceptor.outgoingResponse(any(RequestDetails.class), any(IBaseResource.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); - when(ourInterceptor.outgoingResponse(any(RequestDetails.class), any(ResponseDetails.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); - } - @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.registerInterceptor(new ResponseHighlighterInterceptor()); - servlet.setResourceProviders(new DummyPatientResourceProvider(), new DummyObservationResourceProvider()); - servlet.setPlainProviders(new PlainProvider()); - servlet.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - ourInterceptor = mock(InterceptorAdapter.class); - servlet.registerInterceptor(ourInterceptor); - - ourCtx.getRestfulClientFactory().setSocketTimeout(240 * 1000); - ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); - ourFhirClient = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); - - } public static class PlainProvider { diff --git a/hapi-fhir-structures-dstu3/pom.xml b/hapi-fhir-structures-dstu3/pom.xml index 380194ed555..02408c1f044 100644 --- a/hapi-fhir-structures-dstu3/pom.xml +++ b/hapi-fhir-structures-dstu3/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -155,9 +155,9 @@ as much as possible. See #283. --> - javax.servlet - javax.servlet-api - 3.1.0 + jakarta.servlet + jakarta.servlet-api + 6.0.0 true @@ -200,36 +200,6 @@ xmlunit-core test - - org.eclipse.jetty - jetty-servlets - test - - - org.eclipse.jetty - jetty-servlet - test - - - org.eclipse.jetty - jetty-server - test - - - org.eclipse.jetty - jetty-util - test - - - org.eclipse.jetty - jetty-webapp - test - - - org.eclipse.jetty - jetty-http - test - ch.qos.logback logback-classic @@ -241,7 +211,7 @@ thymeleaf test - + ca.uhn.hapi.fhir hapi-fhir-test-utilities ${project.version} @@ -250,18 +220,18 @@ - com.helger - ph-schematron + com.helger.schematron + ph-schematron-api test - com.helger - ph-commons + com.helger.schematron + ph-schematron-xslt test - javax.activation - javax.activation-api + jakarta.activation + jakarta.activation-api test diff --git a/hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/hapi/rest/server/ServerCapabilityStatementProvider.java b/hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/hapi/rest/server/ServerCapabilityStatementProvider.java index c4ed58392ed..ca200ea7982 100644 --- a/hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/hapi/rest/server/ServerCapabilityStatementProvider.java +++ b/hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/hapi/rest/server/ServerCapabilityStatementProvider.java @@ -45,6 +45,8 @@ import ca.uhn.fhir.rest.server.method.SearchMethodBinding; import ca.uhn.fhir.rest.server.method.SearchParameter; import ca.uhn.fhir.rest.server.provider.ProviderConstants; import ca.uhn.fhir.rest.server.util.BaseServerCapabilityStatementProvider; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.dstu3.model.CapabilityStatement; import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementKind; @@ -81,8 +83,6 @@ import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/context/ContextScanningDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/context/ContextScanningDstu3Test.java index 5dd67c5faec..8e25e3754a8 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/context/ContextScanningDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/context/ContextScanningDstu3Test.java @@ -2,14 +2,18 @@ package ca.uhn.fhir.context; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.client.api.IGenericClient; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.Observation; import org.hl7.fhir.dstu3.model.Observation.ObservationStatus; @@ -19,6 +23,7 @@ import org.hl7.fhir.exceptions.FHIRFormatError; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.TreeSet; @@ -29,10 +34,18 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class ContextScanningDstu3Test { - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ContextScanningDstu3Test.class); - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .registerProvider(new ObservationProvider()) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testContextDoesntScanUnneccesaryTypes() { @@ -44,7 +57,7 @@ public class ContextScanningDstu3Test { ourLog.info("Have {} element definitions: {}", ctx.getElementDefinitions().size(), elementDefs); assertThat(resDefs, not(containsInRelativeOrder("Observation"))); - IGenericClient client = ctx.newRestfulGenericClient("http://localhost:" + ourPort); + IGenericClient client = ctx.newRestfulGenericClient(ourServer.getBaseUrl()); client.read().resource(Patient.class).withId("1").execute(); resDefs = scannedResourceNames(ctx); @@ -101,7 +114,7 @@ public class ContextScanningDstu3Test { BaseRuntimeElementCompositeDefinition compositeDef = (BaseRuntimeElementCompositeDefinition) ctx.getElementDefinition("identifier"); assertFalse(compositeDef.isSealed()); - IGenericClient client = ctx.newRestfulGenericClient("http://localhost:" + ourPort); + IGenericClient client = ctx.newRestfulGenericClient(ourServer.getBaseUrl()); client.read().resource(Patient.class).withId("1").execute(); resDefs = scannedResourceNames(ctx); @@ -141,24 +154,9 @@ public class ContextScanningDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(new PatientProvider(), new ObservationProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - } public static class PatientProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorDstu3Test.java index 421a0ce66a0..64e51dcf21c 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorDstu3Test.java @@ -143,7 +143,7 @@ public class DefaultThymeleafNarrativeGeneratorDstu3Test { String parse = "\n" + " \n" + " \n" + - " \n" + + " \n" + " \n" + " \n" + " \n" + diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CreateBinaryDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CreateBinaryDstu3Test.java index 2cf05c1c35e..933df506788 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CreateBinaryDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CreateBinaryDstu3Test.java @@ -4,8 +4,11 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.Create; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -16,8 +19,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.Binary; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.Patient; @@ -26,6 +29,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -34,13 +38,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; public class CreateBinaryDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static Binary ourLastBinary; private static byte[] ourLastBinaryBytes; private static String ourLastBinaryString; - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new BinaryProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -51,7 +62,7 @@ public class CreateBinaryDstu3Test { @Test public void testRawBytesBinaryContentType() throws Exception { - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost post = new HttpPost(ourServer.getBaseUrl() + "/Binary"); post.setEntity(new ByteArrayEntity(new byte[] { 0, 1, 2, 3, 4 })); post.addHeader("Content-Type", "application/foo"); CloseableHttpResponse status = ourClient.execute(post); @@ -75,7 +86,7 @@ public class CreateBinaryDstu3Test { b.setContent(new byte[] { 0, 1, 2, 3, 4 }); String encoded = ourCtx.newJsonParser().encodeResourceToString(b); - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost post = new HttpPost(ourServer.getBaseUrl() + "/Binary"); post.setEntity(new StringEntity(encoded)); post.addHeader("Content-Type", Constants.CT_FHIR_JSON); CloseableHttpResponse status = ourClient.execute(post); @@ -98,7 +109,7 @@ public class CreateBinaryDstu3Test { b.setContent(ourCtx.newXmlParser().encodeResourceToString(p).getBytes("UTF-8")); String encoded = ourCtx.newJsonParser().encodeResourceToString(b); - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost post = new HttpPost(ourServer.getBaseUrl() + "/Binary"); post.setEntity(new StringEntity(encoded)); post.addHeader("Content-Type", Constants.CT_FHIR_JSON); CloseableHttpResponse status = ourClient.execute(post); @@ -114,7 +125,7 @@ public class CreateBinaryDstu3Test { @Test public void testRawBytesNoContentType() throws Exception { - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost post = new HttpPost(ourServer.getBaseUrl() + "/Binary"); post.setEntity(new ByteArrayEntity(new byte[] { 0, 1, 2, 3, 4 })); CloseableHttpResponse status = ourClient.execute(post); try { @@ -127,31 +138,9 @@ public class CreateBinaryDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - BinaryProvider binaryProvider = new BinaryProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(binaryProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - } - public static class BinaryProvider implements IResourceProvider { @Create() diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CreateDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CreateDstu3Test.java index b1691ef0ad2..bffb7aa199b 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CreateDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CreateDstu3Test.java @@ -7,9 +7,12 @@ import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.client.MyPatientWithExtensions; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -21,8 +24,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.DateType; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.OperationOutcome; @@ -34,6 +37,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -47,14 +51,21 @@ import static org.hamcrest.Matchers.stringContainsInOrder; import static org.junit.jupiter.api.Assertions.assertEquals; public class CreateDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CreateDstu3Test.class); - private static int ourPort; - private static Server ourServer; public static IBaseOperationOutcome ourReturnOo; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourReturnOo = null; @@ -66,7 +77,7 @@ public class CreateDstu3Test { @Test public void testCreateReturnsLocationHeader() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"resourceType\":\"Patient\", \"status\":\"active\"}", ContentType.parse("application/fhir+json; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -79,7 +90,7 @@ public class CreateDstu3Test { assertEquals(1, status.getHeaders("Location").length); assertEquals(1, status.getHeaders("Content-Location").length); - assertEquals("http://localhost:" + ourPort + "/Patient/1", status.getFirstHeader("Location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/1", status.getFirstHeader("Location").getValue()); } @@ -88,7 +99,7 @@ public class CreateDstu3Test { ourReturnOo = new OperationOutcome().addIssue(new OperationOutcomeIssueComponent().setDiagnostics("DIAG")); String expectedResponseContent = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\"},\"gender\":\"male\"}"; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"resourceType\":\"Patient\", \"gender\":\"male\"}", ContentType.parse("application/fhir+json; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -108,7 +119,7 @@ public class CreateDstu3Test { @Test public void testCreateWithInvalidContent() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("FOO", ContentType.parse("application/xml+fhir; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -127,7 +138,7 @@ public class CreateDstu3Test { @Test public void testCreateWithIncorrectContent1() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"foo\":\"bar\"}", ContentType.parse("application/xml+fhir; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -146,7 +157,7 @@ public class CreateDstu3Test { @Test public void testCreateWithIncorrectContent2() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"foo\":\"bar\"}", ContentType.parse("application/fhir+xml; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -165,7 +176,7 @@ public class CreateDstu3Test { @Test public void testCreateWithIncorrectContent3() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"foo\":\"bar\"}", ContentType.parse("application/fhir+json; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -183,7 +194,7 @@ public class CreateDstu3Test { @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=xml&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=xml&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -211,34 +222,10 @@ public class CreateDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class PatientProvider implements IResourceProvider { + private static class PatientProvider implements IResourceProvider { @Create() public MethodOutcome create(@ResourceParam Patient theIdParam) { @@ -263,7 +250,7 @@ public class CreateDstu3Test { @Search public List search() { - ArrayList retVal = new ArrayList(); + ArrayList retVal = new ArrayList<>(); MyPatientWithExtensions p0 = new MyPatientWithExtensions(); p0.setId(new IdType("Patient/0")); diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CustomTypeServerDstu3.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CustomTypeServerDstu3.java index ab4e3d9c0bb..9bae98c5f28 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CustomTypeServerDstu3.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/CustomTypeServerDstu3.java @@ -10,8 +10,11 @@ import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -22,8 +25,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.OperationOutcome; import org.hl7.fhir.dstu3.model.Patient; @@ -31,6 +34,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -40,16 +44,23 @@ import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; public class CustomTypeServerDstu3 { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static String ourLastConditionalUrl; private static IdType ourLastId; private static IdType ourLastIdParam; private static boolean ourLastRequestWasSearch; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CustomTypeServerDstu3.class); - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -67,7 +78,7 @@ public class CustomTypeServerDstu3 { patient.setId("2"); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); // httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?identifier=system%7C001"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -87,7 +98,7 @@ public class CustomTypeServerDstu3 { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/2"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/2"); // httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?identifier=system%7C001"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -109,7 +120,7 @@ public class CustomTypeServerDstu3 { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/2"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/2"); httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?identifier=system%7C001"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -128,32 +139,9 @@ public class CustomTypeServerDstu3 { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Create() diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalDstu3Test.java index 26fc80d2b57..12b738269b5 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalDstu3Test.java @@ -4,17 +4,20 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; import ca.uhn.fhir.rest.annotation.Delete; import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -22,6 +25,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -29,16 +33,23 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class DeleteConditionalDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static IGenericClient ourHapiClient; private static String ourLastConditionalUrl; private static IdType ourLastIdParam; private static boolean ourLastRequestWasDelete; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(DeleteConditionalDstu3Test.class); - private static int ourPort; - private static Server ourServer; - + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { @@ -55,23 +66,13 @@ public class DeleteConditionalDstu3Test { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); -// HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true"); -// -// HttpResponse status = ourClient.execute(httpGet); -// -// String responseContent = IOUtils.toString(status.getEntity().getContent()); -// IOUtils.closeQuietly(status.getEntity().getContent()); -// -// ourLog.info("Response was:\n{}", responseContent); - - //@formatter:off - ourHapiClient + ourServer + .getFhirClient() .delete() .resourceConditionalByType(Patient.class) .where(Patient.IDENTIFIER.exactly().systemAndIdentifier("SOMESYS","SOMEID")) .execute(); - //@formatter:on - + assertTrue(ourLastRequestWasDelete); assertEquals(null, ourLastIdParam); assertEquals("Patient?identifier=SOMESYS%7CSOMEID", ourLastConditionalUrl); @@ -82,36 +83,10 @@ public class DeleteConditionalDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - ourCtx.getRestfulClientFactory().setSocketTimeout(500 * 1000); - ourHapiClient = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/"); - ourHapiClient.registerInterceptor(new LoggingInterceptor()); - } - public static class PatientProvider implements IResourceProvider { @Delete() diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/FormatParameterDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/FormatParameterDstu3Test.java index f9fb9b0cfb1..78ada9acf20 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/FormatParameterDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/FormatParameterDstu3Test.java @@ -5,24 +5,17 @@ import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.extension.RegisterExtension; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -30,21 +23,26 @@ public class FormatParameterDstu3Test { private static final String VALUE_XML = ""; private static final String VALUE_JSON = "{\"resourceType\":\"Patient\",\"id\":\"p1ReadId\",\"meta\":{\"profile\":[\"http://foo_profile\"]},\"identifier\":[{\"value\":\"p1ReadValue\"}]}"; - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FormatParameterDstu3Test.class); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); /** * See #346 */ @Test public void testFormatXml() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); + ourServer.setDefaultResponseEncoding(EncodingEnum.JSON); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=xml"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123?_format=xml"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -62,9 +60,9 @@ public class FormatParameterDstu3Test { */ @Test public void testFormatApplicationXml() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); + ourServer.setDefaultResponseEncoding(EncodingEnum.JSON); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/xml"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123?_format=application/xml"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -82,9 +80,9 @@ public class FormatParameterDstu3Test { */ @Test public void testFormatApplicationXmlFhir() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); + ourServer.setDefaultResponseEncoding(EncodingEnum.JSON); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/xml%2Bfhir"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123?_format=application/xml%2Bfhir"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -102,10 +100,10 @@ public class FormatParameterDstu3Test { */ @Test public void testFormatApplicationXmlFhirUnescaped() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); + ourServer.setDefaultResponseEncoding(EncodingEnum.JSON); // The plus isn't escaped here, and it should be.. but we'll be lenient - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/xml+fhir"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123?_format=application/xml+fhir"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -123,9 +121,9 @@ public class FormatParameterDstu3Test { */ @Test public void testFormatJson() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); + ourServer.setDefaultResponseEncoding(EncodingEnum.XML); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123?_format=json"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -143,9 +141,9 @@ public class FormatParameterDstu3Test { */ @Test public void testFormatApplicationJson() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); + ourServer.setDefaultResponseEncoding(EncodingEnum.XML); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123?_format=application/json"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -163,9 +161,9 @@ public class FormatParameterDstu3Test { */ @Test public void testFormatApplicationJsonFhir() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); + ourServer.setDefaultResponseEncoding(EncodingEnum.XML); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/json%2Bfhir"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123?_format=application/json%2Bfhir"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -183,10 +181,10 @@ public class FormatParameterDstu3Test { */ @Test public void testFormatApplicationJsonFhirUnescaped() throws Exception { - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); + ourServer.setDefaultResponseEncoding(EncodingEnum.XML); // The plus isn't escaped here, and it should be.. but we'll be lenient - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123?_format=application/json+fhir"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123?_format=application/json+fhir"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -201,34 +199,10 @@ public class FormatParameterDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setFhirContext(ourCtx); - ourServlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { + private static class DummyPatientResourceProvider implements IResourceProvider { @Override public Class getResourceType() { diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/InterceptorDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/InterceptorDstu3Test.java index 1f636645ada..f720e5851b7 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/InterceptorDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/InterceptorDstu3Test.java @@ -21,7 +21,9 @@ import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor; import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter; import ca.uhn.fhir.rest.server.interceptor.ServerOperationInterceptorAdapter; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -33,8 +35,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.IntegerType; import org.hl7.fhir.dstu3.model.OperationOutcome; @@ -46,11 +48,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; @@ -73,18 +76,23 @@ import static org.mockito.Mockito.when; public class InterceptorDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static Patient ourLastPatient; private IServerInterceptor myInterceptor1; private IServerInterceptor myInterceptor2; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @AfterEach public void after() { - ourServlet.getInterceptorService().unregisterAllInterceptors(); + ourServer.getInterceptorService().unregisterAllInterceptors(); } @BeforeEach @@ -115,20 +123,20 @@ public class InterceptorDstu3Test { resource.set(requestDetails.getResource()); }; - ourServlet.getInterceptorService().registerAnonymousInterceptor(Pointcut.SERVER_INCOMING_REQUEST_PRE_HANDLED, interceptor); + ourServer.getInterceptorService().registerAnonymousInterceptor(Pointcut.SERVER_INCOMING_REQUEST_PRE_HANDLED, interceptor); try { Parameters p = new Parameters(); p.addParameter().setName("limit").setValue(new IntegerType(123)); String input = ourCtx.newJsonParser().encodeResourceToString(p); - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Patient/$postOperation"); + HttpPost post = new HttpPost(ourServer.getBaseUrl() + "/Patient/$postOperation"); post.setEntity(new StringEntity(input, ContentType.create("application/fhir+json", Constants.CHARSET_UTF8))); try (CloseableHttpResponse status = ourClient.execute(post)) { assertEquals(200, status.getStatusLine().getStatusCode()); IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); } } finally { - ourServlet.unregisterInterceptor(interceptor); + ourServer.unregisterInterceptor(interceptor); } assertNotNull(resource.get()); @@ -148,10 +156,10 @@ public class InterceptorDstu3Test { return true; } }; - ourServlet.registerInterceptor(interceptor); + ourServer.registerInterceptor(interceptor); try { - HttpGet get = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); + HttpGet get = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); try (CloseableHttpResponse status = ourClient.execute(get)) { String response = IOUtils.toString(status.getEntity().getContent(), Constants.CHARSET_UTF8); assertThat(response, containsString("NAME1")); @@ -160,13 +168,13 @@ public class InterceptorDstu3Test { } } finally { - ourServlet.unregisterInterceptor(interceptor); + ourServer.unregisterInterceptor(interceptor); } } @Test public void testResourceResponseIncluded() throws Exception { - ourServlet.setInterceptors(myInterceptor1, myInterceptor2); + ourServer.getRestfulServer().setInterceptors(myInterceptor1, myInterceptor2); when(myInterceptor1.incomingRequestPreProcessed(nullable(HttpServletRequest.class), nullable(HttpServletResponse.class))).thenReturn(true); when(myInterceptor1.incomingRequestPostProcessed(nullable(ServletRequestDetails.class), nullable(HttpServletRequest.class), nullable(HttpServletResponse.class))).thenReturn(true); @@ -192,7 +200,7 @@ public class InterceptorDstu3Test { String input = createInput(); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(input, ContentType.create(Constants.CT_FHIR_JSON, "UTF-8"))); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -214,7 +222,7 @@ public class InterceptorDstu3Test { @Test public void testExceptionInProcessingCompletedNormally() throws Exception { - ourServlet.setInterceptors(myInterceptor1); + ourServer.getRestfulServer().setInterceptors(myInterceptor1); when(myInterceptor1.incomingRequestPreProcessed(nullable(HttpServletRequest.class), nullable(HttpServletResponse.class))).thenReturn(true); when(myInterceptor1.incomingRequestPostProcessed(nullable(ServletRequestDetails.class), nullable(HttpServletRequest.class), nullable(HttpServletResponse.class))).thenReturn(true); @@ -226,7 +234,7 @@ public class InterceptorDstu3Test { String input = createInput(); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(input, ContentType.create(Constants.CT_FHIR_JSON, "UTF-8"))); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -236,7 +244,7 @@ public class InterceptorDstu3Test { @Test public void testResponseWithNothing() throws Exception { - ourServlet.setInterceptors(myInterceptor1); + ourServer.getRestfulServer().setInterceptors(myInterceptor1); when(myInterceptor1.incomingRequestPreProcessed(nullable(HttpServletRequest.class), nullable(HttpServletResponse.class))).thenReturn(true); when(myInterceptor1.incomingRequestPostProcessed(nullable(ServletRequestDetails.class), nullable(HttpServletRequest.class), nullable(HttpServletResponse.class))).thenReturn(true); @@ -248,7 +256,7 @@ public class InterceptorDstu3Test { String input = createInput(); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(input, ContentType.create(Constants.CT_FHIR_JSON, "UTF-8"))); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { assertEquals(201, status.getStatusLine().getStatusCode()); @@ -272,7 +280,7 @@ public class InterceptorDstu3Test { @Test public void testResponseWithOperationOutcome() throws Exception { - ourServlet.setInterceptors(myInterceptor1); + ourServer.getRestfulServer().setInterceptors(myInterceptor1); when(myInterceptor1.incomingRequestPreProcessed(nullable(HttpServletRequest.class), nullable(HttpServletResponse.class))).thenReturn(true); when(myInterceptor1.incomingRequestPostProcessed(nullable(ServletRequestDetails.class), nullable(HttpServletRequest.class), nullable(HttpServletResponse.class))).thenReturn(true); @@ -284,7 +292,7 @@ public class InterceptorDstu3Test { String input = createInput(); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(input, ContentType.create(Constants.CT_FHIR_JSON, "UTF-8"))); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -315,33 +323,9 @@ public class InterceptorDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setResourceProviders(patientProvider); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Create() diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/MetadataCapabilityStatementDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/MetadataCapabilityStatementDstu3Test.java index 62f7c77ac8a..df9e31cd42c 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/MetadataCapabilityStatementDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/MetadataCapabilityStatementDstu3Test.java @@ -10,7 +10,9 @@ import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.system.HapiSystemProperties; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.VersionUtil; import org.apache.commons.io.IOUtils; @@ -22,8 +24,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.hapi.rest.server.ServerCapabilityStatementProvider; import org.hl7.fhir.dstu3.model.CapabilityStatement; import org.hl7.fhir.dstu3.model.Patient; @@ -31,6 +33,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.List; @@ -45,11 +48,18 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class MetadataCapabilityStatementDstu3Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(MetadataCapabilityStatementDstu3Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false) + .withServer(s->s.setServerConformanceProvider(new ServerCapabilityStatementProvider(s).setCache(false))); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); static { HapiSystemProperties.enableTestMode(); @@ -57,14 +67,14 @@ public class MetadataCapabilityStatementDstu3Test { @AfterEach public void after() { - ourServlet.setServerAddressStrategy(new IncomingRequestAddressStrategy()); + ourServer.setServerAddressStrategy(new IncomingRequestAddressStrategy()); } @Test public void testElements() throws Exception { String output; - HttpRequestBase httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_elements=fhirVersion&_pretty=true"); + HttpRequestBase httpPost = new HttpGet(ourServer.getBaseUrl() + "/metadata?_elements=fhirVersion&_pretty=true"); CloseableHttpResponse status = ourClient.execute(httpPost); try { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -81,7 +91,7 @@ public class MetadataCapabilityStatementDstu3Test { public void testHttpMethods() throws Exception { String output; - HttpRequestBase httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata"); + HttpRequestBase httpPost = new HttpGet(ourServer.getBaseUrl() + "/metadata"); CloseableHttpResponse status = ourClient.execute(httpPost); try { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -94,7 +104,7 @@ public class MetadataCapabilityStatementDstu3Test { } try { - httpPost = new HttpPost("http://localhost:" + ourPort + "/metadata"); + httpPost = new HttpPost(ourServer.getBaseUrl() + "/metadata"); status = ourClient.execute(httpPost); output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); assertEquals(405, status.getStatusLine().getStatusCode()); @@ -110,7 +120,7 @@ public class MetadataCapabilityStatementDstu3Test { * would be interpreted as a read on ID "metadata" */ try { - httpPost = new HttpGet("http://localhost:" + ourPort + "/Patient/metadata"); + httpPost = new HttpGet(ourServer.getBaseUrl() + "/Patient/metadata"); status = ourClient.execute(httpPost); output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); assertEquals(400, status.getStatusLine().getStatusCode()); @@ -123,7 +133,7 @@ public class MetadataCapabilityStatementDstu3Test { public void testResponseContainsBaseUrl() throws Exception { String output; - HttpRequestBase httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_format=json"); + HttpRequestBase httpPost = new HttpGet(ourServer.getBaseUrl() + "/metadata?_format=json"); CloseableHttpResponse status = ourClient.execute(httpPost); try { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -131,7 +141,7 @@ public class MetadataCapabilityStatementDstu3Test { ourLog.info(output); CapabilityStatement cs = ourCtx.newJsonParser().parseResource(CapabilityStatement.class, output); - assertEquals("http://localhost:" + ourPort + "/", cs.getImplementation().getUrl()); + assertEquals(ourServer.getBaseUrl() + "/", cs.getImplementation().getUrl()); } finally { IOUtils.closeQuietly(status.getEntity().getContent()); } @@ -139,11 +149,11 @@ public class MetadataCapabilityStatementDstu3Test { @Test public void testResponseContainsBaseUrlFixed() throws Exception { - ourServlet.setServerAddressStrategy(new HardcodedServerAddressStrategy("http://foo/bar")); + ourServer.setServerAddressStrategy(new HardcodedServerAddressStrategy("http://foo/bar")); String output; - HttpRequestBase httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_format=json"); + HttpRequestBase httpPost = new HttpGet(ourServer.getBaseUrl() + "/metadata?_format=json"); CloseableHttpResponse status = ourClient.execute(httpPost); try { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -162,7 +172,7 @@ public class MetadataCapabilityStatementDstu3Test { String output; // With - HttpRequestBase httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_summary=true&_pretty=true"); + HttpRequestBase httpPost = new HttpGet(ourServer.getBaseUrl() + "/metadata?_summary=true&_pretty=true"); CloseableHttpResponse status = ourClient.execute(httpPost); try { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -176,7 +186,7 @@ public class MetadataCapabilityStatementDstu3Test { } // Without - httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_pretty=true"); + httpPost = new HttpGet(ourServer.getBaseUrl() + "/metadata?_pretty=true"); status = ourClient.execute(httpPost); try { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -192,36 +202,9 @@ public class MetadataCapabilityStatementDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setResourceProviders(patientProvider); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ourServlet.setServerConformanceProvider(new ServerCapabilityStatementProvider(ourServlet).setCache(false)); - - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - @SuppressWarnings("unused") public static class DummyPatientResourceProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/MetadataConformanceDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/MetadataConformanceDstu3Test.java index 3a3203833da..60bfcf009e9 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/MetadataConformanceDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/MetadataConformanceDstu3Test.java @@ -9,7 +9,8 @@ import ca.uhn.fhir.rest.annotation.Validate; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.param.StringParam; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.VersionUtil; import org.apache.commons.io.IOUtils; @@ -18,21 +19,13 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.hl7.fhir.dstu3.hapi.rest.server.ServerCapabilityStatementProvider; import org.hl7.fhir.dstu3.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -43,18 +36,24 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class MetadataConformanceDstu3Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(MetadataConformanceDstu3Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testSummary() throws Exception { String output; // With - HttpRequestBase httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_summary=true&_pretty=true"); + HttpRequestBase httpPost = new HttpGet(ourServer.getBaseUrl() + "/metadata?_summary=true&_pretty=true"); CloseableHttpResponse status = ourClient.execute(httpPost); try { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -68,7 +67,7 @@ public class MetadataConformanceDstu3Test { } // Without - httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_pretty=true"); + httpPost = new HttpGet(ourServer.getBaseUrl() + "/metadata?_pretty=true"); status = ourClient.execute(httpPost); try { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -86,7 +85,7 @@ public class MetadataConformanceDstu3Test { public void testElements() throws Exception { String output; - HttpRequestBase httpPost = new HttpGet("http://localhost:" + ourPort + "/metadata?_elements=fhirVersion&_pretty=true"); + HttpRequestBase httpPost = new HttpGet(ourServer.getBaseUrl() + "/metadata?_elements=fhirVersion&_pretty=true"); CloseableHttpResponse status = ourClient.execute(httpPost); try { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -103,7 +102,7 @@ public class MetadataConformanceDstu3Test { public void testHttpMethods() throws Exception { String output; - HttpRequestBase httpOperation = new HttpGet("http://localhost:" + ourPort + "/metadata"); + HttpRequestBase httpOperation = new HttpGet(ourServer.getBaseUrl() + "/metadata"); try (CloseableHttpResponse status = ourClient.execute(httpOperation)) { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -112,7 +111,7 @@ public class MetadataConformanceDstu3Test { assertThat(status.getFirstHeader("X-Powered-By").getValue(), containsString("REST Server (FHIR Server; FHIR " + ourCtx.getVersion().getVersion().getFhirVersionString() + "/" + ourCtx.getVersion().getVersion().name() + ")")); } - httpOperation = new HttpOptions("http://localhost:" + ourPort); + httpOperation = new HttpOptions(ourServer.getBaseUrl()); try (CloseableHttpResponse status = ourClient.execute(httpOperation)) { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -121,7 +120,7 @@ public class MetadataConformanceDstu3Test { assertThat(status.getFirstHeader("X-Powered-By").getValue(), containsString("REST Server (FHIR Server; FHIR " + ourCtx.getVersion().getVersion().getFhirVersionString() + "/" + ourCtx.getVersion().getVersion().name() + ")")); } - httpOperation = new HttpPost("http://localhost:" + ourPort + "/metadata"); + httpOperation = new HttpPost(ourServer.getBaseUrl() + "/metadata"); try (CloseableHttpResponse status = ourClient.execute(httpOperation)) { output = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); assertEquals(405, status.getStatusLine().getStatusCode()); @@ -132,7 +131,7 @@ public class MetadataConformanceDstu3Test { * There is no @read on the RP below, so this should fail. Otherwise it * would be interpreted as a read on ID "metadata" */ - httpOperation = new HttpGet("http://localhost:" + ourPort + "/Patient/metadata"); + httpOperation = new HttpGet(ourServer.getBaseUrl() + "/Patient/metadata"); try (CloseableHttpResponse status = ourClient.execute(httpOperation)) { assertEquals(400, status.getStatusLine().getStatusCode()); } @@ -159,32 +158,7 @@ public class MetadataConformanceDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setServerConformanceProvider(new ServerCapabilityStatementProvider(ourServlet)); - ourServlet.setResourceProviders(patientProvider); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu3Test.java index a4f1f28041c..f8acf9eaa86 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/OperationServerDstu3Test.java @@ -10,7 +10,9 @@ import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -23,8 +25,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.CapabilityStatement; import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementRestOperationComponent; @@ -42,6 +44,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -57,8 +60,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; public class OperationServerDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static IdType ourLastId; private static String ourLastMethod; @@ -68,10 +70,19 @@ public class OperationServerDstu3Test { private static Money ourLastParamMoney1; private static UnsignedIntType ourLastParamUnsignedInt1; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationServerDstu3Test.class); - private static int ourPort; - private static Server ourServer; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .registerProvider(new PlainProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); private IGenericClient myFhirClient; + @BeforeEach public void before() { ourLastParam1 = null; @@ -82,7 +93,7 @@ public class OperationServerDstu3Test { ourLastId = null; ourLastMethod = ""; - myFhirClient = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); + myFhirClient = ourServer.getFhirClient(); } @@ -155,7 +166,7 @@ public class OperationServerDstu3Test { public void testInstanceEverythingGet() throws Exception { // Try with a GET - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$everything"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/$everything"); CloseableHttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -170,7 +181,7 @@ public class OperationServerDstu3Test { @Test public void testInstanceEverythingHapiClient() throws Exception { - ourCtx.newRestfulGenericClient("http://localhost:" + ourPort).operation().onInstance(new IdType("Patient/123")).named("$everything").withParameters(new Parameters()).execute(); + ourCtx.newRestfulGenericClient(ourServer.getBaseUrl()).operation().onInstance(new IdType("Patient/123")).named("$everything").withParameters(new Parameters()).execute(); assertEquals("instance $everything", ourLastMethod); assertEquals("Patient/123", ourLastId.toUnqualifiedVersionless().getValue()); @@ -183,7 +194,7 @@ public class OperationServerDstu3Test { String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(new Parameters()); // Try with a POST - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$everything"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$everything"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -199,7 +210,7 @@ public class OperationServerDstu3Test { @Test public void testOperationCantUseGetIfItIsntIdempotent() throws Exception { - HttpGet httpPost = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE"); + HttpGet httpPost = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); HttpResponse status = ourClient.execute(httpPost); assertEquals(Constants.STATUS_HTTP_405_METHOD_NOT_ALLOWED, status.getStatusLine().getStatusCode()); @@ -216,7 +227,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM1").setValue(new IntegerType(123)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); CloseableHttpResponse status = ourClient.execute(httpPost); try { @@ -235,7 +246,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -255,7 +266,7 @@ public class OperationServerDstu3Test { * Against type should fail */ - httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_INSTANCE"); + httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); status = ourClient.execute(httpPost); @@ -273,7 +284,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE_OR_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE_OR_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -298,7 +309,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_INSTANCE_OR_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_INSTANCE_OR_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); CloseableHttpResponse status = ourClient.execute(httpPost); @@ -322,7 +333,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/$OP_SERVER"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/$OP_SERVER"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -345,7 +356,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -368,7 +379,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_TYPE_RET_BUNDLE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_TYPE_RET_BUNDLE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -386,7 +397,7 @@ public class OperationServerDstu3Test { @Test public void testOperationWithBundleProviderResponse() throws Exception { - HttpGet httpPost = new HttpGet("http://localhost:" + ourPort + "/$OP_INSTANCE_BUNDLE_PROVIDER?_pretty=true"); + HttpGet httpPost = new HttpGet(ourServer.getBaseUrl() + "/$OP_INSTANCE_BUNDLE_PROVIDER?_pretty=true"); HttpResponse status = ourClient.execute(httpPost); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -399,7 +410,7 @@ public class OperationServerDstu3Test { @Test public void testOperationWithGetUsingParams() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$OP_TYPE?PARAM1=PARAM1val"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$OP_TYPE?PARAM1=PARAM1val"); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -416,7 +427,7 @@ public class OperationServerDstu3Test { @Test public void testOperationWithGetUsingParamsFailsWithNonPrimitive() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$OP_TYPE?PARAM1=PARAM1val&PARAM2=foo"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$OP_TYPE?PARAM1=PARAM1val&PARAM2=foo"); HttpResponse status = ourClient.execute(httpGet); assertEquals(405, status.getStatusLine().getStatusCode()); @@ -436,7 +447,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM3").setValue(new StringType("PARAM3val2")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/$OP_SERVER_LIST_PARAM"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/$OP_SERVER_LIST_PARAM"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -461,7 +472,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM1").setValue(new IntegerType("123")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_PROFILE_DT"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_PROFILE_DT"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -482,7 +493,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM1").setValue(money); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_PROFILE_DT2"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_PROFILE_DT2"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -497,7 +508,7 @@ public class OperationServerDstu3Test { @Test public void testOperationWithProfileDatatypeUrl() throws Exception { - HttpGet httpPost = new HttpGet("http://localhost:" + ourPort + "/Patient/$OP_PROFILE_DT?PARAM1=123"); + HttpGet httpPost = new HttpGet(ourServer.getBaseUrl() + "/Patient/$OP_PROFILE_DT?PARAM1=123"); HttpResponse status = ourClient.execute(httpPost); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -514,7 +525,7 @@ public class OperationServerDstu3Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -530,7 +541,7 @@ public class OperationServerDstu3Test { @Test public void testReadWithOperations() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123"); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -542,38 +553,9 @@ public class OperationServerDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu3(); - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); - - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(new PatientProvider()); - servlet.registerProvider(new PlainProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class PatientProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu3Test.java index 76335fec772..3036e082ac3 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/OperationServerWithSearchParamTypesDstu3Test.java @@ -4,6 +4,7 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.param.StringAndListParam; import ca.uhn.fhir.rest.param.StringOrListParam; @@ -13,7 +14,9 @@ import ca.uhn.fhir.rest.param.TokenOrListParam; import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.rest.param.TokenParamModifier; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; import org.apache.commons.io.IOUtils; @@ -26,8 +29,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.hapi.rest.server.ServerCapabilityStatementProvider; import org.hl7.fhir.dstu3.model.CapabilityStatement; import org.hl7.fhir.dstu3.model.IdType; @@ -41,8 +44,10 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.servlet.ServletConfig; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.extension.RegisterExtension; + import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; @@ -55,15 +60,24 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class OperationServerWithSearchParamTypesDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static String ourLastMethod; private static List ourLastParamValStr; private static List ourLastParamValTok; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationServerWithSearchParamTypesDstu3Test.class); - private static int ourPort; - private static Server ourServer; + + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = ""; @@ -95,7 +109,7 @@ public class OperationServerWithSearchParamTypesDstu3Test { p.addParameter().setName("valtok").setValue(new StringType("VALTOK2A|VALTOK2B")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$andlist"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$andlist"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -121,7 +135,7 @@ public class OperationServerWithSearchParamTypesDstu3Test { @Test public void testEscapedOperationName() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/%24andlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/%24andlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -134,7 +148,7 @@ public class OperationServerWithSearchParamTypesDstu3Test { @Test public void testAndListWithUrl() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$andlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$andlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -266,7 +280,7 @@ public class OperationServerWithSearchParamTypesDstu3Test { p.addParameter().setName("valtok").setValue(new StringType("VALTOKA|VALTOKB")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$nonrepeating"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$nonrepeating"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -286,7 +300,7 @@ public class OperationServerWithSearchParamTypesDstu3Test { } @Test public void testNonRepeatingWithUrl() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$nonrepeating?valstr=VALSTR&valtok=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$nonrepeating?valstr=VALSTR&valtok=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -306,7 +320,7 @@ public class OperationServerWithSearchParamTypesDstu3Test { @Test public void testNonRepeatingWithUrlQualified() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$nonrepeating?valstr:exact=VALSTR&valtok:not=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$nonrepeating?valstr:exact=VALSTR&valtok:not=" + UrlUtil.escapeUrlParam("VALTOKA|VALTOKB")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -335,7 +349,7 @@ public class OperationServerWithSearchParamTypesDstu3Test { p.addParameter().setName("valtok").setValue(new StringType("VALTOK2A|VALTOK2B")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$orlist"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$orlist"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -361,7 +375,7 @@ public class OperationServerWithSearchParamTypesDstu3Test { @Test public void testOrListWithUrl() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$orlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$orlist?valstr=VALSTR1A,VALSTR1B&valstr=VALSTR2A,VALSTR2B&valtok=" + UrlUtil.escapeUrlParam("VALTOK1A|VALTOK1B") + "&valtok=" + UrlUtil.escapeUrlParam("VALTOK2A|VALTOK2B")); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -386,33 +400,9 @@ public class OperationServerWithSearchParamTypesDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu3(); - ourServer = new Server(0); - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); - - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(new PatientProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } public static class PatientProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/PatchServerDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/PatchServerDstu3Test.java index e82099319a4..d4b9b59e3de 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/PatchServerDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/PatchServerDstu3Test.java @@ -9,46 +9,47 @@ import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.PatchTypeEnum; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPatch; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.OperationOutcome; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; public class PatchServerDstu3Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(PatchServerDstu3Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); - private static int ourPort; - private static Server ourServer; + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static String ourLastMethod; private static PatchTypeEnum ourLastPatchType; private static String ourLastBody; private static IdType ourLastId; private static String ourLastConditional; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -60,7 +61,7 @@ public class PatchServerDstu3Test { @Test public void testPatchValidJson() throws Exception { String requestContents = "[ { \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ \"foo\", \"bar\" ] } ]"; - HttpPatch httpPatch = new HttpPatch("http://localhost:" + ourPort + "/Patient/123"); + HttpPatch httpPatch = new HttpPatch(ourServer.getBaseUrl() + "/Patient/123"); httpPatch.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); httpPatch.setEntity(new StringEntity(requestContents, ContentType.parse(Constants.CT_JSON_PATCH))); CloseableHttpResponse status = ourClient.execute(httpPatch); @@ -83,7 +84,7 @@ public class PatchServerDstu3Test { @Test public void testPatchUsingConditional() throws Exception { String requestContents = "[ { \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ \"foo\", \"bar\" ] } ]"; - HttpPatch httpPatch = new HttpPatch("http://localhost:" + ourPort + "/Patient?_id=123"); + HttpPatch httpPatch = new HttpPatch(ourServer.getBaseUrl() + "/Patient?_id=123"); httpPatch.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); httpPatch.setEntity(new StringEntity(requestContents, ContentType.parse(Constants.CT_JSON_PATCH))); CloseableHttpResponse status = ourClient.execute(httpPatch); @@ -107,7 +108,7 @@ public class PatchServerDstu3Test { @Test public void testPatchValidXml() throws Exception { String requestContents = ""; - HttpPatch httpPatch = new HttpPatch("http://localhost:" + ourPort + "/Patient/123"); + HttpPatch httpPatch = new HttpPatch(ourServer.getBaseUrl() + "/Patient/123"); httpPatch.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); httpPatch.setEntity(new StringEntity(requestContents, ContentType.parse(Constants.CT_XML_PATCH))); CloseableHttpResponse status = ourClient.execute(httpPatch); @@ -130,7 +131,7 @@ public class PatchServerDstu3Test { @Test public void testPatchValidJsonWithCharset() throws Exception { String requestContents = "[ { \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ \"foo\", \"bar\" ] } ]"; - HttpPatch httpPatch = new HttpPatch("http://localhost:" + ourPort + "/Patient/123"); + HttpPatch httpPatch = new HttpPatch(ourServer.getBaseUrl() + "/Patient/123"); httpPatch.setEntity(new StringEntity(requestContents, ContentType.parse(Constants.CT_JSON_PATCH + Constants.CHARSET_UTF8_CTSUFFIX))); CloseableHttpResponse status = ourClient.execute(httpPatch); @@ -150,7 +151,7 @@ public class PatchServerDstu3Test { @Test public void testPatchInvalidMimeType() throws Exception { String requestContents = "[ { \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ \"foo\", \"bar\" ] } ]"; - HttpPatch httpPatch = new HttpPatch("http://localhost:" + ourPort + "/Patient/123"); + HttpPatch httpPatch = new HttpPatch(ourServer.getBaseUrl() + "/Patient/123"); httpPatch.setEntity(new StringEntity(requestContents, ContentType.parse("text/plain; charset=UTF-8"))); CloseableHttpResponse status = ourClient.execute(httpPatch); @@ -193,33 +194,7 @@ public class PatchServerDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setResourceProviders(patientProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeDstu3Test.java index 3675cb90c9b..9817849504b 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeDstu3Test.java @@ -10,8 +10,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu3Test.java index b3edc466493..5f8bfa1a944 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchCountParamDstu3Test.java @@ -6,7 +6,9 @@ import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.TokenParam; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -15,8 +17,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.HumanName; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -24,6 +26,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -38,13 +41,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchCountParamDstu3Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchCountParamDstu3Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); - private static int ourPort; - private static Server ourServer; + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static String ourLastMethod; private static Integer ourLastParam; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .setDefaultResponseEncoding(EncodingEnum.XML) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -53,7 +63,7 @@ public class SearchCountParamDstu3Test { @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_count=2"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_count=2"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -65,11 +75,11 @@ public class SearchCountParamDstu3Test { assertThat(responseContent, stringContainsInOrder( "", "", - "", + "", "", "", "", - "", + "", "")); } @@ -79,7 +89,7 @@ public class SearchCountParamDstu3Test { @Test public void testSearchCount0() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_count=0&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_count=0&_pretty=true"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -103,7 +113,7 @@ public class SearchCountParamDstu3Test { */ @Test public void testSearchWithNoCountParam() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithNoCountParam&_count=2"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithNoCountParam&_count=2"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -115,11 +125,11 @@ public class SearchCountParamDstu3Test { assertThat(responseContent, stringContainsInOrder( "", "", - "", + "", "", "", "", - "", + "", "")); } finally { @@ -170,33 +180,7 @@ public class SearchCountParamDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setResourceProviders(patientProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchDefaultMethodDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchDefaultMethodDstu3Test.java index ceb424dfcb4..cf4d62d6701 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchDefaultMethodDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchDefaultMethodDstu3Test.java @@ -4,8 +4,11 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.RawParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.StringAndListParam; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -14,8 +17,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.HumanName; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -23,6 +26,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -37,15 +41,24 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchDefaultMethodDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchDefaultMethodDstu3Test.class); private static int ourPort; - private static Server ourServer; private static String ourLastMethod; private static StringAndListParam ourLastParam1; private static StringAndListParam ourLastParam2; + + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -56,7 +69,7 @@ public class SearchDefaultMethodDstu3Test { @Test public void testSearchNoParams() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -76,7 +89,7 @@ public class SearchDefaultMethodDstu3Test { @Test public void testSearchOneOptionalParam() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?param1=val1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?param1=val1"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -97,7 +110,7 @@ public class SearchDefaultMethodDstu3Test { @Test public void testSearchTwoOptionalParams() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?param1=val1¶m2=val2"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?param1=val1¶m2=val2"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -122,7 +135,7 @@ public class SearchDefaultMethodDstu3Test { @Test public void testSearchTwoOptionalParamsAndExtraParam() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?param1=val1¶m2=val2¶m3=val3&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?param1=val1¶m2=val2¶m3=val3&_pretty=true"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -151,7 +164,7 @@ public class SearchDefaultMethodDstu3Test { @Test public void testSearchTwoOptionalParamsWithQualifierAndExtraParam() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?param1=val1¶m2=val2¶m2:exact=val2e¶m3=val3&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?param1=val1¶m2=val2¶m2:exact=val2e¶m3=val3&_pretty=true"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -181,34 +194,9 @@ public class SearchDefaultMethodDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - private static Map> ourLastAdditionalParams; public static class DummyPatientResourceProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchDstu3Test.java index 9ec3e18c12f..2a5ba4c17b7 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchDstu3Test.java @@ -12,34 +12,28 @@ import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; import ca.uhn.fhir.rest.gclient.StringClientParam; import ca.uhn.fhir.rest.param.TokenAndListParam; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.HumanName; import org.hl7.fhir.dstu3.model.OperationOutcome; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -50,14 +44,19 @@ import static org.junit.jupiter.api.Assertions.fail; public class SearchDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static TokenAndListParam ourIdentifiers; private static String ourLastMethod; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchDstu3Test.class); - private static int ourPort; - private static Server ourServer; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -67,7 +66,7 @@ public class SearchDstu3Test { @Test public void testSearchNormal() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo%7Cbar"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier=foo%7Cbar"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -86,7 +85,7 @@ public class SearchDstu3Test { @Test public void testSearchWithInvalidChain() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier.chain=foo%7Cbar"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier.chain=foo%7Cbar"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -111,7 +110,7 @@ public class SearchDstu3Test { Bundle bundle; // Initial search - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo%7Cbar&_format=json"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier=foo%7Cbar&_format=json"); bundle = executeAndReturnLinkNext(httpGet, EncodingEnum.JSON); linkNext = bundle.getLink(Constants.LINK_NEXT).getUrl(); assertThat(linkNext, containsString("_format=json")); @@ -143,7 +142,7 @@ public class SearchDstu3Test { Bundle bundle; // Initial search - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo%7Cbar&_format=" + Constants.CT_FHIR_JSON_NEW); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier=foo%7Cbar&_format=" + Constants.CT_FHIR_JSON_NEW); bundle = executeAndReturnLinkNext(httpGet, EncodingEnum.JSON); linkNext = bundle.getLink(Constants.LINK_NEXT).getUrl(); assertThat(linkNext, containsString("_format=" + UrlUtil.escapeUrlParam(Constants.CT_FHIR_JSON_NEW))); @@ -175,7 +174,7 @@ public class SearchDstu3Test { Bundle bundle; // Initial search - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo%7Cbar&_format=xml"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier=foo%7Cbar&_format=xml"); bundle = executeAndReturnLinkNext(httpGet, EncodingEnum.XML); linkNext = bundle.getLink(Constants.LINK_NEXT).getUrl(); assertThat(linkNext, containsString("_format=xml")); @@ -207,7 +206,7 @@ public class SearchDstu3Test { Bundle bundle; // Initial search - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo%7Cbar"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier=foo%7Cbar"); bundle = executeAndReturnLinkNext(httpGet, EncodingEnum.JSON); linkNext = bundle.getLink(Constants.LINK_NEXT).getUrl(); assertThat(linkNext, not(containsString("_format"))); @@ -239,7 +238,7 @@ public class SearchDstu3Test { Bundle bundle; // Initial search - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo%7Cbar"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier=foo%7Cbar"); httpGet.addHeader(Constants.HEADER_ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); bundle = executeAndReturnLinkNext(httpGet, EncodingEnum.XML); linkNext = bundle.getLink(Constants.LINK_NEXT).getUrl(); @@ -290,7 +289,7 @@ public class SearchDstu3Test { @Test public void testSearchWithPostAndInvalidParameters() throws Exception { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl()); LoggingInterceptor interceptor = new LoggingInterceptor(); interceptor.setLogRequestSummary(true); interceptor.setLogRequestBody(true); @@ -320,35 +319,9 @@ public class SearchDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.JSON); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override @@ -362,13 +335,13 @@ public class SearchDstu3Test { @RequiredParam(name = Patient.SP_IDENTIFIER) TokenAndListParam theIdentifiers) { ourLastMethod = "search"; ourIdentifiers = theIdentifiers; - ArrayList retVal = new ArrayList(); + ArrayList retVal = new ArrayList<>(); for (int i = 0; i < 200; i++) { Patient patient = new Patient(); patient.addName(new HumanName().setFamily("FAMILY")); patient.getIdElement().setValue("Patient/" + i); - retVal.add((Patient) patient); + retVal.add(patient); } return retVal; } diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamDstu3Test.java index 17af852a1cf..7346bc7a7f5 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamDstu3Test.java @@ -6,7 +6,9 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.param.HasAndListParam; import ca.uhn.fhir.rest.param.HasParam; import ca.uhn.fhir.rest.param.TokenParam; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -15,8 +17,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.HumanName; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -24,6 +26,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -33,14 +36,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchHasParamDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchHasParamDstu3Test.class); - private static int ourPort; - private static Server ourServer; private static String ourLastMethod; private static HasAndListParam ourLastParam; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -49,7 +58,7 @@ public class SearchHasParamDstu3Test { @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_has:Encounter:patient:type=SURG"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_has:Encounter:patient:type=SURG"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -66,34 +75,9 @@ public class SearchHasParamDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchPostDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchPostDstu3Test.java index 323e3f2276b..154910aec81 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchPostDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchPostDstu3Test.java @@ -9,7 +9,9 @@ import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.SortSpec; import ca.uhn.fhir.rest.param.StringAndListParam; import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.collect.Lists; import org.apache.commons.io.IOUtils; @@ -22,8 +24,8 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.HumanName; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -32,8 +34,10 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.extension.RegisterExtension; + import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -54,22 +58,28 @@ public class SearchPostDstu3Test { } - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchPostDstu3Test.class); - private static int ourPort; - private static Server ourServer; private static String ourLastMethod; private static SortSpec ourLastSortSpec; private static StringAndListParam ourLastName; - private static RestfulServer ourServlet; + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { ourLastMethod = null; ourLastSortSpec = null; ourLastName = null; - ourServlet.getInterceptorService().unregisterAllInterceptors(); + ourServer.getInterceptorService().unregisterAllInterceptors(); } /** @@ -77,7 +87,7 @@ public class SearchPostDstu3Test { */ @Test public void testSearchWithMixedParamsNoInterceptorsYesParams() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search?_format=application/fhir+json"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/_search?_format=application/fhir+json"); httpPost.addHeader("Cache-Control","no-cache"); List parameters = Lists.newArrayList(); parameters.add(new BasicNameValuePair("name", "Smith")); @@ -108,7 +118,7 @@ public class SearchPostDstu3Test { */ @Test public void testSearchWithMixedParamsNoInterceptorsNoParams() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/_search"); httpPost.addHeader("Cache-Control","no-cache"); List parameters = Lists.newArrayList(); parameters.add(new BasicNameValuePair("name", "Smith")); @@ -139,9 +149,9 @@ public class SearchPostDstu3Test { */ @Test public void testSearchWithMixedParamsYesInterceptorsYesParams() throws Exception { - ourServlet.registerInterceptor(new ParamLoggingInterceptor()); + ourServer.registerInterceptor(new ParamLoggingInterceptor()); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search?_format=application/fhir+json"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/_search?_format=application/fhir+json"); httpPost.addHeader("Cache-Control","no-cache"); List parameters = Lists.newArrayList(); parameters.add(new BasicNameValuePair("name", "Smith")); @@ -172,9 +182,9 @@ public class SearchPostDstu3Test { */ @Test public void testSearchWithMixedParamsYesInterceptorsNoParams() throws Exception { - ourServlet.registerInterceptor(new ParamLoggingInterceptor()); + ourServer.registerInterceptor(new ParamLoggingInterceptor()); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/_search"); httpPost.addHeader("Cache-Control","no-cache"); List parameters = Lists.newArrayList(); parameters.add(new BasicNameValuePair("name", "Smith")); @@ -202,35 +212,9 @@ public class SearchPostDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - ourServlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchSortDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchSortDstu3Test.java index e225ad2feb0..ec1d974ec0f 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchSortDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchSortDstu3Test.java @@ -5,7 +5,9 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.annotation.Sort; import ca.uhn.fhir.rest.api.SortOrderEnum; import ca.uhn.fhir.rest.api.SortSpec; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -14,8 +16,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.HumanName; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -23,6 +25,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -32,14 +35,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchSortDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchSortDstu3Test.class); - private static int ourPort; - private static Server ourServer; private static String ourLastMethod; private static SortSpec ourLastSortSpec; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -48,7 +57,7 @@ public class SearchSortDstu3Test { @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_sort=param1,-param2,param3,-param4"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_sort=param1,-param2,param3,-param4"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -76,34 +85,9 @@ public class SearchSortDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu3Test.java index 96875620297..ed73903c2be 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListDstu3Test.java @@ -5,28 +5,22 @@ import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.HumanName; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -34,13 +28,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchWithGenericListDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithGenericListDstu3Test.class); - private static int ourPort; - private static Server ourServer; private static String ourLastMethod; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -51,7 +52,7 @@ public class SearchWithGenericListDstu3Test { */ @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier=foo&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -59,42 +60,17 @@ public class SearchWithGenericListDstu3Test { assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals("searchByIdentifier", ourLastMethod); assertThat(responseContent, containsString("")); + assertThat(responseContent, containsString("")); } @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setResourceProviders(patientProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } public static class DummyPatientResourceProvider implements IResourceProvider { @@ -109,7 +85,7 @@ public class SearchWithGenericListDstu3Test { public List searchByIdentifier( @RequiredParam(name=Patient.SP_IDENTIFIER) TokenParam theIdentifier) { ourLastMethod = "searchByIdentifier"; - ArrayList retVal = new ArrayList(); + ArrayList retVal = new ArrayList<>(); retVal.add((Patient) new Patient().addName(new HumanName().setFamily("FAMILY")).setId("1")); return retVal; } diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithIncludesDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithIncludesDstu3Test.java index 9a7d1db840b..555df4c1d6e 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithIncludesDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithIncludesDstu3Test.java @@ -5,7 +5,9 @@ import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.rest.annotation.IncludeParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -14,14 +16,15 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.Organization; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -35,15 +38,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchWithIncludesDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithIncludesDstu3Test.class); - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testSearchIncludesReferences() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true&_include=Patient:organization&_include=Organization:" + Organization.SP_PARTOF); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_pretty=true&_include=Patient:organization&_include=Organization:" + Organization.SP_PARTOF); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -63,37 +73,11 @@ public class SearchWithIncludesDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setResourceProviders(patientProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithServerAddressStrategyDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithServerAddressStrategyDstu3Test.java index 10ae6e87550..86b175194a2 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithServerAddressStrategyDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithServerAddressStrategyDstu3Test.java @@ -3,27 +3,21 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.HumanName; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -31,42 +25,48 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchWithServerAddressStrategyDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithServerAddressStrategyDstu3Test.class); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .setDefaultResponseEncoding(EncodingEnum.XML) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testIncomingRequestAddressStrategy() throws Exception { - ourServlet.setServerAddressStrategy(new IncomingRequestAddressStrategy()); + ourServer.setServerAddressStrategy(new IncomingRequestAddressStrategy()); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); ourLog.info(responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); assertThat(responseContent, containsString("")); + assertThat(responseContent, containsString("")); } @Test public void testApacheProxyAddressStrategy() throws Exception { - ourServlet.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttp()); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + ourServer.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttp()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); ourLog.info(responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); assertThat(responseContent, containsString("")); + assertThat(responseContent, containsString("")); - ourServlet.setServerAddressStrategy(new ApacheProxyAddressStrategy(false)); - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + ourServer.setServerAddressStrategy(new ApacheProxyAddressStrategy(false)); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); httpGet.addHeader("x-forwarded-host", "foo.com"); status = ourClient.execute(httpGet); responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -76,8 +76,8 @@ public class SearchWithServerAddressStrategyDstu3Test { assertThat(responseContent, containsString("")); - ourServlet.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttps()); - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + ourServer.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttps()); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); httpGet.addHeader("x-forwarded-host", "foo.com"); status = ourClient.execute(httpGet); responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -87,8 +87,8 @@ public class SearchWithServerAddressStrategyDstu3Test { assertThat(responseContent, containsString("")); - ourServlet.setServerAddressStrategy(new ApacheProxyAddressStrategy(false)); - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + ourServer.setServerAddressStrategy(new ApacheProxyAddressStrategy(false)); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); httpGet.addHeader("x-forwarded-host", "foo.com"); httpGet.addHeader("x-forwarded-proto", "https"); status = ourClient.execute(httpGet); @@ -103,9 +103,9 @@ public class SearchWithServerAddressStrategyDstu3Test { @Test public void testHardcodedAddressStrategy() throws Exception { - ourServlet.setServerAddressStrategy(new HardcodedServerAddressStrategy("http://example.com/fhir/base")); + ourServer.setServerAddressStrategy(new HardcodedServerAddressStrategy("http://example.com/fhir/base")); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -118,37 +118,10 @@ public class SearchWithServerAddressStrategyDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - ourServlet.setResourceProviders(patientProvider); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override @@ -159,7 +132,7 @@ public class SearchWithServerAddressStrategyDstu3Test { //@formatter:off @Search() public List searchByIdentifier() { - ArrayList retVal = new ArrayList(); + ArrayList retVal = new ArrayList<>(); retVal.add((Patient) new Patient().addName(new HumanName().addGiven("FAMILY")).setId("1")); retVal.add((Patient) new Patient().addName(new HumanName().addGiven("FAMILY")).setId("2")); return retVal; diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerExceptionDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerExceptionDstu3Test.java index 2b329c2b91d..0bf146ae48a 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerExceptionDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerExceptionDstu3Test.java @@ -9,11 +9,14 @@ import ca.uhn.fhir.interceptor.api.Pointcut; import ca.uhn.fhir.rest.annotation.Create; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; @@ -25,8 +28,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.OperationOutcome; import org.hl7.fhir.dstu3.model.OperationOutcome.IssueType; @@ -36,6 +39,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -51,11 +55,17 @@ public class ServerExceptionDstu3Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ServerExceptionDstu3Test.class); public static Exception ourException; - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @AfterEach public void after() { @@ -72,7 +82,7 @@ public class ServerExceptionDstu3Test { .addResponseHeader("X-Foo", "BAR BAR"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -100,7 +110,7 @@ public class ServerExceptionDstu3Test { ourException = new InternalErrorException("Error", operationOutcome); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=json"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { byte[] responseContentBytes = IOUtils.toByteArray(status.getEntity().getContent()); String responseContent = new String(responseContentBytes, Charsets.UTF_8); @@ -116,7 +126,7 @@ public class ServerExceptionDstu3Test { ourException = new NullPointerException("Hello"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=json"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { assertEquals(500, status.getStatusLine().getStatusCode()); byte[] responseContentBytes = IOUtils.toByteArray(status.getEntity().getContent()); @@ -133,7 +143,7 @@ public class ServerExceptionDstu3Test { ourException = new IOException("Hello"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=json"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { assertEquals(500, status.getStatusLine().getStatusCode()); byte[] responseContentBytes = IOUtils.toByteArray(status.getEntity().getContent()); @@ -148,14 +158,14 @@ public class ServerExceptionDstu3Test { @Test public void testInterceptorThrowsNonHapiUncheckedExceptionHandledCleanly() throws Exception { - ourServlet.getInterceptorService().registerAnonymousInterceptor(Pointcut.SERVER_INCOMING_REQUEST_PRE_HANDLED, new IAnonymousInterceptor() { + ourServer.getInterceptorService().registerAnonymousInterceptor(Pointcut.SERVER_INCOMING_REQUEST_PRE_HANDLED, new IAnonymousInterceptor() { @Override public void invoke(IPointcut thePointcut, HookParams theArgs) { throw new NullPointerException("Hello"); } }); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=json"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { assertEquals(500, status.getStatusLine().getStatusCode()); byte[] responseContentBytes = IOUtils.toByteArray(status.getEntity().getContent()); @@ -165,7 +175,7 @@ public class ServerExceptionDstu3Test { assertThat(responseContent, containsString("\"diagnostics\":\"Hello\"")); } - ourServlet.getInterceptorService().unregisterAllInterceptors(); + ourServer.getInterceptorService().unregisterAllInterceptors(); } @@ -173,7 +183,7 @@ public class ServerExceptionDstu3Test { @Test public void testPostWithNoBody() throws IOException { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(status.getStatusLine().toString()); @@ -194,7 +204,7 @@ public class ServerExceptionDstu3Test { ourException = new AuthenticationException().addAuthenticateHeaderForRealm("REALM"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(status.getStatusLine().toString()); @@ -231,32 +241,8 @@ public class ServerExceptionDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - ourServlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } } diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeDstu3Test.java index 258ecf21f3e..cdef78525ce 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeDstu3Test.java @@ -10,7 +10,9 @@ import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.client.MyPatientWithExtensions; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -25,8 +27,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.CapabilityStatement; import org.hl7.fhir.dstu3.model.CodeType; import org.hl7.fhir.dstu3.model.DateType; @@ -37,6 +39,7 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -51,16 +54,22 @@ import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.assertEquals; public class ServerMimetypeDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ServerMimetypeDstu3Test.class); - private static int ourPort; - private static Server ourServer; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testConformanceMetadataUsesNewMimetypes() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/metadata"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/metadata"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String content = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -91,7 +100,7 @@ public class ServerMimetypeDstu3Test { String enc = ourCtx.newXmlParser().encodeResourceToString(p); String expectedResponseContent = ""; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_XML + "; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -107,7 +116,7 @@ public class ServerMimetypeDstu3Test { @Test public void testHttpTraceNotEnabled() throws Exception { - HttpTrace req = new HttpTrace("http://localhost:" + ourPort + "/Patient"); + HttpTrace req = new HttpTrace(ourServer.getBaseUrl() + "/Patient"); CloseableHttpResponse status = ourClient.execute(req); try { ourLog.info(status.toString()); @@ -124,7 +133,7 @@ public class ServerMimetypeDstu3Test { public String getMethod() { return "TRACK"; }}; - req.setURI(new URI("http://localhost:" + ourPort + "/Patient")); + req.setURI(new URI(ourServer.getBaseUrl() + "/Patient")); CloseableHttpResponse status = ourClient.execute(req); try { @@ -142,7 +151,7 @@ public class ServerMimetypeDstu3Test { String enc = ourCtx.newXmlParser().encodeResourceToString(p); String expectedResponseContent = ""; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_XML_NEW + "; charset=utf-8"))); httpPost.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); HttpResponse status = ourClient.execute(httpPost); @@ -164,7 +173,7 @@ public class ServerMimetypeDstu3Test { String enc = ourCtx.newXmlParser().encodeResourceToString(p); String expectedResponseContent = ""; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_XML + "; charset=utf-8"))); httpPost.addHeader(Constants.HEADER_ACCEPT, Constants.CT_FHIR_XML_NEW); HttpResponse status = ourClient.execute(httpPost); @@ -186,7 +195,7 @@ public class ServerMimetypeDstu3Test { String enc = ourCtx.newJsonParser().encodeResourceToString(p); String expectedResponseContent = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\"},\"name\":[{\"family\":\"FAMILY\"}]}"; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_JSON + "; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -207,7 +216,7 @@ public class ServerMimetypeDstu3Test { String enc = ourCtx.newJsonParser().encodeResourceToString(p); String expectedResponseContent = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\"},\"name\":[{\"family\":\"FAMILY\"}]}"; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_JSON_NEW + "; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -228,7 +237,7 @@ public class ServerMimetypeDstu3Test { String enc = ourCtx.newJsonParser().encodeResourceToString(p); String expectedResponseContent = "{\"resourceType\":\"OperationOutcome\",\"issue\":[{\"diagnostics\":\"FAMILY\"}]}"; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_JSON + "; charset=utf-8"))); httpPost.addHeader(Constants.HEADER_ACCEPT, Constants.CT_FHIR_JSON_NEW); httpPost.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); @@ -247,7 +256,7 @@ public class ServerMimetypeDstu3Test { @Test public void testSearchWithFormatXmlSimple() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=xml"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=xml"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -264,7 +273,7 @@ public class ServerMimetypeDstu3Test { @Test public void testSearchWithFormatXmlLegacy() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_XML); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=" + Constants.CT_FHIR_XML); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -281,7 +290,7 @@ public class ServerMimetypeDstu3Test { @Test public void testSearchWithFormatXmlNew() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_XML_NEW); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=" + Constants.CT_FHIR_XML_NEW); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -300,7 +309,7 @@ public class ServerMimetypeDstu3Test { @Test public void testSearchWithFormatJsonSimple() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -316,7 +325,7 @@ public class ServerMimetypeDstu3Test { @Test public void testSearchWithFormatJsonLegacy() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_JSON); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=" + Constants.CT_FHIR_JSON); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -332,7 +341,7 @@ public class ServerMimetypeDstu3Test { @Test public void testSearchWithFormatJsonNew() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_JSON_NEW); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=" + Constants.CT_FHIR_JSON_NEW); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -347,33 +356,9 @@ public class ServerMimetypeDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } + public static class PatientProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerUsingOldTypesDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerUsingOldTypesDstu3Test.java index 45e3a4ecb9b..6cd10c180cc 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerUsingOldTypesDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ServerUsingOldTypesDstu3Test.java @@ -14,7 +14,7 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/UnclassifiedServerExceptionDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/UnclassifiedServerExceptionDstu3Test.java index 4e03d07bf6e..a2ca5a8680d 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/UnclassifiedServerExceptionDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/UnclassifiedServerExceptionDstu3Test.java @@ -2,8 +2,11 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.server.exceptions.UnclassifiedServerFailureException; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -12,8 +15,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.OperationOutcome; import org.hl7.fhir.dstu3.model.OperationOutcome.IssueType; import org.hl7.fhir.dstu3.model.Patient; @@ -21,6 +24,7 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.List; @@ -32,13 +36,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class UnclassifiedServerExceptionDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(UnclassifiedServerExceptionDstu3Test.class); - private static int ourPort; - private static Server ourServer; public static UnclassifiedServerFailureException ourException; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @Test public void testSearch() throws Exception { @@ -46,7 +57,7 @@ public class UnclassifiedServerExceptionDstu3Test { operationOutcome.addIssue().setCode(IssueType.BUSINESSRULE); ourException = new UnclassifiedServerFailureException(477, "SOME MESSAGE", operationOutcome); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -63,33 +74,9 @@ public class UnclassifiedServerExceptionDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } public static class DummyPatientResourceProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu3Test.java index c18f4175cee..844069431a2 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/ValidateDstu3Test.java @@ -8,7 +8,9 @@ import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.ValidationModeEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -20,8 +22,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.CodeType; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.OperationOutcome; @@ -33,6 +35,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -41,8 +44,7 @@ import static org.hamcrest.Matchers.stringContainsInOrder; import static org.junit.jupiter.api.Assertions.assertEquals; public class ValidateDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static EncodingEnum ourLastEncoding; private static IdType ourLastId; private static ValidationModeEnum ourLastMode; @@ -51,9 +53,17 @@ public class ValidateDstu3Test { private static String ourLastResourceBody; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ValidateDstu3Test.class); private static OperationOutcome ourOutcomeToReturn; - private static int ourPort; - private static Server ourServer; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new PatientProvider()) + .registerProvider(new OrganizationProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach() public void before() { @@ -74,7 +84,7 @@ public class ValidateDstu3Test { Parameters params = new Parameters(); params.addParameter().setName("resource").setResource(patient); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -97,7 +107,7 @@ public class ValidateDstu3Test { params.addParameter().setName("resource").setResource(patient); params.addParameter().setName("mode").setValue(new CodeType(" ")); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -118,7 +128,7 @@ public class ValidateDstu3Test { params.addParameter().setName("resource").setResource(patient); params.addParameter().setName("mode").setValue(new CodeType("AAA")); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -140,7 +150,7 @@ public class ValidateDstu3Test { Parameters params = new Parameters(); params.addParameter().setName("mode").setValue(new CodeType("create")); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -156,7 +166,7 @@ public class ValidateDstu3Test { ourOutcomeToReturn = new OperationOutcome(); ourOutcomeToReturn.addIssue().setDiagnostics("FOOBAR"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$validate"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/$validate"); HttpResponse status = ourClient.execute(httpGet); String resp = IOUtils.toString(status.getEntity().getContent()); @@ -180,7 +190,7 @@ public class ValidateDstu3Test { Parameters params = new Parameters(); params.addParameter().setName("resource").setResource(org); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Organization/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Organization/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_JSON, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -203,7 +213,7 @@ public class ValidateDstu3Test { params.addParameter().setName("profile").setValue(new StringType("http://foo")); params.addParameter().setName("mode").setValue(new StringType(ValidationModeEnum.CREATE.getCode())); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -231,7 +241,7 @@ public class ValidateDstu3Test { Parameters params = new Parameters(); params.addParameter().setName("resource").setResource(patient); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -245,32 +255,9 @@ public class ValidateDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider, new OrganizationProvider()); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } public static class OrganizationProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/BanUnsupprtedHttpMethodsInterceptorDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/BanUnsupprtedHttpMethodsInterceptorDstu3Test.java index a4296c69645..d5dcec14b98 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/BanUnsupprtedHttpMethodsInterceptorDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/BanUnsupprtedHttpMethodsInterceptorDstu3Test.java @@ -3,10 +3,15 @@ package ca.uhn.fhir.rest.server.interceptor; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.rest.server.CreateDstu3Test; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -19,13 +24,14 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.IdType; import org.hl7.fhir.dstu3.model.Patient; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.net.URI; import java.util.HashMap; @@ -38,17 +44,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class BanUnsupprtedHttpMethodsInterceptorDstu3Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu3(); + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BanUnsupprtedHttpMethodsInterceptorDstu3Test.class); - private static int ourPort; - private static Server ourServer; + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .registerInterceptor(new BanUnsupportedHttpMethodsInterceptor()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); - private static RestfulServer servlet; + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testHttpTraceNotEnabled() throws Exception { - HttpTrace req = new HttpTrace("http://localhost:" + ourPort + "/Patient"); + HttpTrace req = new HttpTrace(ourServer.getBaseUrl() + "/Patient"); CloseableHttpResponse status = ourClient.execute(req); try { ourLog.info(status.toString()); @@ -60,7 +71,7 @@ public class BanUnsupprtedHttpMethodsInterceptorDstu3Test { @Test public void testHeadJsonWithInvalidPatient() throws Exception { - HttpHead httpGet = new HttpHead("http://localhost:" + ourPort + "/Patient/123"); + HttpHead httpGet = new HttpHead(ourServer.getBaseUrl() + "/Patient/123"); HttpResponse status = ourClient.execute(httpGet); assertEquals(null, status.getEntity()); ourLog.info(status.toString()); @@ -71,7 +82,7 @@ public class BanUnsupprtedHttpMethodsInterceptorDstu3Test { @Test public void testHeadJsonWithValidPatient() throws Exception { - HttpHead httpGet = new HttpHead("http://localhost:" + ourPort + "/Patient/1"); + HttpHead httpGet = new HttpHead(ourServer.getBaseUrl() + "/Patient/1"); HttpResponse status = ourClient.execute(httpGet); assertEquals(null, status.getEntity()); ourLog.info(status.toString()); @@ -88,7 +99,7 @@ public class BanUnsupprtedHttpMethodsInterceptorDstu3Test { return "TRACK"; } }; - req.setURI(new URI("http://localhost:" + ourPort + "/Patient")); + req.setURI(new URI(ourServer.getBaseUrl() + "/Patient")); CloseableHttpResponse status = ourClient.execute(req); try { @@ -107,7 +118,7 @@ public class BanUnsupprtedHttpMethodsInterceptorDstu3Test { return "FOO"; } }; - req.setURI(new URI("http://localhost:" + ourPort + "/Patient")); + req.setURI(new URI(ourServer.getBaseUrl() + "/Patient")); CloseableHttpResponse status = ourClient.execute(req); try { @@ -121,7 +132,7 @@ public class BanUnsupprtedHttpMethodsInterceptorDstu3Test { @Test public void testRead() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -130,33 +141,9 @@ public class BanUnsupprtedHttpMethodsInterceptorDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - servlet = new RestfulServer(ourCtx); - - servlet.setResourceProviders(new DummyPatientResourceProvider()); - servlet.registerInterceptor(new BanUnsupportedHttpMethodsInterceptor()); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { private Patient createPatient1() { diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/CorsInterceptorDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/CorsInterceptorDstu3Test.java index 5098740f1b5..6255287bcfc 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/CorsInterceptorDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/CorsInterceptorDstu3Test.java @@ -28,8 +28,8 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.Enumerations.AdministrativeGender; import org.hl7.fhir.dstu3.model.HumanName; diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/auth/AuthorizationInterceptorDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/auth/AuthorizationInterceptorDstu3Test.java index 6d3a2777a34..25fa2bb8d1d 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/auth/AuthorizationInterceptorDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/interceptor/auth/AuthorizationInterceptorDstu3Test.java @@ -19,7 +19,9 @@ import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; @@ -31,9 +33,10 @@ import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu3.model.Binary; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.CarePlan; @@ -52,6 +55,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,27 +70,25 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class AuthorizationInterceptorDstu3Test { - private static final String ERR403 = "{\"resourceType\":\"OperationOutcome\",\"issue\":[{\"severity\":\"error\",\"code\":\"processing\",\"diagnostics\":\"Access denied by default policy (no applicable rules)\"}]}"; - private static final Logger ourLog = LoggerFactory.getLogger(AuthorizationInterceptorDstu3Test.class); - private static CloseableHttpClient ourClient; - private static String ourConditionalCreateId; - private static FhirContext ourCtx = FhirContext.forDstu3(); - private static boolean ourHitMethod; - private static int ourPort; + private static final FhirContext ourCtx = FhirContext.forDstu3Cached(); private static List ourReturn; private static List ourDeleted; - private static Server ourServer; - private static RestfulServer ourServlet; + + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PlainProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { ourCtx.setAddProfileTagWhenEncoding(AddProfileTagEnum.NEVER); - ourServlet.getInterceptorService().unregisterAllInterceptors(); - ourServlet.setTenantIdentificationStrategy(null); + ourServer.getInterceptorService().unregisterAllInterceptors(); + ourServer.getRestfulServer().setTenantIdentificationStrategy(null); ourReturn = null; ourDeleted = null; - ourHitMethod = false; - ourConditionalCreateId = "1123"; } private Resource createCarePlan(Integer theId, String theSubjectId) { @@ -176,7 +178,7 @@ public class AuthorizationInterceptorDstu3Test { @Test public void testTransactionWithPatch() throws IOException { - ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { + ourServer.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) { @Override public List buildRuleList(RequestDetails theRequestDetails) { return new RuleBuilder() @@ -207,7 +209,7 @@ public class AuthorizationInterceptorDstu3Test { responseBundle.setType(Bundle.BundleType.TRANSACTION); ourReturn = Collections.singletonList(responseBundle); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl()); httpPost.setEntity(createFhirResourceEntity(requestBundle)); CloseableHttpResponse status = ourClient.execute(httpPost); String resp = extractResponseAndClose(status); @@ -220,31 +222,26 @@ public class AuthorizationInterceptorDstu3Test { @History() public List history() { - ourHitMethod = true; return (ourReturn); } @Operation(name = "opName", idempotent = true) public Parameters operation() { - ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } @Operation(name = "process-message", idempotent = true) public Parameters processMessage(@OperationParam(name = "content") Bundle theInput) { - ourHitMethod = true; return (Parameters) new Parameters().setId("1"); } @GraphQL public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQueryUrl String theQuery) { - ourHitMethod = true; return "{'foo':'bar'}"; } @Transaction() public Bundle search(ServletRequestDetails theRequestDetails, IInterceptorBroadcaster theInterceptorBroadcaster, @TransactionParam Bundle theInput) { - ourHitMethod = true; if (ourDeleted != null) { for (IBaseResource next : ourDeleted) { HookParams params = new HookParams() @@ -261,34 +258,8 @@ public class AuthorizationInterceptorDstu3Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PlainProvider plainProvider = new PlainProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.setFhirContext(ourCtx); - ourServlet.registerProvider(plainProvider); - ourServlet.setPagingProvider(new FifoMemoryPagingProvider(100)); - ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-dstu3/src/test/java/org/hl7/fhir/dstu3/hapi/rest/server/PatientResourceProvider.java b/hapi-fhir-structures-dstu3/src/test/java/org/hl7/fhir/dstu3/hapi/rest/server/PatientResourceProvider.java index 08c67a17007..7cefdb1a833 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/org/hl7/fhir/dstu3/hapi/rest/server/PatientResourceProvider.java +++ b/hapi-fhir-structures-dstu3/src/test/java/org/hl7/fhir/dstu3/hapi/rest/server/PatientResourceProvider.java @@ -27,7 +27,7 @@ public class PatientResourceProvider implements IResourceProvider @Search() public IBundleProvider search( - javax.servlet.http.HttpServletRequest theServletRequest, + jakarta.servlet.http.HttpServletRequest theServletRequest, @Description(shortDefinition="The resource identity") @OptionalParam(name="_id") diff --git a/hapi-fhir-structures-dstu3/src/test/java/org/hl7/fhir/dstu3/hapi/rest/server/ServerCapabilityStatementProviderDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/org/hl7/fhir/dstu3/hapi/rest/server/ServerCapabilityStatementProviderDstu3Test.java index 916c47c286b..a88043940cf 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/org/hl7/fhir/dstu3/hapi/rest/server/ServerCapabilityStatementProviderDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/org/hl7/fhir/dstu3/hapi/rest/server/ServerCapabilityStatementProviderDstu3Test.java @@ -74,9 +74,9 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -970,7 +970,7 @@ public class ServerCapabilityStatementProviderDstu3Test { public static class MultiTypeEncounterProvider implements IResourceProvider { @Operation(name = "someOp") - public IBundleProvider everything(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, + public IBundleProvider everything(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @OperationParam(name = "someOpParam1") DateType theStart, @OperationParam(name = "someOpParam2") Encounter theEnd) { return null; } @@ -981,7 +981,7 @@ public class ServerCapabilityStatementProviderDstu3Test { } @Validate - public IBundleProvider validate(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @ResourceParam Encounter thePatient) { + public IBundleProvider validate(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @ResourceParam Encounter thePatient) { return null; } @@ -991,7 +991,7 @@ public class ServerCapabilityStatementProviderDstu3Test { public static class MultiTypePatientProvider implements IResourceProvider { @Operation(name = "someOp") - public IBundleProvider everything(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, + public IBundleProvider everything(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @OperationParam(name = "someOpParam1") DateType theStart, @OperationParam(name = "someOpParam2") Patient theEnd) { return null; } @@ -1002,7 +1002,7 @@ public class ServerCapabilityStatementProviderDstu3Test { } @Validate - public IBundleProvider validate(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @ResourceParam Patient thePatient) { + public IBundleProvider validate(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @ResourceParam Patient thePatient) { return null; } @@ -1037,7 +1037,7 @@ public class ServerCapabilityStatementProviderDstu3Test { public static class PlainProviderWithExtendedOperationOnNoType { @Operation(name = "plain", idempotent = true, returnParameters = { @OperationParam(min = 1, max = 2, name = "out1", type = StringType.class) }) - public IBundleProvider everything(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @OperationParam(name = "start") DateType theStart, + public IBundleProvider everything(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @OperationParam(name = "start") DateType theStart, @OperationParam(name = "end") DateType theEnd) { return null; } @@ -1048,7 +1048,7 @@ public class ServerCapabilityStatementProviderDstu3Test { public static class ProviderWithExtendedOperationReturningBundle implements IResourceProvider { @Operation(name = "everything", idempotent = true) - public IBundleProvider everything(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @OperationParam(name = "start") DateType theStart, + public IBundleProvider everything(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @OperationParam(name = "start") DateType theStart, @OperationParam(name = "end") DateType theEnd) { return null; } diff --git a/hapi-fhir-structures-hl7org-dstu2/pom.xml b/hapi-fhir-structures-hl7org-dstu2/pom.xml index 4f4e5b841be..1b297a905e9 100644 --- a/hapi-fhir-structures-hl7org-dstu2/pom.xml +++ b/hapi-fhir-structures-hl7org-dstu2/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -32,6 +32,13 @@ ${fhir_core_version} + + jakarta.servlet + jakarta.servlet-api + provided + true + + @@ -59,17 +66,6 @@ true - - - javax.servlet - servlet-api - 2.5 - true - - org.ogce xpp3 @@ -103,36 +99,6 @@ xmlunit-core test - - org.eclipse.jetty - jetty-servlets - test - - - org.eclipse.jetty - jetty-servlet - test - - - org.eclipse.jetty - jetty-server - test - - - org.eclipse.jetty - jetty-util - test - - - org.eclipse.jetty - jetty-webapp - test - - - org.eclipse.jetty - jetty-http - test - ch.qos.logback logback-classic @@ -153,23 +119,18 @@ - com.helger - ph-schematron + com.helger.schematron + ph-schematron-api test - com.helger - ph-commons + com.helger.schematron + ph-schematron-xslt test - javax.activation - javax.activation-api - test - - - javax.xml.bind - jaxb-api + jakarta.activation + jakarta.activation-api test @@ -295,7 +256,7 @@ --> - javax.servlet*;resolution:=optional, + jakarta.servlet*;resolution:=optional, * diff --git a/hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/dstu2/hapi/rest/server/ServerConformanceProvider.java b/hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/dstu2/hapi/rest/server/ServerConformanceProvider.java index 4a6aaae718a..49315d13b8d 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/dstu2/hapi/rest/server/ServerConformanceProvider.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/dstu2/hapi/rest/server/ServerConformanceProvider.java @@ -43,6 +43,8 @@ import ca.uhn.fhir.rest.server.method.OperationParameter; import ca.uhn.fhir.rest.server.method.SearchMethodBinding; import ca.uhn.fhir.rest.server.method.SearchParameter; import ca.uhn.fhir.rest.server.util.BaseServerCapabilityStatementProvider; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.dstu2.model.Conformance; import org.hl7.fhir.dstu2.model.Conformance.*; @@ -58,8 +60,6 @@ import org.hl7.fhir.instance.model.api.IPrimitiveType; import java.util.Map.Entry; import java.util.*; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; import static org.apache.commons.lang3.StringUtils.isNotBlank; diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryHl7OrgDstu2Test.java index b2bf88b0eb1..fe89591728f 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/BinaryHl7OrgDstu2Test.java @@ -9,7 +9,10 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; @@ -20,8 +23,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.Binary; import org.hl7.fhir.dstu2.model.IdType; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -29,6 +32,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.Collections; import java.util.List; @@ -45,12 +49,18 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class BinaryHl7OrgDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BinaryHl7OrgDstu2Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); private static Binary ourLast; - private static int ourPort; - private static Server ourServer; + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new ResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -59,7 +69,7 @@ public class BinaryHl7OrgDstu2Test { @Test public void testReadWithExplicitTypeXml() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary/foo?_format=xml"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Binary/foo?_format=xml"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), "UTF-8"); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -76,7 +86,7 @@ public class BinaryHl7OrgDstu2Test { @Test public void testReadWithExplicitTypeJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary/foo?_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Binary/foo?_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), "UTF-8"); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -94,7 +104,7 @@ public class BinaryHl7OrgDstu2Test { @Test public void testCreate() throws Exception { - HttpPost http = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost http = new HttpPost(ourServer.getBaseUrl() + "/Binary"); http.setEntity(new ByteArrayEntity(new byte[]{1, 2, 3, 4}, ContentType.create("foo/bar", "UTF-8"))); HttpResponse status = ourClient.execute(http); @@ -107,7 +117,7 @@ public class BinaryHl7OrgDstu2Test { @Test public void testRead() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary/foo"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Binary/foo"); HttpResponse status = ourClient.execute(httpGet); byte[] responseContent = IOUtils.toByteArray(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -119,7 +129,7 @@ public class BinaryHl7OrgDstu2Test { @Test public void testSearchJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary?_pretty=true&_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Binary?_pretty=true&_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -137,7 +147,7 @@ public class BinaryHl7OrgDstu2Test { @Test public void testSearchXml() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Binary?_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -191,30 +201,7 @@ public class BinaryHl7OrgDstu2Test { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ResourceProvider patientProvider = new ResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - + TestUtil.randomizeLocaleAndTimezone(); } } diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseHl7OrgTest.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseHl7OrgTest.java index 734e011c748..12341610839 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseHl7OrgTest.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/BundleTypeInResponseHl7OrgTest.java @@ -4,7 +4,10 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.narrative.DefaultThymeleafNarrativeGenerator; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; @@ -12,13 +15,14 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.Bundle.BundleType; import org.hl7.fhir.dstu2.model.Patient; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -29,14 +33,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class BundleTypeInResponseHl7OrgTest { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BundleTypeInResponseHl7OrgTest.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); - private static int ourPort; - private static Server ourServer; + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); + + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -71,32 +82,7 @@ public class BundleTypeInResponseHl7OrgTest { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.getFhirContext().setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator()); - servlet.setResourceProviders(patientProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - + TestUtil.randomizeLocaleAndTimezone(); } } diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/CreateConditionalHl7OrgTest.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/CreateConditionalHl7OrgTest.java index d14a0e629c9..38103382829 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/CreateConditionalHl7OrgTest.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/CreateConditionalHl7OrgTest.java @@ -10,8 +10,12 @@ import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; @@ -22,14 +26,15 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.IdType; import org.hl7.fhir.dstu2.model.Patient; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -43,18 +48,23 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * Created by dsotnikov on 2/25/2014. */ public class CreateConditionalHl7OrgTest { - private static CloseableHttpClient ourClient; - private static String ourLastConditionalUrl; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CreateConditionalHl7OrgTest.class); - private static int ourPort; - private static Server ourServer; private static IdType ourLastId; private static IdType ourLastIdParam; private static boolean ourLastRequestWasSearch; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); - - + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); + + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { @@ -70,7 +80,7 @@ public class CreateConditionalHl7OrgTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?identifier=system%7C001"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -82,8 +92,8 @@ public class CreateConditionalHl7OrgTest { ourLog.info("Response was:\n{}", responseContent); assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); assertNull(ourLastId.getValue()); assertNull(ourLastIdParam); @@ -97,7 +107,7 @@ public class CreateConditionalHl7OrgTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient?_format=true&_pretty=true"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient?_format=true&_pretty=true"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -108,8 +118,8 @@ public class CreateConditionalHl7OrgTest { ourLog.info("Response was:\n{}", responseContent); assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); assertNull(ourLastId.getValue()); assertNull(ourLastIdParam); @@ -123,7 +133,7 @@ public class CreateConditionalHl7OrgTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_pretty=true"); HttpResponse status = ourClient.execute(httpGet); @@ -142,32 +152,10 @@ public class CreateConditionalHl7OrgTest { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); + TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalHl7OrgTest.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalHl7OrgTest.java index 1722aa1034b..6ca5d14e60a 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalHl7OrgTest.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalHl7OrgTest.java @@ -4,22 +4,27 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; import ca.uhn.fhir.rest.annotation.Delete; import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.IdType; import org.hl7.fhir.dstu2.model.Patient; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -30,16 +35,23 @@ import static org.junit.jupiter.api.Assertions.assertNull; * Created by dsotnikov on 2/25/2014. */ public class DeleteConditionalHl7OrgTest { - private static CloseableHttpClient ourClient; private static String ourLastConditionalUrl; - private static int ourPort; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); - private static Server ourServer; + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); private static IdType ourLastIdParam; - - - - @BeforeEach + + + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + + + @BeforeEach public void before() { ourLastConditionalUrl = null; ourLastIdParam = null; @@ -50,7 +62,7 @@ public class DeleteConditionalHl7OrgTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpDelete httpPost = new HttpDelete("http://localhost:" + ourPort + "/Patient?identifier=system%7C001"); + HttpDelete httpPost = new HttpDelete(ourServer.getBaseUrl() + "/Patient?identifier=system%7C001"); HttpResponse status = ourClient.execute(httpPost); @@ -66,7 +78,7 @@ public class DeleteConditionalHl7OrgTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpDelete httpPost = new HttpDelete("http://localhost:" + ourPort + "/Patient/2"); + HttpDelete httpPost = new HttpDelete(ourServer.getBaseUrl() + "/Patient/2"); HttpResponse status = ourClient.execute(httpPost); @@ -78,32 +90,10 @@ public class DeleteConditionalHl7OrgTest { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); + TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeAndRevincludeParameterHl7OrgTest.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeAndRevincludeParameterHl7OrgTest.java index 6528c42fb52..2cf3d0a2737 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeAndRevincludeParameterHl7OrgTest.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeAndRevincludeParameterHl7OrgTest.java @@ -5,7 +5,11 @@ import ca.uhn.fhir.context.api.BundleInclusionRule; import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.rest.annotation.IncludeParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; @@ -13,13 +17,14 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.Patient; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -33,14 +38,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class IncludeAndRevincludeParameterHl7OrgTest { - private static CloseableHttpClient ourClient; - private static int ourPort; - private static Server ourServer; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); private static Set ourIncludes; private static Set ourReverseIncludes; - @BeforeEach + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .withServer(s->s.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + + @BeforeEach public void before() { ourIncludes = null; ourReverseIncludes = null; @@ -48,7 +61,7 @@ public class IncludeAndRevincludeParameterHl7OrgTest { @Test public void testNoIncludes() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=normalInclude"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=normalInclude"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -60,7 +73,7 @@ public class IncludeAndRevincludeParameterHl7OrgTest { @Test public void testWithBoth() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=normalInclude&_include=A.a&_include=B.b&_revinclude=C.c&_revinclude=D.d"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=normalInclude&_include=A.a&_include=B.b&_revinclude=C.c&_revinclude=D.d"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -74,30 +87,7 @@ public class IncludeAndRevincludeParameterHl7OrgTest { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } - - @BeforeAll - public static void beforeClass() throws Exception { - - ourCtx = FhirContext.forDstu2Hl7Org(); - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(new DummyPatientResourceProvider()); - servlet.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - + TestUtil.randomizeLocaleAndTimezone(); } public static class DummyPatientResourceProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeHl7OrgDstu2Test.java index 39899c6b19c..362cf19d653 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/IncludeHl7OrgDstu2Test.java @@ -11,17 +11,13 @@ import ca.uhn.fhir.rest.annotation.IncludeParam; import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.ElementUtil; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.Bundle; import org.hl7.fhir.dstu2.model.Bundle.SearchEntryMode; import org.hl7.fhir.dstu2.model.DiagnosticReport; @@ -31,9 +27,9 @@ import org.hl7.fhir.dstu2.model.Organization; import org.hl7.fhir.dstu2.model.Patient; import org.hl7.fhir.dstu2.model.Practitioner; import org.hl7.fhir.dstu2.model.Reference; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.Arrays; @@ -41,7 +37,6 @@ import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -50,14 +45,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class IncludeHl7OrgDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(IncludeHl7OrgDstu2Test.class); - private static CloseableHttpClient ourClient; - private static int ourPort; - private static Server ourServer; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); + + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false) + .withServer(s->s.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE)); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testNoIncludes() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -73,7 +76,7 @@ public class IncludeHl7OrgDstu2Test { @Test public void testOneIncludeXml() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -93,7 +96,7 @@ public class IncludeHl7OrgDstu2Test { @Test public void testOneIncludeJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo&_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo&_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -113,7 +116,7 @@ public class IncludeHl7OrgDstu2Test { @Test public void testIIncludedResourcesNonContained() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=normalInclude&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=normalInclude&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -139,7 +142,7 @@ public class IncludeHl7OrgDstu2Test { @Test public void testIIncludedResourcesNonContainedInExtension() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=extInclude&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=extInclude&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -165,7 +168,7 @@ public class IncludeHl7OrgDstu2Test { @Test public void testIIncludedResourcesNonContainedInExtensionJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=extInclude&_pretty=true&_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=extInclude&_pretty=true&_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -191,7 +194,7 @@ public class IncludeHl7OrgDstu2Test { @Test public void testIIncludedResourcesNonContainedInDeclaredExtension() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=declaredExtInclude&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=declaredExtInclude&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -219,7 +222,7 @@ public class IncludeHl7OrgDstu2Test { @Test public void testTwoInclude() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo&_include=bar&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo&_include=bar&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -243,7 +246,7 @@ public class IncludeHl7OrgDstu2Test { @Test public void testBadInclude() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo&_include=baz"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo&_include=baz"); HttpResponse status = ourClient.execute(httpGet); assertEquals(400, status.getStatusLine().getStatusCode()); } @@ -435,33 +438,7 @@ public class IncludeHl7OrgDstu2Test { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } - - @BeforeAll - public static void beforeClass() throws Exception { - - ourCtx = FhirContext.forDstu2Hl7Org(); - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider, new DummyDiagnosticReportResourceProvider()); - servlet.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - + TestUtil.randomizeLocaleAndTimezone(); } } diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationDuplicateServerHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationDuplicateServerHl7OrgDstu2Test.java index 885e0427105..4a7f6762ef5 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationDuplicateServerHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationDuplicateServerHl7OrgDstu2Test.java @@ -5,7 +5,10 @@ import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.system.HapiSystemProperties; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; @@ -13,8 +16,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.Conformance; import org.hl7.fhir.dstu2.model.OperationDefinition; import org.hl7.fhir.dstu2.model.Organization; @@ -25,6 +28,7 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -32,20 +36,29 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class OperationDuplicateServerHl7OrgDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationDuplicateServerHl7OrgDstu2Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; - private static int ourPort; - private static Server ourServer; + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); static { HapiSystemProperties.enableTestMode(); } + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .registerProvider(new OrganizationProvider()) + .registerProvider(new PlainProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + @Test public void testOperationsAreCollapsed() throws Exception { // Metadata { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/metadata?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/metadata?_pretty=true"); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -64,7 +77,7 @@ public class OperationDuplicateServerHl7OrgDstu2Test { // OperationDefinition { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/OperationDefinition/OrganizationPatient-ts-myoperation?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/OperationDefinition/OrganizationPatient-ts-myoperation?_pretty=true"); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -118,34 +131,7 @@ public class OperationDuplicateServerHl7OrgDstu2Test { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu2Hl7Org(); - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(new PatientProvider(), new OrganizationProvider()); - servlet.setPlainProviders(new PlainProvider()); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - + TestUtil.randomizeLocaleAndTimezone(); } } diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerHl7OrgTest.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerHl7OrgTest.java index 43577d3d6b3..adc247aa472 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerHl7OrgTest.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/OperationServerHl7OrgTest.java @@ -8,7 +8,10 @@ import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.IBundleProvider; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse; @@ -20,8 +23,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.Bundle; import org.hl7.fhir.dstu2.model.IdType; import org.hl7.fhir.dstu2.model.IntegerType; @@ -33,6 +36,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -47,16 +51,24 @@ import static org.junit.jupiter.api.Assertions.assertNull; public class OperationServerHl7OrgTest { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationServerHl7OrgTest.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); private static StringType ourLastParam1; private static Patient ourLastParam2; - private static int ourPort; private static IdType ourLastId; - private static Server ourServer; private static String ourLastMethod; private static List ourLastParam3; + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .registerProvider(new PlainProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastParam1 = null; @@ -73,7 +85,7 @@ public class OperationServerHl7OrgTest { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -91,7 +103,7 @@ public class OperationServerHl7OrgTest { @Test public void testOperationWithGetUsingParams() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$OP_TYPE?PARAM1=PARAM1val"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$OP_TYPE?PARAM1=PARAM1val"); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -108,7 +120,7 @@ public class OperationServerHl7OrgTest { @Test public void testOperationWithGetUsingParamsFailsWithNonPrimitive() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$OP_TYPE?PARAM1=PARAM1val&PARAM2=foo"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$OP_TYPE?PARAM1=PARAM1val&PARAM2=foo"); HttpResponse status = ourClient.execute(httpGet); assertEquals(405, status.getStatusLine().getStatusCode()); @@ -126,7 +138,7 @@ public class OperationServerHl7OrgTest { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_TYPE_RET_BUNDLE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_TYPE_RET_BUNDLE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -149,7 +161,7 @@ public class OperationServerHl7OrgTest { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/$OP_SERVER"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/$OP_SERVER"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -167,7 +179,7 @@ public class OperationServerHl7OrgTest { @Test public void testOperationWithBundleProviderResponse() throws Exception { - HttpGet httpPost = new HttpGet("http://localhost:" + ourPort + "/$OP_INSTANCE_BUNDLE_PROVIDER?_pretty=true"); + HttpGet httpPost = new HttpGet(ourServer.getBaseUrl() + "/$OP_INSTANCE_BUNDLE_PROVIDER?_pretty=true"); HttpResponse status = ourClient.execute(httpPost); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -187,7 +199,7 @@ public class OperationServerHl7OrgTest { p.addParameter().setName("PARAM3").setValue(new StringType("PARAM3val2")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/$OP_SERVER_LIST_PARAM"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/$OP_SERVER_LIST_PARAM"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -213,7 +225,7 @@ public class OperationServerHl7OrgTest { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -232,7 +244,7 @@ public class OperationServerHl7OrgTest { @Test public void testOperationCantUseGetIfItIsntIdempotent() throws Exception { - HttpGet httpPost = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE"); + HttpGet httpPost = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); HttpResponse status = ourClient.execute(httpPost); assertEquals(Constants.STATUS_HTTP_405_METHOD_NOT_ALLOWED, status.getStatusLine().getStatusCode()); @@ -250,7 +262,7 @@ public class OperationServerHl7OrgTest { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -266,7 +278,7 @@ public class OperationServerHl7OrgTest { @Test public void testReadWithOperations() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123"); HttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -280,7 +292,7 @@ public class OperationServerHl7OrgTest { String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(new Parameters()); // Try with a POST - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$everything"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$everything"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -296,7 +308,7 @@ public class OperationServerHl7OrgTest { @Test public void testInstanceEverythingHapiClient() throws Exception { - Parameters p = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort).operation().onInstance(new IdType("Patient/123")).named("$everything").withParameters(new Parameters()).execute(); + Parameters p = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl()).operation().onInstance(new IdType("Patient/123")).named("$everything").withParameters(new Parameters()).execute(); Bundle b = (Bundle) p.getParameter().get(0).getResource(); assertNotNull(b); @@ -309,7 +321,7 @@ public class OperationServerHl7OrgTest { public void testInstanceEverythingGet() throws Exception { // Try with a GET - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$everything"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/$everything"); CloseableHttpResponse status = ourClient.execute(httpGet); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -473,34 +485,8 @@ public class OperationServerHl7OrgTest { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); + TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forDstu2Hl7Org(); - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(new PatientProvider()); - servlet.setPlainProviders(new PlainProvider()); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } } diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/PreferHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/PreferHl7OrgDstu2Test.java index 57c3ad93858..92be0bbb272 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/PreferHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/PreferHl7OrgDstu2Test.java @@ -6,8 +6,12 @@ import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Update; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; @@ -17,13 +21,14 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.IdType; import org.hl7.fhir.dstu2.model.Patient; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -33,21 +38,28 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * Created by dsotnikov on 2/25/2014. */ public class PreferHl7OrgDstu2Test { - private static CloseableHttpClient ourClient; - + private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(PreferHl7OrgDstu2Test.class); - private static int ourPort; - private static Server ourServer; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); - - - @Test + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); + + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + + + @Test public void testCreateWithNoPrefer() throws Exception { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -58,8 +70,8 @@ public class PreferHl7OrgDstu2Test { ourLog.info("Response was:\n{}", responseContent); assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); } @@ -68,32 +80,10 @@ public class PreferHl7OrgDstu2Test { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); + TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ReadHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ReadHl7OrgDstu2Test.java index 1a13e271050..890df560551 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ReadHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ReadHl7OrgDstu2Test.java @@ -3,22 +3,17 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.extension.RegisterExtension; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -26,17 +21,24 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class ReadHl7OrgDstu2Test { - private static CloseableHttpClient ourClient; - private static int ourPort; - private static Server ourServer; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); - - /** + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); + + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + + /** * In DSTU2+ the resource ID appears in the resource body */ @Test public void testReadXml() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123&_format=xml"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123&_format=xml"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -51,7 +53,7 @@ public class ReadHl7OrgDstu2Test { */ @Test public void testReadJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123&_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123&_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -63,30 +65,7 @@ public class ReadHl7OrgDstu2Test { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - + TestUtil.randomizeLocaleAndTimezone(); } /** diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchHl7OrgDstu2Test.java index a2a9ddf740b..ccc5109eb02 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchHl7OrgDstu2Test.java @@ -6,7 +6,10 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.IBundleProvider; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; @@ -14,14 +17,15 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.Bundle; import org.hl7.fhir.dstu2.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import javax.annotation.Nonnull; import java.util.List; @@ -38,17 +42,22 @@ import static org.junit.jupiter.api.Assertions.assertNull; public class SearchHl7OrgDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchHl7OrgDstu2Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); - private static int ourPort; - + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); private static InstantDt ourReturnPublished; - private static Server ourServer; + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testEncodeConvertsReferencesToRelative() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithRef"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithRef"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -65,7 +74,7 @@ public class SearchHl7OrgDstu2Test { @Test public void testEncodeConvertsReferencesToRelativeJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithRef&_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithRef&_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -82,7 +91,7 @@ public class SearchHl7OrgDstu2Test { @Test public void testResultBundleHasUuid() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithRef"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithRef"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -97,7 +106,7 @@ public class SearchHl7OrgDstu2Test { ourReturnPublished = new InstantDt("2011-02-03T11:22:33Z"); assertEquals(ourReturnPublished.getValueAsString(), "2011-02-03T11:22:33Z"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithBundleProvider&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithBundleProvider&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -153,7 +162,7 @@ public class SearchHl7OrgDstu2Test { public Patient searchWithRef() { Patient patient = new Patient(); patient.setId("Patient/1/_history/1"); - patient.getManagingOrganization().setReference("http://localhost:" + ourPort + "/Organization/555/_history/666"); + patient.getManagingOrganization().setReference(ourServer.getBaseUrl() + "/Organization/555/_history/666"); return patient; } @@ -161,31 +170,7 @@ public class SearchHl7OrgDstu2Test { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - + TestUtil.randomizeLocaleAndTimezone(); } } diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListHl7OrgDstu2Test.java index af3acf25d3d..a288b8217c0 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithGenericListHl7OrgDstu2Test.java @@ -5,28 +5,22 @@ import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.TokenParam; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.HumanName; import org.hl7.fhir.dstu2.model.Patient; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -35,12 +29,19 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchWithGenericListHl7OrgDstu2Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithGenericListHl7OrgDstu2Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); - private static int ourPort; - private static Server ourServer; + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); private static String ourLastMethod; + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -51,7 +52,7 @@ public class SearchWithGenericListHl7OrgDstu2Test { */ @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?identifier=foo&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?identifier=foo&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -59,7 +60,7 @@ public class SearchWithGenericListHl7OrgDstu2Test { assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals("searchByIdentifier", ourLastMethod); assertThat(responseContent, containsString("")); + assertThat(responseContent, containsString("")); } public static class DummyPatientResourceProvider implements IResourceProvider { @@ -86,33 +87,7 @@ public class SearchWithGenericListHl7OrgDstu2Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithHl7OrgDstu2BundleTest.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithHl7OrgDstu2BundleTest.java index 009b4656a8b..5269847861a 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithHl7OrgDstu2BundleTest.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/SearchWithHl7OrgDstu2BundleTest.java @@ -2,23 +2,18 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.Search; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.Bundle; import org.hl7.fhir.dstu2.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.extension.RegisterExtension; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.stringContainsInOrder; @@ -26,15 +21,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchWithHl7OrgDstu2BundleTest { - private static CloseableHttpClient ourClient; - private static int ourPort; - private static Server ourServer; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithHl7OrgDstu2BundleTest.class); - @Test + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + + @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=xml&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=xml&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -50,10 +52,10 @@ public class SearchWithHl7OrgDstu2BundleTest { "", "" , "", - "", + "", "" , "" , - //"" , + //"" , "" , "")); // @formatter:off @@ -62,30 +64,7 @@ public class SearchWithHl7OrgDstu2BundleTest { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); - } - - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - + TestUtil.randomizeLocaleAndTimezone(); } /** diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerConformanceProviderHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerConformanceProviderHl7OrgDstu2Test.java index a2b44b07ae7..2f202dc09ff 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerConformanceProviderHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ServerConformanceProviderHl7OrgDstu2Test.java @@ -45,8 +45,8 @@ import org.hl7.fhir.dstu2.model.StringType; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.jupiter.api.Test; -import javax.servlet.ServletConfig; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.http.HttpServletRequest; import java.util.Collection; import java.util.List; import java.util.Set; @@ -492,7 +492,7 @@ public class ServerConformanceProviderHl7OrgDstu2Test { @Operation(name = "plain", idempotent = true, returnParameters= { @OperationParam(min=1, max=2, name="out1", type=StringType.class) }) - public IBundleProvider everything(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @OperationParam(name = "start") DateType theStart, @OperationParam(name = "end") DateType theEnd) { + public IBundleProvider everything(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @OperationParam(name = "start") DateType theStart, @OperationParam(name = "end") DateType theEnd) { return null; } @@ -501,7 +501,7 @@ public class ServerConformanceProviderHl7OrgDstu2Test { public static class ProviderWithExtendedOperationReturningBundle implements IResourceProvider { @Operation(name = "everything", idempotent = true) - public IBundleProvider everything(javax.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @OperationParam(name = "start") DateType theStart, @OperationParam(name = "end") DateType theEnd) { + public IBundleProvider everything(jakarta.servlet.http.HttpServletRequest theServletRequest, @IdParam IdType theId, @OperationParam(name = "start") DateType theStart, @OperationParam(name = "end") DateType theEnd) { return null; } diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithBundleResourceParamHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithBundleResourceParamHl7OrgDstu2Test.java index f101a33165c..89ab146034d 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithBundleResourceParamHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/TransactionWithBundleResourceParamHl7OrgDstu2Test.java @@ -16,7 +16,7 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.Bundle; import org.hl7.fhir.dstu2.model.Bundle.BundleEntryComponent; import org.hl7.fhir.dstu2.model.Bundle.HTTPVerb; @@ -231,7 +231,7 @@ public class TransactionWithBundleResourceParamHl7OrgDstu2Test { RestfulServer server = new RestfulServer(ourCtx); server.setProviders(patientProvider); - org.eclipse.jetty.servlet.ServletContextHandler proxyHandler = new org.eclipse.jetty.servlet.ServletContextHandler(); + org.eclipse.jetty.ee10.servlet.ServletContextHandler proxyHandler = new org.eclipse.jetty.ee10.servlet.ServletContextHandler(); proxyHandler.setContextPath("/"); ServletHolder handler = new ServletHolder(); diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/UpdateConditionalHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/UpdateConditionalHl7OrgDstu2Test.java index 2c33117196d..f78b2581532 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/UpdateConditionalHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/UpdateConditionalHl7OrgDstu2Test.java @@ -10,8 +10,12 @@ import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.annotation.Update; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; @@ -22,14 +26,15 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.IdType; import org.hl7.fhir.dstu2.model.Patient; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -40,19 +45,26 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class UpdateConditionalHl7OrgDstu2Test { - private static CloseableHttpClient ourClient; private static String ourLastConditionalUrl; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(UpdateConditionalHl7OrgDstu2Test.class); - private static int ourPort; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); - private static Server ourServer; + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); private static String ourLastId; private static IdType ourLastIdParam; private static boolean ourLastRequestWasSearch; - - - - @BeforeEach + + + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + + + @BeforeEach public void before() { ourLastId = null; ourLastConditionalUrl = null; @@ -66,7 +78,7 @@ public class UpdateConditionalHl7OrgDstu2Test { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?identifier=system%7C001"); + HttpPut httpPost = new HttpPut(ourServer.getBaseUrl() + "/Patient?identifier=system%7C001"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -78,7 +90,7 @@ public class UpdateConditionalHl7OrgDstu2Test { assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals(null, status.getFirstHeader("location")); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); assertNull(ourLastId); assertNull(ourLastIdParam); @@ -93,7 +105,7 @@ public class UpdateConditionalHl7OrgDstu2Test { patient.setId("2"); patient.addIdentifier().setValue("002"); - HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/2"); + HttpPut httpPost = new HttpPut(ourServer.getBaseUrl() + "/Patient/2"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -105,7 +117,7 @@ public class UpdateConditionalHl7OrgDstu2Test { assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals(null, status.getFirstHeader("location")); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); assertEquals("Patient/2", new IdType(ourLastId).toUnqualified().getValue()); assertEquals("Patient/2", ourLastIdParam.toUnqualified().getValue()); @@ -119,7 +131,7 @@ public class UpdateConditionalHl7OrgDstu2Test { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_pretty=true"); HttpResponse status = ourClient.execute(httpGet); @@ -138,32 +150,10 @@ public class UpdateConditionalHl7OrgDstu2Test { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); + TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class PatientProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ValidateHl7OrgDstu2Test.java b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ValidateHl7OrgDstu2Test.java index 268ef8c772d..6994f042f11 100644 --- a/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ValidateHl7OrgDstu2Test.java +++ b/hapi-fhir-structures-hl7org-dstu2/src/test/java/ca/uhn/fhir/rest/server/ValidateHl7OrgDstu2Test.java @@ -8,7 +8,10 @@ import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.ValidationModeEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; @@ -18,8 +21,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.dstu2.model.IdType; import org.hl7.fhir.dstu2.model.OperationOutcome; import org.hl7.fhir.dstu2.model.Organization; @@ -30,6 +33,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -41,17 +45,25 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * Created by dsotnikov on 2/25/2014. */ public class ValidateHl7OrgDstu2Test { - private static CloseableHttpClient ourClient; private static EncodingEnum ourLastEncoding; private static String ourLastResourceBody; - private static int ourPort; - private static Server ourServer; private static OperationOutcome ourOutcomeToReturn; private static ValidationModeEnum ourLastMode; private static String ourLastProfile; - private static FhirContext ourCtx = FhirContext.forDstu2Hl7Org(); - - @BeforeEach() + private static final FhirContext ourCtx = FhirContext.forDstu2Hl7OrgCached(); + + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .registerProvider(new OrganizationProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + + @BeforeEach() public void before() { ourLastResourceBody = null; ourLastEncoding = null; @@ -72,7 +84,7 @@ public class ValidateHl7OrgDstu2Test { params.addParameter().setName("profile").setValue(new StringType("http://foo")); params.addParameter().setName("mode").setValue(new StringType(ValidationModeEnum.CREATE.getCode())); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -96,7 +108,7 @@ public class ValidateHl7OrgDstu2Test { Parameters params = new Parameters(); params.addParameter().setName("resource").setResource(patient); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -121,7 +133,7 @@ public class ValidateHl7OrgDstu2Test { Parameters params = new Parameters(); params.addParameter().setName("resource").setResource(patient); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -143,7 +155,7 @@ public class ValidateHl7OrgDstu2Test { Parameters params = new Parameters(); params.addParameter().setName("resource").setResource(org); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Organization/$validate"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Organization/$validate"); httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(params), ContentType.create(Constants.CT_FHIR_JSON, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -156,30 +168,9 @@ public class ValidateHl7OrgDstu2Test { @AfterAll public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); + TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider, new OrganizationProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } public static class PatientProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-r4/pom.xml b/hapi-fhir-structures-r4/pom.xml index b537170eff6..5aa456fa37a 100644 --- a/hapi-fhir-structures-r4/pom.xml +++ b/hapi-fhir-structures-r4/pom.xml @@ -5,7 +5,7 @@ ca.uhn.hapi.fhir hapi-deployable-pom - 6.11.4-SNAPSHOT + 6.11.5-SNAPSHOT ../hapi-deployable-pom/pom.xml @@ -106,8 +106,8 @@ true - javax.servlet - javax.servlet-api + jakarta.servlet + jakarta.servlet-api true @@ -140,6 +140,11 @@ + + com.helger.commons + ph-collection + test + - - com.helger - ph-schematron - test - - - com.helger - ph-commons - test - - - javax.activation - javax.activation-api - test - - - javax.xml.bind - jaxb-api - test - - - org.glassfish.jaxb - jaxb-runtime - test - - - net.sf.json-lib diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/narrative/CustomThymeleafNarrativeGeneratorR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/narrative/CustomThymeleafNarrativeGeneratorR4Test.java index 012552f7896..f7e9bd5797d 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/narrative/CustomThymeleafNarrativeGeneratorR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/narrative/CustomThymeleafNarrativeGeneratorR4Test.java @@ -15,9 +15,6 @@ public class CustomThymeleafNarrativeGeneratorR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CustomThymeleafNarrativeGeneratorR4Test.class); - /** - * Don't use cached here since we modify the context - */ private final FhirContext myCtx = FhirContext.forR4Cached(); @AfterEach @@ -30,7 +27,6 @@ public class CustomThymeleafNarrativeGeneratorR4Test { */ @Test public void testStandardType() { - CustomThymeleafNarrativeGenerator gen = new CustomThymeleafNarrativeGenerator("classpath:narrative/standardtypes_r4.properties"); myCtx.setNarrativeGenerator(gen); @@ -51,6 +47,7 @@ public class CustomThymeleafNarrativeGeneratorR4Test { @Test public void testCustomType() { + myCtx.setNarrativeGenerator(null); CustomPatient patient = new CustomPatient(); patient.setActive(true); diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorR4Test.java index 6a88ca6c9e8..f78bc4d32a3 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/narrative/DefaultThymeleafNarrativeGeneratorR4Test.java @@ -91,7 +91,7 @@ public class DefaultThymeleafNarrativeGeneratorR4Test { String parse = "\n" + " \n" + " \n" + - " \n" + + " \n" + " \n" + " \n" + " \n" + diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/parser/RDFParserTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/parser/RDFParserTest.java index a27fddac70c..7ddda19896a 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/parser/RDFParserTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/parser/RDFParserTest.java @@ -38,6 +38,8 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Base; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.core.io.Resource; @@ -88,6 +90,7 @@ public class RDFParserTest extends BaseTest { */ @ParameterizedTest @MethodSource("getInputFiles") + @Execution(ExecutionMode.CONCURRENT) public void testRDFRoundTrip(String referenceFilePath) throws IOException { String referenceFileName = referenceFilePath.substring(referenceFilePath.lastIndexOf("/")+1); IBaseResource referenceResource = parseJson(new FileInputStream(referenceFilePath)); diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientHeadersR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientHeadersR4Test.java index e14028ac170..7d5a51910f1 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientHeadersR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientHeadersR4Test.java @@ -9,17 +9,17 @@ import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; import ca.uhn.fhir.test.utilities.JettyUtil; import ca.uhn.fhir.util.TestUtil; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientIntegrationTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientIntegrationTest.java index fe78ecb8004..026af8d9059 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientIntegrationTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/ClientIntegrationTest.java @@ -4,69 +4,66 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory; import ca.uhn.fhir.rest.client.api.IBasicClient; import ca.uhn.fhir.rest.client.impl.HttpBasicAuthInterceptor; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; +import ca.uhn.fhir.rest.server.interceptor.ExceptionInterceptorMethodTest; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.lang3.Validate; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.extension.RegisterExtension; + import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; public class ClientIntegrationTest { - private Server myServer; - private MyPatientResourceProvider myPatientProvider; - private static FhirContext ourCtx = FhirContext.forR4(); + private MyPatientResourceProvider myPatientProvider = new MyPatientResourceProvider(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); - @BeforeEach - public void before() { - myServer = new Server(0); + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(myPatientProvider) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML); - myPatientProvider = new MyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(myPatientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - myServer.setHandler(proxyHandler); - - } + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @SuppressWarnings("deprecation") @Test public void testClientSecurity() throws Exception { - JettyUtil.startServer(myServer); - int myPort = JettyUtil.getPortForStartedServer(myServer); - - FhirContext ctx = FhirContext.forR4(); - HttpClientBuilder builder = HttpClientBuilder.create(); // PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); // builder.setConnectionManager(connectionManager); builder.addInterceptorFirst(new HttpBasicAuthInterceptor("foobar", "boobear")); CloseableHttpClient httpClient = builder.build(); - ctx.getRestfulClientFactory().setHttpClient(httpClient); - PatientClient client = ctx.newRestfulClient(PatientClient.class, "http://localhost:" + myPort + "/"); + ourCtx.getRestfulClientFactory().setHttpClient(httpClient); + + PatientClient client = ourCtx.newRestfulClient(PatientClient.class, ourServer.getBaseUrl() + "/"); List actualPatients = client.searchForPatients(new StringDt("AAAABBBB")); assertEquals(1, actualPatients.size()); @@ -77,7 +74,7 @@ public class ClientIntegrationTest { @AfterEach public void after() throws Exception { - JettyUtil.closeServer(myServer); + ourCtx.setRestfulClientFactory(new ApacheRestfulClientFactory(ourCtx)); } public static class MyPatientResourceProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/CompressOutgoingContentInterceptorTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/CompressOutgoingContentInterceptorTest.java index e24883f5696..31bf708965e 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/CompressOutgoingContentInterceptorTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/CompressOutgoingContentInterceptorTest.java @@ -5,51 +5,48 @@ import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.rest.annotation.Create; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.client.apache.GZipContentInterceptor; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; -import ca.uhn.fhir.rest.server.RestfulServer; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import jakarta.servlet.http.HttpServletRequest; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - -import javax.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.extension.RegisterExtension; import static org.junit.jupiter.api.Assertions.assertEquals; public class CompressOutgoingContentInterceptorTest { - private static IGenericClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static Patient ourLastPatient; private static String ourLastReq; private static String ourLastResponseEncoding; - private static int ourPort; - private static Server ourServer; - @BeforeEach - public void before() { - ourClient = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); - } + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10)) + .setDefaultResponseEncoding(EncodingEnum.XML); + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testCreate() { - ourClient.registerInterceptor(new GZipContentInterceptor()); + IGenericClient client = ourServer.getFhirClient(); + client.registerInterceptor(new GZipContentInterceptor()); Patient p = new Patient(); p.addName().setFamily("FAMILY"); - ourClient.create().resource(p).execute(); + client.create().resource(p).execute(); assertEquals("FAMILY", p.getName().get(0).getFamily()); assertEquals("gzip", ourLastReq); @@ -59,28 +56,9 @@ public class CompressOutgoingContentInterceptorTest { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Create diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/HttpProxyTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/HttpProxyTest.java index e04b623afe2..9231bbe7184 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/HttpProxyTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/HttpProxyTest.java @@ -11,17 +11,17 @@ import ca.uhn.fhir.util.TestUtil; import org.apache.commons.collections.EnumerationUtils; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletContextHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/LoggingInterceptorTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/LoggingInterceptorTest.java index 2f4109fb05e..93c67d6a6f9 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/LoggingInterceptorTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/client/LoggingInterceptorTest.java @@ -5,11 +5,16 @@ import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.client.api.IGenericClient; +import ca.uhn.fhir.rest.client.api.IRestfulClientFactory; import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; +import ca.uhn.fhir.rest.server.interceptor.ExceptionInterceptorMethodTest; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; @@ -17,8 +22,8 @@ import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; @@ -26,6 +31,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentMatcher; import org.slf4j.LoggerFactory; @@ -42,11 +48,18 @@ import static org.mockito.Mockito.when; public class LoggingInterceptorTest { private static final FhirContext ourCtx = FhirContext.forR4Cached(); - private static int ourPort; - private static Server ourServer; private Logger myLoggerRoot; private Appender myMockAppender; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @AfterEach public void after() { myLoggerRoot.detachAppender(myMockAppender); @@ -71,7 +84,7 @@ public class LoggingInterceptorTest { @Test public void testLoggerNonVerbose() { System.out.println("Starting testLogger"); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl()); ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); LoggingInterceptor interceptor = new LoggingInterceptor(false); @@ -87,7 +100,7 @@ public class LoggingInterceptorTest { System.out.println("** Got Message: " + formattedMessage); System.out.flush(); return - formattedMessage.contains("Client request: GET http://localhost:" + ourPort + "/Patient/1 HTTP/1.1") || + formattedMessage.contains("Client request: GET " + ourServer.getBaseUrl() + "/Patient/1 HTTP/1.1") || formattedMessage.contains("Client response: HTTP 200 OK (Patient/1/_history/1) in "); } })); @@ -96,7 +109,7 @@ public class LoggingInterceptorTest { @Test public void testLoggerVerbose() { System.out.println("Starting testLogger"); - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl()); ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); LoggingInterceptor interceptor = new LoggingInterceptor(true); @@ -132,7 +145,7 @@ public class LoggingInterceptorTest { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); + ourCtx.getRestfulClientFactory().setServerValidationMode(IRestfulClientFactory.DEFAULT_SERVER_VALIDATION_MODE); TestUtil.randomizeLocaleAndTimezone(); } @@ -147,20 +160,6 @@ public class LoggingInterceptorTest { context.reset(); configurator.doConfigure(conf); - ourServer = new Server(0); - - DummyProvider patientProvider = new DummyProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamR4Test.java index aedeb3c7f84..2a6b5016d3e 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamR4Test.java @@ -4,32 +4,26 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.api.TemporalPrecisionEnum; import ca.uhn.fhir.model.primitive.DateTimeDt; import ca.uhn.fhir.model.primitive.InstantDt; -import ca.uhn.fhir.narrative.DefaultThymeleafNarrativeGenerator; import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.QualifiedParamList; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; -import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.time.DateUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.jena.base.Sys; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,7 +35,6 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; -import java.util.concurrent.TimeUnit; import static ca.uhn.fhir.rest.param.ParamPrefixEnum.EQUAL; import static ca.uhn.fhir.rest.param.ParamPrefixEnum.GREATERTHAN_OR_EQUALS; @@ -59,12 +52,8 @@ public class DateRangeParamR4Test { private static final SimpleDateFormat ourFmtLowerForTime; private static final SimpleDateFormat ourFmtUpperForTime; private static final Logger ourLog = LoggerFactory.getLogger(DateRangeParamR4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4Cached(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static DateRangeParam ourLastDateRange; - private static int ourPort; - private static Server ourServer; - private static String ourBaseUrl; static { ourFmtLower = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS"); @@ -77,6 +66,17 @@ public class DateRangeParamR4Test { ourFmtUpperForTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS"); } + @RegisterExtension + private RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .setDefaultResponseEncoding(EncodingEnum.XML) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + + @BeforeEach public void before() { ourLastDateRange = null; @@ -84,7 +84,7 @@ public class DateRangeParamR4Test { @Test public void testSearchForMultipleUnqualifiedDate() throws Exception { - String baseUrl = "http://localhost:" + ourPort + "/Patient?" + Patient.SP_BIRTHDATE + "="; + String baseUrl = ourServer.getBaseUrl() + "/Patient?" + Patient.SP_BIRTHDATE + "="; HttpGet httpGet = new HttpGet(baseUrl + "2012-01-01&" + Patient.SP_BIRTHDATE + "=2012-02-03"); CloseableHttpResponse status = ourClient.execute(httpGet); consumeResponse(status); @@ -102,7 +102,7 @@ public class DateRangeParamR4Test { @Test public void testSearchForOneUnqualifiedDate() throws Exception { - HttpGet httpGet = new HttpGet(ourBaseUrl + "?birthdate=2012-01-01"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?birthdate=2012-01-01"); CloseableHttpResponse status = ourClient.execute(httpGet); consumeResponse(status); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -118,7 +118,7 @@ public class DateRangeParamR4Test { @Test public void testSearchForOneQualifiedDateEq() throws Exception { - HttpGet httpGet = new HttpGet(ourBaseUrl + "?birthdate=eq2012-01-01"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?birthdate=eq2012-01-01"); CloseableHttpResponse status = ourClient.execute(httpGet); consumeResponse(status); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -134,7 +134,7 @@ public class DateRangeParamR4Test { @Test public void testSearchForOneQualifiedDateGt() throws Exception { - HttpGet httpGet = new HttpGet(ourBaseUrl + "?birthdate=gt2012-01-01"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?birthdate=gt2012-01-01"); CloseableHttpResponse status = ourClient.execute(httpGet); consumeResponse(status); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -150,7 +150,7 @@ public class DateRangeParamR4Test { @Test public void testSearchForOneQualifiedDateLt() throws Exception { - HttpGet httpGet = new HttpGet(ourBaseUrl + "?birthdate=lt2012-01-01"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?birthdate=lt2012-01-01"); CloseableHttpResponse status = ourClient.execute(httpGet); consumeResponse(status); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -166,7 +166,7 @@ public class DateRangeParamR4Test { @Test public void testSearchForOneQualifiedDateGe() throws Exception { - HttpGet httpGet = new HttpGet(ourBaseUrl + "?birthdate=ge2012-01-01"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?birthdate=ge2012-01-01"); CloseableHttpResponse status = ourClient.execute(httpGet); consumeResponse(status); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -182,7 +182,7 @@ public class DateRangeParamR4Test { @Test public void testSearchForOneQualifiedDateLe() throws Exception { - HttpGet httpGet = new HttpGet(ourBaseUrl + "?birthdate=le2012-01-01"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?birthdate=le2012-01-01"); CloseableHttpResponse status = ourClient.execute(httpGet); consumeResponse(status); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -198,7 +198,7 @@ public class DateRangeParamR4Test { @Test public void testSearchForOneQualifiedDateNe() throws Exception { - HttpGet httpGet = new HttpGet(ourBaseUrl + "?birthdate=ne2012-01-01"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?birthdate=ne2012-01-01"); CloseableHttpResponse status = ourClient.execute(httpGet); consumeResponse(status); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -212,7 +212,7 @@ public class DateRangeParamR4Test { @Test public void testRangeWithDatePrecision() throws Exception { - HttpGet httpGet = new HttpGet(ourBaseUrl + "?birthdate=gt2012-01-01&birthdate=lt2012-01-03"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?birthdate=gt2012-01-01&birthdate=lt2012-01-03"); CloseableHttpResponse status = ourClient.execute(httpGet); consumeResponse(status); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -412,7 +412,7 @@ public class DateRangeParamR4Test { assertEquals(new DateRangeParam(null, upperBound), new DateRangeParam(null, new DateParam(LESSTHAN_OR_EQUALS, upperBound))); } - public static class DummyPatientResourceProvider implements IResourceProvider { + private static class DummyPatientResourceProvider implements IResourceProvider { @Override public Class getResourceType() { @@ -466,33 +466,7 @@ public class DateRangeParamR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.getFhirContext().setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator()); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - ourBaseUrl = "http://localhost:" + ourPort + "/Patient"; - } - } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/BaseR4ServerTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/BaseR4ServerTest.java index a1bc70a2618..3f73d339ed0 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/BaseR4ServerTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/BaseR4ServerTest.java @@ -2,43 +2,42 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.api.BundleInclusionRule; +import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; public class BaseR4ServerTest { - protected FhirContext myCtx = FhirContext.forR4Cached(); - private Server myServer; - protected IGenericClient myClient; - protected String myBaseUrl; + private static final FhirContext ourCtx = FhirContext.forR4Cached(); - @AfterEach - public void after() throws Exception { - JettyUtil.closeServer(myServer); - } + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PlaceholderProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .withServer(s->s.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE)); + + @RegisterExtension + public HttpClientExtension ourClient = new HttpClientExtension(); protected void startServer(Object theProvider) throws Exception { - RestfulServer servlet = new RestfulServer(myCtx); - servlet.registerProvider(theProvider); - ServletHandler proxyHandler = new ServletHandler(); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - - myServer = new Server(0); - myServer.setHandler(proxyHandler); - JettyUtil.startServer(myServer); - int port = JettyUtil.getPortForStartedServer(myServer); - - myBaseUrl = "http://localhost:" + port; - myCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); - myClient = myCtx.newRestfulGenericClient(myBaseUrl); + ourServer.getRestfulServer().registerProvider(theProvider); } + private static class PlaceholderProvider { + + @Operation(name = "placeholderOperation") + public void placeholderOperation() { + // nothing + } + + } } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/BinaryServerR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/BinaryServerR4Test.java index c507eb82aca..13f98b36727 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/BinaryServerR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/BinaryServerR4Test.java @@ -7,8 +7,10 @@ import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Update; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; @@ -18,39 +20,38 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Binary; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.Reference; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.extension.RegisterExtension; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; -public class BinaryServerR4Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); +public class BinaryServerR4Test { + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static Binary ourLastBinary; private static byte[] ourLastBinaryBytes; private static String ourLastBinaryString; - private static int ourPort; - private static Server ourServer; private static IdType ourLastId; private static Binary ourNextBinary; + @RegisterExtension + public static final RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new BinaryProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false); + + @RegisterExtension + public static final HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastBinary = null; @@ -69,7 +70,7 @@ public class BinaryServerR4Test { ourNextBinary.setSecurityContext(new Reference("Patient/1")); ourNextBinary.setContentType("application/foo"); - HttpGet get = new HttpGet("http://localhost:" + ourPort + "/Binary/A"); + HttpGet get = new HttpGet(ourServer.getBaseUrl() + "/Binary/A"); get.addHeader("Content-Type", "application/foo"); CloseableHttpResponse status = ourClient.execute(get); try { @@ -77,7 +78,7 @@ public class BinaryServerR4Test { assertEquals("application/foo", status.getEntity().getContentType().getValue()); assertEquals("Patient/1", status.getFirstHeader(Constants.HEADER_X_SECURITY_CONTEXT).getValue()); assertEquals("W/\"222\"", status.getFirstHeader(Constants.HEADER_ETAG).getValue()); - assertEquals("http://localhost:" + ourPort + "/Binary/A/_history/222", status.getFirstHeader(Constants.HEADER_CONTENT_LOCATION).getValue()); + assertEquals(ourServer.getBaseUrl() + "/Binary/A/_history/222", status.getFirstHeader(Constants.HEADER_CONTENT_LOCATION).getValue()); assertEquals(null, status.getFirstHeader(Constants.HEADER_LOCATION)); byte[] content = IOUtils.toByteArray(status.getEntity().getContent()); @@ -97,7 +98,7 @@ public class BinaryServerR4Test { ourNextBinary.setSecurityContext(new Reference("Patient/1")); ourNextBinary.setContentType("application/foo"); - HttpGet get = new HttpGet("http://localhost:" + ourPort + "/Binary/A"); + HttpGet get = new HttpGet(ourServer.getBaseUrl() + "/Binary/A"); get.addHeader("Content-Type", "application/foo"); get.addHeader("Accept", Constants.CT_FHIR_JSON); CloseableHttpResponse status = ourClient.execute(get); @@ -106,7 +107,7 @@ public class BinaryServerR4Test { assertEquals("application/json+fhir;charset=utf-8", status.getEntity().getContentType().getValue()); assertEquals("Patient/1", status.getFirstHeader(Constants.HEADER_X_SECURITY_CONTEXT).getValue()); assertEquals("W/\"222\"", status.getFirstHeader(Constants.HEADER_ETAG).getValue()); - assertEquals("http://localhost:" + ourPort + "/Binary/A/_history/222", status.getFirstHeader(Constants.HEADER_CONTENT_LOCATION).getValue()); + assertEquals(ourServer.getBaseUrl() + "/Binary/A/_history/222", status.getFirstHeader(Constants.HEADER_CONTENT_LOCATION).getValue()); assertEquals(null, status.getFirstHeader(Constants.HEADER_LOCATION)); String content = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); @@ -118,7 +119,7 @@ public class BinaryServerR4Test { @Test public void testPostBinaryWithSecurityContext() throws Exception { - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost post = new HttpPost(ourServer.getBaseUrl() + "/Binary"); post.setEntity(new ByteArrayEntity(new byte[]{0, 1, 2, 3, 4})); post.addHeader("Content-Type", "application/foo"); post.addHeader(Constants.HEADER_X_SECURITY_CONTEXT, "Encounter/2"); @@ -136,7 +137,7 @@ public class BinaryServerR4Test { @Test public void testPostRawBytesBinaryContentType() throws Exception { - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost post = new HttpPost(ourServer.getBaseUrl() + "/Binary"); post.setEntity(new ByteArrayEntity(new byte[]{0, 1, 2, 3, 4})); post.addHeader("Content-Type", "application/foo"); CloseableHttpResponse status = ourClient.execute(post); @@ -161,7 +162,7 @@ public class BinaryServerR4Test { b.setContent(new byte[]{0, 1, 2, 3, 4}); String encoded = ourCtx.newJsonParser().encodeResourceToString(b); - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost post = new HttpPost(ourServer.getBaseUrl() + "/Binary"); post.setEntity(new StringEntity(encoded)); post.addHeader("Content-Type", Constants.CT_FHIR_JSON); CloseableHttpResponse status = ourClient.execute(post); @@ -184,7 +185,7 @@ public class BinaryServerR4Test { b.setContent(ourCtx.newXmlParser().encodeResourceToString(p).getBytes("UTF-8")); String encoded = ourCtx.newJsonParser().encodeResourceToString(b); - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost post = new HttpPost(ourServer.getBaseUrl() + "/Binary"); post.setEntity(new StringEntity(encoded)); post.addHeader("Content-Type", Constants.CT_FHIR_JSON); CloseableHttpResponse status = ourClient.execute(post); @@ -200,7 +201,7 @@ public class BinaryServerR4Test { @Test public void testPostRawBytesNoContentType() throws Exception { - HttpPost post = new HttpPost("http://localhost:" + ourPort + "/Binary"); + HttpPost post = new HttpPost(ourServer.getBaseUrl() + "/Binary"); post.setEntity(new ByteArrayEntity(new byte[]{0, 1, 2, 3, 4})); CloseableHttpResponse status = ourClient.execute(post); try { @@ -213,7 +214,7 @@ public class BinaryServerR4Test { @Test public void testPutBinaryWithSecurityContext() throws Exception { - HttpPut post = new HttpPut("http://localhost:" + ourPort + "/Binary/A"); + HttpPut post = new HttpPut(ourServer.getBaseUrl() + "/Binary/A"); post.setEntity(new ByteArrayEntity(new byte[]{0, 1, 2, 3, 4})); post.addHeader("Content-Type", "application/foo"); post.addHeader(Constants.HEADER_X_SECURITY_CONTEXT, "Encounter/2"); @@ -232,31 +233,9 @@ public class BinaryServerR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - BinaryProvider binaryProvider = new BinaryProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(binaryProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - } - public static class BinaryProvider implements IResourceProvider { @Create() public MethodOutcome createBinary(@ResourceParam Binary theBinary, @ResourceParam String theBinaryString, @ResourceParam byte[] theBinaryBytes) { diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/CapabilityStatementCacheR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/CapabilityStatementCacheR4Test.java index d10efd46300..0e82c283a81 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/CapabilityStatementCacheR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/CapabilityStatementCacheR4Test.java @@ -13,7 +13,7 @@ import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.List; import java.util.stream.Collectors; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/CreateR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/CreateR4Test.java index d9a7957056c..9cf95713f2d 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/CreateR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/CreateR4Test.java @@ -8,10 +8,13 @@ import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.PreferReturnEnum; import ca.uhn.fhir.rest.client.MyPatientWithExtensions; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -24,8 +27,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.DateType; import org.hl7.fhir.r4.model.IdType; @@ -37,6 +40,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -54,17 +58,21 @@ import static org.junit.jupiter.api.Assertions.assertNull; public class CreateR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CreateR4Test.class); public static OperationOutcome ourReturnOo; - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + private static final FhirContext ourCtx = FhirContext.forR4Cached(); - @AfterEach - public void after() { - ourServlet.setDefaultPreferReturn(RestfulServer.DEFAULT_PREFER_RETURN); - } + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProviderCreate()) + .registerProvider(new PatientProviderRead()) + .registerProvider(new PatientProviderSearch()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .withServer(s->s.setDefaultPreferReturn(RestfulServer.DEFAULT_PREFER_RETURN)) + .setDefaultPrettyPrint(false); + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourReturnOo = null; @@ -73,7 +81,7 @@ public class CreateR4Test { @Test public void testCreateIgnoresIdInResourceBody() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"resourceType\":\"Patient\", \"id\":\"999\", \"status\":\"active\"}", ContentType.parse("application/fhir+json; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -86,14 +94,14 @@ public class CreateR4Test { assertEquals(1, status.getHeaders("Location").length); assertEquals(1, status.getHeaders("Content-Location").length); - assertEquals("http://localhost:" + ourPort + "/Patient/1", status.getFirstHeader("Location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/1", status.getFirstHeader("Location").getValue()); } @Test public void testCreateFailsIfNoContentTypeProvided() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"resourceType\":\"Patient\", \"id\":\"999\", \"status\":\"active\"}", (ContentType) null)); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { @@ -113,7 +121,7 @@ public class CreateR4Test { @Test public void testCreateReturnsLocationHeader() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"resourceType\":\"Patient\", \"status\":\"active\"}", ContentType.parse("application/fhir+json; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -126,7 +134,7 @@ public class CreateR4Test { assertEquals(1, status.getHeaders("Location").length); assertEquals(1, status.getHeaders("Content-Location").length); - assertEquals("http://localhost:" + ourPort + "/Patient/1", status.getFirstHeader("Location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/1", status.getFirstHeader("Location").getValue()); } @@ -134,7 +142,7 @@ public class CreateR4Test { public void testCreateReturnsOperationOutcome() throws Exception { ourReturnOo = new OperationOutcome().addIssue(new OperationOutcomeIssueComponent().setDiagnostics("DIAG")); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"resourceType\":\"Patient\", \"status\":\"active\"}", ContentType.parse("application/fhir+json; charset=utf-8"))); httpPost.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); HttpResponse status = ourClient.execute(httpPost); @@ -154,7 +162,7 @@ public class CreateR4Test { ourReturnOo = new OperationOutcome().addIssue(new OperationOutcomeIssueComponent().setDiagnostics("DIAG")); String expectedResponseContent = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\"},\"gender\":\"male\"}"; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"resourceType\":\"Patient\", \"gender\":\"male\"}", ContentType.parse("application/fhir+json; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -170,7 +178,7 @@ public class CreateR4Test { @Test public void testCreateWithIncorrectContent1() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"foo\":\"bar\"}", ContentType.parse("application/xml+fhir; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -189,7 +197,7 @@ public class CreateR4Test { @Test public void testCreateWithIncorrectContent2() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"foo\":\"bar\"}", ContentType.parse("application/fhir+xml; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -208,7 +216,7 @@ public class CreateR4Test { @Test public void testCreateWithIncorrectContent3() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("{\"foo\":\"bar\"}", ContentType.parse("application/fhir+json; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -229,7 +237,7 @@ public class CreateR4Test { @Test public void testCreateWithInvalidContent() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity("FOO", ContentType.parse("application/xml+fhir; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -256,7 +264,7 @@ public class CreateR4Test { String body = ourCtx.newJsonParser().encodeResourceToString(p); HttpPost httpPost; - httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(body, ContentType.parse("application/fhir+json; charset=utf-8"))); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { @@ -279,9 +287,9 @@ public class CreateR4Test { p.setActive(true); String body = ourCtx.newJsonParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(body, ContentType.parse("application/fhir+json; charset=utf-8"))); - ourServlet.setDefaultPreferReturn(PreferReturnEnum.OPERATION_OUTCOME); + ourServer.getRestfulServer().setDefaultPreferReturn(PreferReturnEnum.OPERATION_OUTCOME); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { assertEquals(201, status.getStatusLine().getStatusCode()); @@ -304,9 +312,9 @@ public class CreateR4Test { p.setActive(true); String body = ourCtx.newJsonParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(body, ContentType.parse("application/fhir+json; charset=utf-8"))); - ourServlet.setDefaultPreferReturn(PreferReturnEnum.MINIMAL); + ourServer.getRestfulServer().setDefaultPreferReturn(PreferReturnEnum.MINIMAL); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { assertEquals(201, status.getStatusLine().getStatusCode()); @@ -321,7 +329,7 @@ public class CreateR4Test { @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=xml&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=xml&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -389,7 +397,7 @@ public class CreateR4Test { @Search public List search() { - ArrayList retVal = new ArrayList(); + ArrayList retVal = new ArrayList<>(); MyPatientWithExtensions p0 = new MyPatientWithExtensions(); p0.setId(new IdType("Patient/0")); @@ -408,33 +416,7 @@ public class CreateR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProviderCreate patientProviderCreate = new PatientProviderCreate(); - PatientProviderRead patientProviderRead = new PatientProviderRead(); - PatientProviderSearch patientProviderSearch = new PatientProviderSearch(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - - ourServlet.setResourceProviders(patientProviderCreate, patientProviderRead, patientProviderSearch); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalR4Test.java index edbbb0b25be..6c26e113fe2 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/DeleteConditionalR4Test.java @@ -4,17 +4,20 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; import ca.uhn.fhir.rest.annotation.Delete; import ca.uhn.fhir.rest.annotation.IdParam; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Patient; @@ -22,6 +25,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -30,16 +34,21 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class DeleteConditionalR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(DeleteConditionalR4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); - private static IGenericClient ourHapiClient; + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static String ourLastConditionalUrl; private static IdType ourLastIdParam; private static boolean ourLastRequestWasDelete; - private static int ourPort; - private static Server ourServer; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastConditionalUrl = null; @@ -54,7 +63,8 @@ public class DeleteConditionalR4Test { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - ourHapiClient + ourServer + .getFhirClient() .delete() .resourceConditionalByType(Patient.class) .where(Patient.IDENTIFIER.exactly().systemAndIdentifier("SOMESYS", "SOMEID")).execute(); @@ -84,33 +94,7 @@ public class DeleteConditionalR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - ourCtx.getRestfulClientFactory().setSocketTimeout(500 * 1000); - ourHapiClient = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/"); - ourHapiClient.registerInterceptor(new LoggingInterceptor()); - } - } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ETagServerR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ETagServerR4Test.java index d4f2aea8004..c4c867f8f10 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ETagServerR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ETagServerR4Test.java @@ -10,7 +10,9 @@ import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.server.exceptions.PreconditionFailedException; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; +import ca.uhn.fhir.util.TestUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; import org.apache.http.Header; @@ -20,39 +22,37 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Identifier; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.Date; -import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; public class ETagServerR4Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static Date ourLastModifiedDate; - private static int ourPort; - private static Server ourServer; - private static PoolingHttpClientConnectionManager ourConnectionManager; private static IdType ourLastId; private static boolean ourPutVersionInPatientId; private static boolean ourPutVersionInPatientMeta; - @BeforeEach + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + + @BeforeEach public void before() { ourLastId = null; ourPutVersionInPatientId = true; @@ -74,7 +74,7 @@ public class ETagServerR4Test { private void doTestAutomaticNotModified() throws Exception { ourLastModifiedDate = new InstantDt("2012-11-25T02:34:45.2222Z").getValue(); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/2"); httpGet.addHeader(Constants.HEADER_IF_NONE_MATCH, "\"222\""); HttpResponse status = ourClient.execute(httpGet); assertEquals(Constants.STATUS_HTTP_304_NOT_MODIFIED, status.getStatusLine().getStatusCode()); @@ -84,7 +84,7 @@ public class ETagServerR4Test { public void testETagHeader() throws Exception { ourLastModifiedDate = new InstantDt("2012-11-25T02:34:45.2222Z").getValue(); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/_history/3"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/2/_history/3"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -105,7 +105,7 @@ public class ETagServerR4Test { ourPutVersionInPatientId = false; ourLastModifiedDate = null; - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/_history/3"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/2/_history/3"); HttpResponse status = ourClient.execute(httpGet); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -120,7 +120,7 @@ public class ETagServerR4Test { public void testLastModifiedHeader() throws Exception { ourLastModifiedDate = new InstantDt("2012-11-25T02:34:45.2222Z").getValue(); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/_history/3"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/2/_history/3"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -143,7 +143,7 @@ public class ETagServerR4Test { String resBody = ourCtx.newXmlParser().encodeResourceToString(p); HttpPut http; - http = new HttpPut("http://localhost:" + ourPort + "/Patient/2"); + http = new HttpPut(ourServer.getBaseUrl() + "/Patient/2"); http.setEntity(new StringEntity(resBody, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); http.addHeader(Constants.HEADER_IF_MATCH, "\"221\""); CloseableHttpResponse status = ourClient.execute(http); @@ -161,7 +161,7 @@ public class ETagServerR4Test { String resBody = ourCtx.newXmlParser().encodeResourceToString(p); HttpPut http; - http = new HttpPut("http://localhost:" + ourPort + "/Patient/2"); + http = new HttpPut(ourServer.getBaseUrl() + "/Patient/2"); http.setEntity(new StringEntity(resBody, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); http.addHeader(Constants.HEADER_IF_MATCH, "\"222\""); CloseableHttpResponse status = ourClient.execute(http); @@ -178,7 +178,7 @@ public class ETagServerR4Test { String resBody = ourCtx.newXmlParser().encodeResourceToString(p); HttpPut http; - http = new HttpPut("http://localhost:" + ourPort + "/Patient/2"); + http = new HttpPut(ourServer.getBaseUrl() + "/Patient/2"); http.setEntity(new StringEntity(resBody, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(http); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -187,32 +187,10 @@ public class ETagServerR4Test { } @AfterAll - public static void afterClass() throws Exception { - JettyUtil.closeServer(ourServer); + public static void afterClass() { + TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - ourConnectionManager = new PoolingHttpClientConnectionManager(50000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(ourConnectionManager); - ourClient = builder.build(); - - } public static class PatientProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ElementsParamR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ElementsParamR4Test.java index b4a6e2b015a..9f888145b1e 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ElementsParamR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ElementsParamR4Test.java @@ -8,7 +8,10 @@ import ca.uhn.fhir.rest.annotation.IncludeParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.rest.server.interceptor.ExceptionInterceptorMethodTest; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; @@ -18,8 +21,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.DiagnosticReport; @@ -35,6 +38,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.io.IOException; import java.util.Collection; @@ -51,27 +55,34 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class ElementsParamR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ElementsParamR4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static Set ourLastElements; - private static int ourPort; - private static Server ourServer; private static Procedure ourNextProcedure; - private static RestfulServer ourServlet; private static Observation ourNextObservation; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .registerProvider(new DummyProcedureResourceProvider()) + .registerProvider(new DummyObservationResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastElements = null; ourNextProcedure = null; - ourServlet.setElementsSupport(new RestfulServer().getElementsSupport()); + ourServer.getRestfulServer().setElementsSupport(new RestfulServer().getElementsSupport()); } @Test public void testElementsOnChoiceWithGenericName() throws IOException { createObservationWithQuantity(); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Observation?_elements=value,status", + ourServer.getBaseUrl() + "/Observation?_elements=value,status", bundle -> { Observation obs = (Observation) bundle.getEntry().get(0).getResource(); assertEquals("SUBSETTED", obs.getMeta().getTag().get(0).getCode()); @@ -85,7 +96,7 @@ public class ElementsParamR4Test { public void testElementsOnChoiceWithSpecificName() throws IOException { createObservationWithQuantity(); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Observation?_elements=valueQuantity,status", + ourServer.getBaseUrl() + "/Observation?_elements=valueQuantity,status", bundle -> { Observation obs = (Observation) bundle.getEntry().get(0).getResource(); assertEquals("SUBSETTED", obs.getMeta().getTag().get(0).getCode()); @@ -100,7 +111,7 @@ public class ElementsParamR4Test { public void testElementsOnChoiceWithSpecificNameNotMatching() throws IOException { createObservationWithQuantity(); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Observation?_elements=valueString,status", + ourServer.getBaseUrl() + "/Observation?_elements=valueString,status", bundle -> { Observation obs = (Observation) bundle.getEntry().get(0).getResource(); assertEquals("SUBSETTED", obs.getMeta().getTag().get(0).getCode()); @@ -113,7 +124,7 @@ public class ElementsParamR4Test { public void testExcludeResources() throws IOException { createProcedureWithLongChain(); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_include=*&_elements:exclude=Procedure,DiagnosticReport,*.meta", + ourServer.getBaseUrl() + "/Procedure?_include=*&_elements:exclude=Procedure,DiagnosticReport,*.meta", bundle -> { assertEquals(null, bundle.getEntry().get(0).getResource()); assertEquals(null, bundle.getEntry().get(1).getResource()); @@ -133,7 +144,7 @@ public class ElementsParamR4Test { HttpGet httpGet; encodingEnum = EncodingEnum.JSON; - httpGet = new HttpGet(("http://localhost:" + ourPort + "/Procedure?_include=*&_elements=DiagnosticReport:foo") + "&_pretty=true&_format=" + encodingEnum.getFormatContentType()); + httpGet = new HttpGet((ourServer.getBaseUrl() + "/Procedure?_include=*&_elements=DiagnosticReport:foo") + "&_pretty=true&_format=" + encodingEnum.getFormatContentType()); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); ourLog.info(responseContent); @@ -156,7 +167,7 @@ public class ElementsParamR4Test { @Test public void testReadSummaryData() throws Exception { verifyXmlAndJson( - "http://localhost:" + ourPort + "/Patient/1?_elements=name,maritalStatus", + ourServer.getBaseUrl() + "/Patient/1?_elements=name,maritalStatus", Patient.class, patient -> { String responseContent = ourCtx.newXmlParser().encodeResourceToString(patient); @@ -173,7 +184,7 @@ public class ElementsParamR4Test { @Test public void testReadSummaryTrue() throws Exception { verifyXmlAndJson( - "http://localhost:" + ourPort + "/Patient/1?_elements=name", + ourServer.getBaseUrl() + "/Patient/1?_elements=name", Patient.class, patient -> { String responseContent = ourCtx.newXmlParser().encodeResourceToString(patient); @@ -188,7 +199,7 @@ public class ElementsParamR4Test { @Test public void testSearchSummaryData() throws Exception { verifyXmlAndJson( - "http://localhost:" + ourPort + "/Patient?_elements=name,maritalStatus", + ourServer.getBaseUrl() + "/Patient?_elements=name,maritalStatus", bundle -> { assertEquals("1", bundle.getTotalElement().getValueAsString()); String responseContent = ourCtx.newXmlParser().encodeResourceToString(bundle.getEntry().get(0).getResource()); @@ -204,7 +215,7 @@ public class ElementsParamR4Test { @Test public void testSearchSummaryText() throws Exception { verifyXmlAndJson( - "http://localhost:" + ourPort + "/Patient?_elements=text&_pretty=true", + ourServer.getBaseUrl() + "/Patient?_elements=text&_pretty=true", bundle -> { assertEquals("1", bundle.getTotalElement().getValueAsString()); String responseContent = ourCtx.newXmlParser().encodeResourceToString(bundle.getEntry().get(0).getResource()); @@ -224,7 +235,7 @@ public class ElementsParamR4Test { public void testStandardElementsFilter() throws IOException { createProcedureWithLongChain(); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_include=*&_elements=reasonCode,status", + ourServer.getBaseUrl() + "/Procedure?_include=*&_elements=reasonCode,status", bundle -> { Procedure procedure = (Procedure) bundle.getEntry().get(0).getResource(); assertEquals("SUBSETTED", procedure.getMeta().getTag().get(0).getCode()); @@ -246,7 +257,7 @@ public class ElementsParamR4Test { public void testMultiResourceElementsFilter() throws IOException { createProcedureWithLongChain(); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_include=*&_elements=Procedure.reasonCode,Observation.status,Observation.subject,Observation.value", + ourServer.getBaseUrl() + "/Procedure?_include=*&_elements=Procedure.reasonCode,Observation.status,Observation.subject,Observation.value", bundle -> { Procedure procedure = (Procedure) bundle.getEntry().get(0).getResource(); assertEquals("SUBSETTED", procedure.getMeta().getTag().get(0).getCode()); @@ -272,7 +283,7 @@ public class ElementsParamR4Test { .setUrl("http://quantity") .setValue(Quantity.fromUcum("1.1", "mg")); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_elements=Procedure.extension", + ourServer.getBaseUrl() + "/Procedure?_elements=Procedure.extension", bundle -> { Procedure procedure = (Procedure) bundle.getEntry().get(0).getResource(); assertEquals("SUBSETTED", procedure.getMeta().getTag().get(0).getCode()); @@ -282,7 +293,7 @@ public class ElementsParamR4Test { }); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_elements=Procedure.extension.value", + ourServer.getBaseUrl() + "/Procedure?_elements=Procedure.extension.value", bundle -> { Procedure procedure = (Procedure) bundle.getEntry().get(0).getResource(); assertEquals("SUBSETTED", procedure.getMeta().getTag().get(0).getCode()); @@ -292,7 +303,7 @@ public class ElementsParamR4Test { }); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_elements=Procedure.extension.value.value", + ourServer.getBaseUrl() + "/Procedure?_elements=Procedure.extension.value.value", bundle -> { Procedure procedure = (Procedure) bundle.getEntry().get(0).getResource(); assertEquals("SUBSETTED", procedure.getMeta().getTag().get(0).getCode()); @@ -302,7 +313,7 @@ public class ElementsParamR4Test { }); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_elements=Procedure.reason", + ourServer.getBaseUrl() + "/Procedure?_elements=Procedure.reason", bundle -> { Procedure procedure = (Procedure) bundle.getEntry().get(0).getResource(); assertEquals("SUBSETTED", procedure.getMeta().getTag().get(0).getCode()); @@ -314,7 +325,7 @@ public class ElementsParamR4Test { public void testMultiResourceElementsFilterWithMetadataExcluded() throws IOException { createProcedureWithLongChain(); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_include=*&_elements=Procedure.reasonCode,Observation.status,Observation.subject,Observation.value&_elements:exclude=*.meta", + ourServer.getBaseUrl() + "/Procedure?_include=*&_elements=Procedure.reasonCode,Observation.status,Observation.subject,Observation.value&_elements:exclude=*.meta", bundle -> { Procedure procedure = (Procedure) bundle.getEntry().get(0).getResource(); assertEquals(true, procedure.getMeta().isEmpty()); @@ -340,7 +351,7 @@ public class ElementsParamR4Test { public void testMultiResourceElementsFilterDoesntAffectFocalResource() throws IOException { createProcedureWithLongChain(); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_include=*&_elements=Observation.subject", + ourServer.getBaseUrl() + "/Procedure?_include=*&_elements=Observation.subject", bundle -> { Procedure procedure = (Procedure) bundle.getEntry().get(0).getResource(); assertEquals(true, procedure.getMeta().isEmpty()); @@ -362,10 +373,10 @@ public class ElementsParamR4Test { @Test public void testMultiResourceElementsFilterWithMetadataExcludedStandardMode() throws IOException { - ourServlet.setElementsSupport(ElementsSupportEnum.STANDARD); + ourServer.getRestfulServer().setElementsSupport(ElementsSupportEnum.STANDARD); createProcedureWithLongChain(); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_include=*&_elements=Procedure.reasonCode,Observation.status,Observation.subject,Observation.value&_elements:exclude=*.meta", + ourServer.getBaseUrl() + "/Procedure?_include=*&_elements=Procedure.reasonCode,Observation.status,Observation.subject,Observation.value&_elements:exclude=*.meta", bundle -> { Procedure procedure = (Procedure) bundle.getEntry().get(0).getResource(); assertEquals(true, procedure.getMeta().isEmpty()); @@ -388,7 +399,7 @@ public class ElementsParamR4Test { public void testElementsFilterWithComplexPath() throws IOException { createProcedureWithLongChain(); verifyXmlAndJson( - "http://localhost:" + ourPort + "/Procedure?_elements=Procedure.reasonCode.coding.code", + ourServer.getBaseUrl() + "/Procedure?_elements=Procedure.reasonCode.coding.code", bundle -> { Procedure procedure = (Procedure) bundle.getEntry().get(0).getResource(); assertEquals("SUBSETTED", procedure.getMeta().getTag().get(0).getCode()); @@ -507,32 +518,8 @@ public class ElementsParamR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - - ourServlet.registerProvider(new DummyPatientResourceProvider()); - ourServlet.registerProvider(new DummyProcedureResourceProvider()); - ourServlet.registerProvider(new DummyObservationResourceProvider()); - - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/HistoryR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/HistoryR4Test.java index 6764e39cee8..d208c883aa8 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/HistoryR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/HistoryR4Test.java @@ -9,7 +9,9 @@ import ca.uhn.fhir.rest.annotation.Since; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.param.ParamPrefixEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; @@ -19,8 +21,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IPrimitiveType; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.DateTimeType; @@ -32,6 +34,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,15 +50,22 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class HistoryR4Test { private static final Logger ourLog = LoggerFactory.getLogger(HistoryR4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static DateRangeParam ourLastAt; private static InstantType ourLastSince; private static IPrimitiveType ourLastSince2; private static IPrimitiveType ourLastSince3; private static IPrimitiveType ourLastSince4; - private static int ourPort; - private static Server ourServer; + + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPlainProvider()) + .registerProvider(new DummyResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -69,7 +79,7 @@ public class HistoryR4Test { @Test public void testAt() throws Exception { { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/_history?_at=gt2001&_at=lt2005"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/_history?_at=gt2001&_at=lt2005"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); ourLog.info(responseContent); @@ -86,7 +96,7 @@ public class HistoryR4Test { @Test public void testInstanceHistory() throws Exception { { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/_history?_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/_history?_pretty=true"); String responseContent; try (CloseableHttpResponse status = ourClient.execute(httpGet)) { responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); @@ -96,8 +106,8 @@ public class HistoryR4Test { Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); assertEquals(2, bundle.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/Patient/ih1/_history/1", bundle.getEntry().get(0).getResource().getId()); - assertEquals("http://localhost:" + ourPort + "/Patient/ih1/_history/2", bundle.getEntry().get(1).getResource().getId()); + assertEquals(ourServer.getBaseUrl() + "/Patient/ih1/_history/1", bundle.getEntry().get(0).getResource().getId()); + assertEquals(ourServer.getBaseUrl() + "/Patient/ih1/_history/2", bundle.getEntry().get(1).getResource().getId()); } } @@ -105,7 +115,7 @@ public class HistoryR4Test { @Test public void testServerHistory() throws Exception { { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/_history"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/_history"); String responseContent; try (CloseableHttpResponse status = ourClient.execute(httpGet)) { responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); @@ -115,8 +125,8 @@ public class HistoryR4Test { Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); assertEquals(2, bundle.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/Patient/h1/_history/1", bundle.getEntry().get(0).getResource().getId()); - assertEquals("http://localhost:" + ourPort + "/Patient/h1/_history/2", bundle.getEntry().get(1).getResource().getId()); + assertEquals(ourServer.getBaseUrl() + "/Patient/h1/_history/1", bundle.getEntry().get(0).getResource().getId()); + assertEquals(ourServer.getBaseUrl() + "/Patient/h1/_history/2", bundle.getEntry().get(1).getResource().getId()); } } @@ -124,7 +134,7 @@ public class HistoryR4Test { @Test public void testSince() throws Exception { { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/_history?_since=2005"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/_history?_since=2005"); String responseContent; try (CloseableHttpResponse status = ourClient.execute(httpGet)) { responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); @@ -146,7 +156,7 @@ public class HistoryR4Test { @Test public void testTypeHistory() throws Exception { { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/_history"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/_history"); String responseContent; try (CloseableHttpResponse status = ourClient.execute(httpGet)) { responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); @@ -158,8 +168,8 @@ public class HistoryR4Test { Bundle bundle = ourCtx.newXmlParser().parseResource(Bundle.class, responseContent); assertEquals(2, bundle.getEntry().size()); - assertEquals("http://localhost:" + ourPort + "/Patient/th1/_history/1", bundle.getEntry().get(0).getResource().getId()); - assertEquals("http://localhost:" + ourPort + "/Patient/th1/_history/2", bundle.getEntry().get(1).getResource().getId()); + assertEquals(ourServer.getBaseUrl() + "/Patient/th1/_history/1", bundle.getEntry().get(0).getResource().getId()); + assertEquals(ourServer.getBaseUrl() + "/Patient/th1/_history/2", bundle.getEntry().get(1).getResource().getId()); } } @@ -170,7 +180,7 @@ public class HistoryR4Test { @Test public void testVread() throws Exception { { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/_history/456"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/_history/456"); String responseContent; try (CloseableHttpResponse status = ourClient.execute(httpGet)) { responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); @@ -185,34 +195,9 @@ public class HistoryR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPlainProvider plainProvider = new DummyPlainProvider(); - DummyResourceProvider patientProvider = new DummyResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.registerProviders(plainProvider, patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPlainProvider { @History diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/IncludeTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/IncludeTest.java index 247c425c19a..06143b2dafe 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/IncludeTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/IncludeTest.java @@ -12,7 +12,9 @@ import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.BundleUtil; import ca.uhn.fhir.util.ElementUtil; import ca.uhn.fhir.util.TestUtil; @@ -23,8 +25,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.DiagnosticReport; import org.hl7.fhir.r4.model.Observation; @@ -35,6 +37,7 @@ import org.hl7.fhir.r4.model.Reference; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.Arrays; @@ -53,14 +56,22 @@ import static org.junit.jupiter.api.Assertions.fail; public class IncludeTest { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(IncludeTest.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; - private static int ourPort; - private static Server ourServer; + private static final FhirContext ourCtx = FhirContext.forR4Cached(); + + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .registerProvider(new DummyDiagnosticReportResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .withServer(s->s.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE)); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testBadInclude() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo&_include=baz"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo&_include=baz"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { assertEquals(400, status.getStatusLine().getStatusCode()); String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -72,7 +83,7 @@ public class IncludeTest { @Test public void testIIncludedResourcesNonContained() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=normalInclude&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=normalInclude&_pretty=true"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -98,7 +109,7 @@ public class IncludeTest { @Test public void testIIncludedResourcesNonContainedInDeclaredExtension() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=declaredExtInclude&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=declaredExtInclude&_pretty=true"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -124,7 +135,7 @@ public class IncludeTest { @Test public void testIIncludedResourcesNonContainedInExtension() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=extInclude&_pretty=true"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=extInclude&_pretty=true"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -149,7 +160,7 @@ public class IncludeTest { @Test public void testIIncludedResourcesNonContainedInExtensionJson() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=extInclude&_pretty=true&_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=extInclude&_pretty=true&_format=json"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -205,7 +216,7 @@ public class IncludeTest { @Test public void testNoIncludes() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -221,7 +232,7 @@ public class IncludeTest { @Test public void testOneInclude() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -238,7 +249,7 @@ public class IncludeTest { @Test public void testOneIncludeIterate() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&" + Constants.PARAM_INCLUDE_ITERATE + "=foo"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&" + Constants.PARAM_INCLUDE_ITERATE + "=foo"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -255,7 +266,7 @@ public class IncludeTest { @Test public void testTwoInclude() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo&_include=bar"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?name=Hello&_include=foo&_include=bar"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -277,7 +288,7 @@ public class IncludeTest { @Test public void testStringInclude() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=stringInclude&_include=foo"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=stringInclude&_include=foo"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -478,34 +489,7 @@ public class IncludeTest { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - - @BeforeAll - public static void beforeClass() throws Exception { - - ourCtx = FhirContext.forR4(); - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - servlet.setBundleInclusionRule(BundleInclusionRule.BASED_ON_RESOURCE_PRESENCE); - servlet.setResourceProviders(patientProvider, new DummyDiagnosticReportResourceProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/LastNProviderTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/LastNProviderTest.java index 0a52c202083..899f97e383e 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/LastNProviderTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/LastNProviderTest.java @@ -40,9 +40,10 @@ public class LastNProviderTest extends BaseR4ServerTest { MyProvider provider = new MyProvider(); startServer(provider); - Bundle response = myClient + Bundle response = ourServer + .getFhirClient() .search() - .byUrl(myBaseUrl + "/Observation/$lastn?subject=Patient/123&category=http://terminology.hl7.org/CodeSystem/observation-category|laboratory,http://terminology.hl7.org/CodeSystem/observation-category|vital-signs&code=http://loinc.org|1111-1,http://loinc.org|2222-2&max=15") + .byUrl(ourServer.getBaseUrl() + "/Observation/$lastn?subject=Patient/123&category=http://terminology.hl7.org/CodeSystem/observation-category|laboratory,http://terminology.hl7.org/CodeSystem/observation-category|vital-signs&code=http://loinc.org|1111-1,http://loinc.org|2222-2&max=15") .returnBundle(Bundle.class) .execute(); assertEquals("abc123", response.getIdElement().getIdPart()); diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/MultitenancyR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/MultitenancyR4Test.java index b73b66cdf3e..07aad245a88 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/MultitenancyR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/MultitenancyR4Test.java @@ -8,30 +8,24 @@ import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.param.TokenAndListParam; import ca.uhn.fhir.rest.server.tenant.UrlBaseTenantIdentificationStrategy; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.HumanName; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -41,14 +35,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class MultitenancyR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(MultitenancyR4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static TokenAndListParam ourIdentifiers; private static String ourLastMethod; - private static int ourPort; - private static Server ourServer; private static String ourLastTenantId; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .withServer(s -> s.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy())) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -58,24 +60,8 @@ public class MultitenancyR4Test { @Test public void testUrlBaseStrategy() throws Exception { - ourServer = new Server(0); - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.JSON); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - servlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy()); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANT2/Patient?identifier=foo%7Cbar"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/TENANT2/Patient?identifier=foo%7Cbar"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -88,22 +74,22 @@ public class MultitenancyR4Test { Bundle resp = ourCtx.newJsonParser().parseResource(Bundle.class, responseContent); ourLog.debug(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); - assertEquals("http://localhost:" + ourPort + "/TENANT2/Patient?identifier=foo%7Cbar", resp.getLink("self").getUrl()); - assertEquals("http://localhost:" + ourPort + "/TENANT2/Patient/0", resp.getEntry().get(0).getFullUrl()); - assertEquals("http://localhost:"+ourPort+"/TENANT2/Patient/0", resp.getEntry().get(0).getResource().getId()); - assertThat(resp.getLink("next").getUrl(), startsWith("http://localhost:"+ourPort+"/TENANT2?_getpages=")); + assertEquals(ourServer.getBaseUrl() + "/TENANT2/Patient?identifier=foo%7Cbar", resp.getLink("self").getUrl()); + assertEquals(ourServer.getBaseUrl() + "/TENANT2/Patient/0", resp.getEntry().get(0).getFullUrl()); + assertEquals(ourServer.getBaseUrl() + "/TENANT2/Patient/0", resp.getEntry().get(0).getResource().getId()); + assertThat(resp.getLink("next").getUrl(), startsWith(ourServer.getBaseUrl() + "/TENANT2?_getpages=")); } finally { IOUtils.closeQuietly(status.getEntity().getContent()); } // GET the root - httpGet = new HttpGet("http://localhost:" + ourPort + "/"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/"); status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); assertEquals(400, status.getStatusLine().getStatusCode()); - assertThat(responseContent, containsString("\"diagnostics\":\""+ Msg.code(307) + "This is the base URL of a multitenant FHIR server. Unable to handle this request, as it does not contain a tenant ID.\"")); + assertThat(responseContent, containsString("\"diagnostics\":\"" + Msg.code(307) + "This is the base URL of a multitenant FHIR server. Unable to handle this request, as it does not contain a tenant ID.\"")); } finally { IOUtils.closeQuietly(status.getEntity().getContent()); } @@ -111,20 +97,11 @@ public class MultitenancyR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() { - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - } - - public static class DummyPatientResourceProvider implements IResourceProvider { + private static class DummyPatientResourceProvider implements IResourceProvider { @Override @@ -135,8 +112,8 @@ public class MultitenancyR4Test { @SuppressWarnings("rawtypes") @Search() public List search( - RequestDetails theRequestDetails, - @RequiredParam(name = Patient.SP_IDENTIFIER) TokenAndListParam theIdentifiers) { + RequestDetails theRequestDetails, + @RequiredParam(name = Patient.SP_IDENTIFIER) TokenAndListParam theIdentifiers) { ourLastMethod = "search"; ourIdentifiers = theIdentifiers; ourLastTenantId = theRequestDetails.getTenantId(); diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationGenericServer2R4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationGenericServer2R4Test.java index 125754b1f4a..faeb24863a6 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationGenericServer2R4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationGenericServer2R4Test.java @@ -9,7 +9,11 @@ import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; +import ca.uhn.fhir.rest.server.provider.HashMapResourceProvider; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -21,14 +25,15 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.ICompositeType; import org.hl7.fhir.instance.model.api.IPrimitiveType; import org.hl7.fhir.r4.model.CodeType; import org.hl7.fhir.r4.model.Coding; import org.hl7.fhir.r4.model.IdType; +import org.hl7.fhir.r4.model.MolecularSequence; import org.hl7.fhir.r4.model.Parameters; import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.StringType; @@ -39,7 +44,9 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.servlet.ServletException; +import jakarta.servlet.ServletException; +import org.junit.jupiter.api.extension.RegisterExtension; + import java.nio.charset.StandardCharsets; import java.util.List; import java.util.concurrent.TimeUnit; @@ -51,15 +58,23 @@ import static org.junit.jupiter.api.Assertions.fail; public class OperationGenericServer2R4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationGenericServer2R4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static IdType ourLastId; private static Object ourLastParam1; private static Object ourLastParam2; private static Object ourLastParam3; private static Parameters ourLastResourceParam; - private int myPort; - private Server myServer; + + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new HashMapResourceProvider<>(ourCtx, MolecularSequence.class)) + .withPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { @@ -103,14 +118,14 @@ public class OperationGenericServer2R4Test { } PatientProvider provider = new PatientProvider(); - startServer(provider); + ourServer.registerProvider(provider); Parameters p = new Parameters(); p.addParameter().setName("PARAM1").setValue(new CodeType("PARAM1val")); p.addParameter().setName("PARAM2").setValue(new Coding("sys", "val", "dis")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + myPort + "/Patient/123/$OP_INSTANCE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { assertEquals(200, status.getStatusLine().getStatusCode()); @@ -159,14 +174,14 @@ public class OperationGenericServer2R4Test { } PatientProvider provider = new PatientProvider(); - startServer(provider); + ourServer.registerProvider(provider); Parameters p = new Parameters(); p.addParameter().setName("PARAM1").setValue(new CodeType("PARAM1val")); p.addParameter().setName("PARAM1").setValue(new CodeType("PARAM1val2")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + myPort + "/Patient/123/$OP_INSTANCE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { assertEquals(200, status.getStatusLine().getStatusCode()); @@ -218,14 +233,14 @@ public class OperationGenericServer2R4Test { } PatientProvider provider = new PatientProvider(); - startServer(provider); + ourServer.registerProvider(provider); Parameters p = new Parameters(); p.addParameter().setName("PARAM1").setValue(new UriType("PARAM1val")); p.addParameter().setName("PARAM2").setValue(new StringType("PARAM2val")); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + myPort + "/Patient/123/$OP_INSTANCE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { assertEquals(200, status.getStatusLine().getStatusCode()); @@ -264,11 +279,11 @@ public class OperationGenericServer2R4Test { try { PatientProvider provider = new PatientProvider(); - startServer(provider); + ourServer.registerProvider(provider); fail(); - } catch (ServletException e) { + } catch (ConfigurationException e) { ConfigurationException ce = (ConfigurationException) e.getCause(); - assertThat(ce.getMessage(), containsString("Failure scanning class PatientProvider: " + Msg.code(405) + "Non assignable parameter typeName=\"code\" specified on method public org.hl7.fhir.r4.model.Parameters ca.uhn.fhir.rest.server.OperationGenericServer2R4Test")); + assertThat(ce.getMessage(), containsString(Msg.code(405) + "Non assignable parameter typeName=\"code\" specified on method public org.hl7.fhir.r4.model.Parameters ca.uhn.fhir.rest.server.OperationGenericServer2R4Test")); } } @@ -295,9 +310,9 @@ public class OperationGenericServer2R4Test { } PlainProvider provider = new PlainProvider(); - startServer(provider); + ourServer.registerProvider(provider); - HttpGet httpPost = new HttpGet("http://localhost:" + myPort + "/Patient/123/$OP_INSTANCE"); + HttpGet httpPost = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); try (CloseableHttpResponse status = ourClient.execute(httpPost)) { String response = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(response); @@ -324,37 +339,19 @@ public class OperationGenericServer2R4Test { PlainProvider provider = new PlainProvider(); try { - startServer(provider); + ourServer.registerProvider(provider); fail(); - } catch (ServletException e) { - Throwable cause = e.getRootCause(); - assertEquals(Msg.code(288) + "Failure scanning class PlainProvider: " + Msg.code(423) + "Failed to bind method public org.hl7.fhir.r4.model.Parameters ca.uhn.fhir.rest.server.OperationGenericServer2R4Test$2PlainProvider.opInstance() - " + Msg.code(1684) + "Unknown resource name \"FOO\" (this name is not known in FHIR version \"R4\")", cause.getMessage()); + } catch (ConfigurationException e) { + Throwable cause = e.getCause(); + assertEquals(Msg.code(423) + "Failed to bind method public org.hl7.fhir.r4.model.Parameters ca.uhn.fhir.rest.server.OperationGenericServer2R4Test$2PlainProvider.opInstance() - " + Msg.code(1684) + "Unknown resource name \"FOO\" (this name is not known in FHIR version \"R4\")", cause.getMessage()); } } - private void startServer(Object theProvider) throws Exception { - myServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); - - servlet.setFhirContext(ourCtx); - servlet.registerProvider(theProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - myServer.setHandler(proxyHandler); - JettyUtil.startServer(myServer); - myPort = JettyUtil.getPortForStartedServer(myServer); - } - @AfterEach public void after() throws Exception { - JettyUtil.closeServer(myServer); + TestUtil.randomizeLocaleAndTimezone(); } @AfterAll @@ -362,15 +359,4 @@ public class OperationGenericServer2R4Test { TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() { - ourCtx = FhirContext.forR4(); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationGenericServerR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationGenericServerR4Test.java index 999e7ffc1ae..56e17ae4a0f 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationGenericServerR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationGenericServerR4Test.java @@ -8,7 +8,9 @@ import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -20,8 +22,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Parameters; @@ -31,6 +33,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -42,16 +45,23 @@ import static org.junit.jupiter.api.Assertions.assertNull; public class OperationGenericServerR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OperationGenericServerR4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx; + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static IdType ourLastId; private static String ourLastMethod; private static StringType ourLastParam1; private static Patient ourLastParam2; - private static int ourPort; - private static Server ourServer; private static Parameters ourLastResourceParam; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .registerProvider(new PlainProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastParam1 = null; @@ -69,7 +79,7 @@ public class OperationGenericServerR4Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$OP_INSTANCE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/123/$OP_INSTANCE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); CloseableHttpResponse status = ourClient.execute(httpPost); try { @@ -99,7 +109,7 @@ public class OperationGenericServerR4Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/$OP_SERVER"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/$OP_SERVER"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); CloseableHttpResponse status = ourClient.execute(httpPost); try { @@ -126,7 +136,7 @@ public class OperationGenericServerR4Test { p.addParameter().setName("PARAM2").setResource(new Patient().setActive(true)); String inParamsStr = ourCtx.newXmlParser().encodeResourceToString(p); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/$OP_TYPE"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient/$OP_TYPE"); httpPost.setEntity(new StringEntity(inParamsStr, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); CloseableHttpResponse status = ourClient.execute(httpPost); try { @@ -150,7 +160,7 @@ public class OperationGenericServerR4Test { @Test public void testOperationWithGetUsingParams() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$OP_TYPE?PARAM1=PARAM1val"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/$OP_TYPE?PARAM1=PARAM1val"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String response = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -174,7 +184,7 @@ public class OperationGenericServerR4Test { @Test public void testSearchGetsClassifiedAppropriately() throws Exception { - HttpGet httpPost = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpPost = new HttpGet(ourServer.getBaseUrl() + "/Patient"); CloseableHttpResponse status = ourClient.execute(httpPost); try { assertEquals(200, status.getStatusLine().getStatusCode()); @@ -275,35 +285,8 @@ public class OperationGenericServerR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourCtx = FhirContext.forR4(); - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.XML); - - servlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(2)); - - servlet.setFhirContext(ourCtx); - servlet.setResourceProviders(new PatientProvider()); - servlet.setPlainProviders(new PlainProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationServerR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationServerR4Test.java index 3215597a114..20744e7ca0f 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationServerR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/OperationServerR4Test.java @@ -36,8 +36,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PagingTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PagingTest.java index aed0f118745..f3b35670e85 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PagingTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PagingTest.java @@ -49,7 +49,7 @@ import static org.mockito.Mockito.when; */ public class PagingTest { - private FhirContext ourContext = FhirContext.forR4(); + private FhirContext ourContext = FhirContext.forR4Cached(); @RegisterExtension public RestfulServerExtension myServerExtension = new RestfulServerExtension(ourContext); diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PagingUsingNamedPagesR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PagingUsingNamedPagesR4Test.java index 6a05c7f0ff2..ce11063307e 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PagingUsingNamedPagesR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PagingUsingNamedPagesR4Test.java @@ -5,7 +5,10 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.IBundleProvider; +import ca.uhn.fhir.rest.server.interceptor.ExceptionInterceptorMethodTest; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; import org.apache.commons.io.IOUtils; @@ -17,8 +20,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Patient; @@ -26,6 +29,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -47,20 +51,25 @@ import static org.mockito.Mockito.when; public class PagingUsingNamedPagesR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(PagingUsingNamedPagesR4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); - private static int ourPort; - - private static Server ourServer; - private static RestfulServer servlet; + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static IBundleProvider ourNextBundleProvider; private IPagingProvider myPagingProvider; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { myPagingProvider = mock(IPagingProvider.class); when(myPagingProvider.canStoreSearchResults()).thenReturn(true); - servlet.setPagingProvider(myPagingProvider); + ourServer.getRestfulServer().setPagingProvider(myPagingProvider); ourNextBundleProvider = null; } @@ -118,32 +127,32 @@ public class PagingUsingNamedPagesR4Test { Bundle bundle; // Initial search - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=xml"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=xml"); bundle = executeAndReturnBundle(httpGet, EncodingEnum.XML); linkSelf = bundle.getLink(Constants.LINK_SELF).getUrl(); - assertEquals("http://localhost:" + ourPort + "/Patient?_format=xml", linkSelf); + assertEquals(ourServer.getBaseUrl() + "/Patient?_format=xml", linkSelf); linkNext = bundle.getLink(Constants.LINK_NEXT).getUrl(); - assertEquals("http://localhost:" + ourPort + "?_getpages=SEARCHID0&_pageId=PAGEID1&_format=xml&_bundletype=searchset", linkNext); + assertEquals(ourServer.getBaseUrl() + "?_getpages=SEARCHID0&_pageId=PAGEID1&_format=xml&_bundletype=searchset", linkNext); assertNull(bundle.getLink(Constants.LINK_PREVIOUS)); // Fetch the next page httpGet = new HttpGet(linkNext); bundle = executeAndReturnBundle(httpGet, EncodingEnum.XML); linkSelf = bundle.getLink(Constants.LINK_SELF).getUrl(); - assertEquals("http://localhost:" + ourPort + "?_getpages=SEARCHID0&_pageId=PAGEID1&_format=xml&_bundletype=searchset", linkSelf); + assertEquals(ourServer.getBaseUrl() + "?_getpages=SEARCHID0&_pageId=PAGEID1&_format=xml&_bundletype=searchset", linkSelf); linkNext = bundle.getLink(Constants.LINK_NEXT).getUrl(); - assertEquals("http://localhost:" + ourPort + "?_getpages=SEARCHID0&_pageId=PAGEID2&_format=xml&_bundletype=searchset", linkNext); + assertEquals(ourServer.getBaseUrl() + "?_getpages=SEARCHID0&_pageId=PAGEID2&_format=xml&_bundletype=searchset", linkNext); linkPrev = bundle.getLink(Constants.LINK_PREVIOUS).getUrl(); - assertEquals("http://localhost:" + ourPort + "?_getpages=SEARCHID0&_pageId=PAGEID0&_format=xml&_bundletype=searchset", linkPrev); + assertEquals(ourServer.getBaseUrl() + "?_getpages=SEARCHID0&_pageId=PAGEID0&_format=xml&_bundletype=searchset", linkPrev); // Fetch the next page httpGet = new HttpGet(linkNext); bundle = executeAndReturnBundle(httpGet, EncodingEnum.XML); linkSelf = bundle.getLink(Constants.LINK_SELF).getUrl(); - assertEquals("http://localhost:" + ourPort + "?_getpages=SEARCHID0&_pageId=PAGEID2&_format=xml&_bundletype=searchset", linkSelf); + assertEquals(ourServer.getBaseUrl() + "?_getpages=SEARCHID0&_pageId=PAGEID2&_format=xml&_bundletype=searchset", linkSelf); assertNull(bundle.getLink(Constants.LINK_NEXT)); linkPrev = bundle.getLink(Constants.LINK_PREVIOUS).getUrl(); - assertEquals("http://localhost:" + ourPort + "?_getpages=SEARCHID0&_pageId=PAGEID1&_format=xml&_bundletype=searchset", linkPrev); + assertEquals(ourServer.getBaseUrl() + "?_getpages=SEARCHID0&_pageId=PAGEID1&_format=xml&_bundletype=searchset", linkPrev); } @Test @@ -153,7 +162,7 @@ public class PagingUsingNamedPagesR4Test { when(myPagingProvider.retrieveResultList(any(), nullable(String.class), nullable(String.class))).thenReturn(null); // With ID - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "?_getpages=SEARCHID0&_pageId=PAGEID0&_format=xml&_bundletype=FOO" + UrlUtil.escapeUrlParam("\"")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "?_getpages=SEARCHID0&_pageId=PAGEID0&_format=xml&_bundletype=FOO" + UrlUtil.escapeUrlParam("\"")); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(responseContent); @@ -162,7 +171,7 @@ public class PagingUsingNamedPagesR4Test { } // Without ID - httpGet = new HttpGet("http://localhost:" + ourPort + "?_getpages=SEARCHID0&_format=xml&_bundletype=FOO" + UrlUtil.escapeUrlParam("\"")); + httpGet = new HttpGet(ourServer.getBaseUrl() + "?_getpages=SEARCHID0&_format=xml&_bundletype=FOO" + UrlUtil.escapeUrlParam("\"")); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(responseContent); @@ -181,7 +190,7 @@ public class PagingUsingNamedPagesR4Test { when(myPagingProvider.retrieveResultList(any(), eq("SEARCHID0"), eq("PAGEID0"))).thenReturn(provider0); // Initial search - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "?_getpages=SEARCHID0&_pageId=PAGEID0&_format=xml&_bundletype=FOO" + UrlUtil.escapeUrlParam("\"")); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "?_getpages=SEARCHID0&_pageId=PAGEID0&_format=xml&_bundletype=FOO" + UrlUtil.escapeUrlParam("\"")); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(responseContent); @@ -197,37 +206,10 @@ public class PagingUsingNamedPagesR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - servlet = new RestfulServer(ourCtx); - servlet.setDefaultResponseEncoding(EncodingEnum.JSON); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(600000).build()); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { + private static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PatientResourceProvider.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PatientResourceProvider.java index dd278c04bc9..80c9a1f6484 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PatientResourceProvider.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PatientResourceProvider.java @@ -29,7 +29,7 @@ public class PatientResourceProvider implements IResourceProvider @Search() public IBundleProvider search( - javax.servlet.http.HttpServletRequest theServletRequest, + jakarta.servlet.http.HttpServletRequest theServletRequest, @Description(shortDefinition="The resource identity") @OptionalParam(name="_id") diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PlainProviderR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PlainProviderR4Test.java index 1a11ebd4cfd..72599912728 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PlainProviderR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PlainProviderR4Test.java @@ -10,7 +10,10 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.annotation.Since; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.TokenParam; +import ca.uhn.fhir.rest.server.provider.HashMapResourceProvider; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -20,8 +23,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hamcrest.core.IsEqual; import org.hamcrest.core.StringStartsWith; import org.hl7.fhir.instance.model.api.IBaseResource; @@ -31,6 +34,7 @@ import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Identifier; import org.hl7.fhir.r4.model.InstantType; import org.hl7.fhir.r4.model.IntegerType; +import org.hl7.fhir.r4.model.Observation; import org.hl7.fhir.r4.model.Organization; import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.Resource; @@ -38,6 +42,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.HashMap; @@ -51,47 +56,26 @@ import static org.junit.jupiter.api.Assertions.assertNull; public class PlainProviderR4Test { - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(PlainProviderR4Test.class); - private CloseableHttpClient myClient; - private int myPort; - private RestfulServer myRestfulServer; - private Server myServer; - @AfterEach - public void after() throws Exception { - JettyUtil.closeServer(myServer); - } + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new HashMapResourceProvider<>(ourCtx, Observation.class)) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .withServletPath("/fhir/context/*"); - @BeforeEach - public void before() throws Exception { - myServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - ServletHolder servletHolder = new ServletHolder(); - myRestfulServer = new RestfulServer(ourCtx); - myRestfulServer.setDefaultResponseEncoding(EncodingEnum.XML); - servletHolder.setServlet(myRestfulServer); - proxyHandler.addServletWithMapping(servletHolder, "/fhir/context/*"); - myServer.setHandler(proxyHandler); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - - builder.setConnectionManager(connectionManager); - myClient = builder.build(); - - } + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testGlobalHistory() throws Exception { GlobalHistoryProvider provider = new GlobalHistoryProvider(); - myRestfulServer.setProviders(provider); - JettyUtil.startServer(myServer); - myPort = JettyUtil.getPortForStartedServer(myServer); + ourServer.registerProvider(provider); - String baseUri = "http://localhost:" + myPort + "/fhir/context"; - HttpResponse status = myClient.execute(new HttpGet(baseUri + "/_history?_since=2012-01-02T00%3A01%3A02&_count=12")); + String baseUri = ourServer.getBaseUrl(); + HttpResponse status = ourClient.execute(new HttpGet(baseUri + "/_history?_since=2012-01-02T00%3A01%3A02&_count=12")); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -103,7 +87,7 @@ public class PlainProviderR4Test { assertThat(provider.myLastSince.getValueAsString(), StringStartsWith.startsWith("2012-01-02T00:01:02")); assertThat(provider.myLastCount.getValueAsString(), IsEqual.equalTo("12")); - status = myClient.execute(new HttpGet(baseUri + "/_history?&_count=12")); + status = ourClient.execute(new HttpGet(baseUri + "/_history?&_count=12")); responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -112,7 +96,7 @@ public class PlainProviderR4Test { assertNull(provider.myLastSince); assertThat(provider.myLastCount.getValueAsString(), IsEqual.equalTo("12")); - status =myClient.execute(new HttpGet(baseUri + "/_history?_since=2012-01-02T00%3A01%3A02")); + status =ourClient.execute(new HttpGet(baseUri + "/_history?_since=2012-01-02T00%3A01%3A02")); responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -125,12 +109,10 @@ public class PlainProviderR4Test { @Test public void testGlobalHistoryNoParams() throws Exception { GlobalHistoryProvider provider = new GlobalHistoryProvider(); - myRestfulServer.setProviders(provider); - JettyUtil.startServer(myServer); - myPort = JettyUtil.getPortForStartedServer(myServer); + ourServer.registerProvider(provider); - String baseUri = "http://localhost:" + myPort + "/fhir/context"; - CloseableHttpResponse status = myClient.execute(new HttpGet(baseUri + "/_history")); + String baseUri = ourServer.getBaseUrl(); + CloseableHttpResponse status = ourClient.execute(new HttpGet(baseUri + "/_history")); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); @@ -143,14 +125,12 @@ public class PlainProviderR4Test { @Test public void testSearchByParamIdentifier() throws Exception { - myRestfulServer.setProviders(new SearchProvider()); - JettyUtil.startServer(myServer); - myPort = JettyUtil.getPortForStartedServer(myServer); + ourServer.registerProvider(new SearchProvider()); - String baseUri = "http://localhost:" + myPort + "/fhir/context"; + String baseUri = ourServer.getBaseUrl(); String uri = baseUri + "/Patient?identifier=urn:hapitest:mrns%7C00001"; HttpGet httpGet = new HttpGet(uri); - try (CloseableHttpResponse status = myClient.execute(httpGet)) { + try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PreferTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PreferTest.java index 45891b4d569..a412d83006a 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PreferTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/PreferTest.java @@ -7,8 +7,11 @@ import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.ResourceParam; import ca.uhn.fhir.rest.annotation.Update; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -19,8 +22,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseOperationOutcome; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.IdType; @@ -30,6 +33,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.concurrent.TimeUnit; @@ -41,14 +45,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; public class PreferTest { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(PreferTest.class); - private static int ourPort; - private static Server ourServer; private static IBaseOperationOutcome ourReturnOperationOutcome; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourReturnOperationOutcome = null; @@ -64,7 +75,7 @@ public class PreferTest { oo.addIssue().setDiagnostics("DIAG"); ourReturnOperationOutcome = oo; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_MINIMAL); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -79,8 +90,8 @@ public class PreferTest { assertThat(responseContent, is(emptyOrNullString())); // assertThat(status.getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue(), not(containsString("fhir"))); assertNull(status.getFirstHeader(Constants.HEADER_CONTENT_TYPE)); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); } @@ -94,7 +105,7 @@ public class PreferTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -108,8 +119,8 @@ public class PreferTest { assertEquals(Constants.STATUS_HTTP_201_CREATED, status.getStatusLine().getStatusCode()); assertThat(responseContent, containsString("DIAG")); assertEquals("application/xml+fhir;charset=utf-8", status.getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue().toLowerCase().replace(" ", "")); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); } @@ -119,7 +130,7 @@ public class PreferTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_REPRESENTATION); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); @@ -133,8 +144,8 @@ public class PreferTest { assertEquals(Constants.STATUS_HTTP_201_CREATED, status.getStatusLine().getStatusCode()); assertThat(status.getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue(), containsString(Constants.CT_FHIR_XML)); assertEquals("", responseContent); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); } @@ -144,7 +155,7 @@ public class PreferTest { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -155,38 +166,16 @@ public class PreferTest { ourLog.info("Response was:\n{}", responseContent); assertEquals(201, status.getStatusLine().getStatusCode()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); - assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); + assertEquals(ourServer.getBaseUrl() + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); } @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } public static class PatientProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ResponseCodeModifyingResourceProviderTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ResponseCodeModifyingResourceProviderTest.java index c4526ff9ee6..06be8295137 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ResponseCodeModifyingResourceProviderTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ResponseCodeModifyingResourceProviderTest.java @@ -15,7 +15,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import javax.servlet.ServletRequest; +import jakarta.servlet.ServletRequest; import static ca.uhn.fhir.rest.api.Constants.STATUS_HTTP_202_ACCEPTED; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/RestfulServerTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/RestfulServerTest.java index 7624f4c23d1..d7fdff76d8d 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/RestfulServerTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/RestfulServerTest.java @@ -23,8 +23,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; import java.io.Serializable; import java.util.List; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeR4Test.java index 9034759aa55..77defe6e41c 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchBundleProviderWithNoSizeR4Test.java @@ -2,10 +2,14 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.param.TokenAndListParam; +import ca.uhn.fhir.rest.server.interceptor.ExceptionInterceptorMethodTest; import ca.uhn.fhir.rest.server.method.ResponsePage; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.collect.Lists; import org.apache.commons.io.IOUtils; @@ -15,8 +19,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Bundle.BundleLinkComponent; @@ -25,6 +29,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -42,15 +47,20 @@ import static org.mockito.Mockito.when; public class SearchBundleProviderWithNoSizeR4Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static TokenAndListParam ourIdentifiers; private static IBundleProvider ourLastBundleProvider; private static String ourLastMethod; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchBundleProviderWithNoSizeR4Test.class); - private static int ourPort; - private static Server ourServer; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -86,7 +96,7 @@ public class SearchBundleProviderWithNoSizeR4Test { BundleLinkComponent linkNext; try { - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=json"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=json"); status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(responseContent); @@ -146,33 +156,9 @@ public class SearchBundleProviderWithNoSizeR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } public static class DummyPatientResourceProvider implements IResourceProvider { diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamR4Test.java index 3235d7342e4..31eeb8243fd 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchHasParamR4Test.java @@ -3,10 +3,13 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.HasAndListParam; import ca.uhn.fhir.rest.param.HasParam; import ca.uhn.fhir.rest.param.TokenParam; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; @@ -16,8 +19,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.HumanName; import org.hl7.fhir.r4.model.Patient; @@ -25,6 +28,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -34,14 +38,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchHasParamR4Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchHasParamR4Test.class); - private static int ourPort; - private static Server ourServer; private static String ourLastMethod; private static HasAndListParam ourLastParam; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -50,7 +60,7 @@ public class SearchHasParamR4Test { @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_has:Encounter:patient:type=SURG"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_has:Encounter:patient:type=SURG"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -67,34 +77,9 @@ public class SearchHasParamR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - public static class DummyPatientResourceProvider implements IResourceProvider { @Override diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchR4Test.java index 198285c87e5..4bf2de0a10e 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchR4Test.java @@ -38,6 +38,7 @@ import org.hl7.fhir.r4.model.OperationOutcome; import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.Reference; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -81,6 +82,11 @@ public class SearchR4Test { myCtx.setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator()); } + @AfterEach + public void after() { + myCtx.setNarrativeGenerator(null); + } + private Bundle executeSearchAndValidateHasLinkNext(HttpGet httpGet, EncodingEnum theExpectEncoding) throws IOException { Bundle bundle = executeSearch(httpGet, theExpectEncoding); String linkNext = bundle.getLink(Constants.LINK_NEXT).getUrl(); diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSearchServerR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSearchServerR4Test.java index 2698f569afb..7f670af8b28 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSearchServerR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSearchServerR4Test.java @@ -20,7 +20,9 @@ import ca.uhn.fhir.rest.param.StringOrListParam; import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.rest.param.TokenOrListParam; import ca.uhn.fhir.rest.param.TokenParam; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.BundleUtil; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; @@ -38,17 +40,19 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.BaseResource; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Observation; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.nio.charset.Charset; import java.util.ArrayList; @@ -72,27 +76,39 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class SearchSearchServerR4Test { - private static CloseableHttpClient ourClient; - private static final FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static IServerAddressStrategy ourDefaultAddressStrategy; private static StringAndListParam ourLastAndList; private static Set ourLastIncludes; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchSearchServerR4Test.class); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; - @BeforeEach + @RegisterExtension + public static RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .registerProvider(new DummyObservationResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(10)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + public static HttpClientExtension ourClient = new HttpClientExtension(); + + @BeforeEach public void before() { - ourServlet.setServerAddressStrategy(ourDefaultAddressStrategy); - ourLastIncludes = null; + ourServer.setServerAddressStrategy(new IncomingRequestAddressStrategy()); + ourLastIncludes = null; ourLastAndList = null; + ourCtx.setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator()); + } + + @AfterEach + public void after() { + ourCtx.setNarrativeGenerator(null); } @Test public void testEncodeConvertsReferencesToRelative() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchWithRef"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchWithRef"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -110,7 +126,7 @@ public class SearchSearchServerR4Test { @Test public void testGetPagesWithPost() throws Exception { - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl()); List parameters = Collections.singletonList(new BasicNameValuePair("_getpages", "AAA")); httpPost.setEntity(new UrlEncodedFormEntity(parameters)); @@ -124,7 +140,7 @@ public class SearchSearchServerR4Test { @Test public void testOmitEmptyOptionalParam() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id="); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_id="); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -139,8 +155,7 @@ public class SearchSearchServerR4Test { @Test public void testParseEscapedValues() throws Exception { - String b = "http://localhost:" + - ourPort + + String b = ourServer.getBaseUrl() + "/Patient?" + escapeUrlParam("findPatientWithAndList") + '=' + escapeUrlParam("NE\\,NE,NE\\,NE") + '&' + escapeUrlParam("findPatientWithAndList") + '=' + escapeUrlParam("NE\\\\NE") + '&' + @@ -169,7 +184,7 @@ public class SearchSearchServerR4Test { @Test public void testReturnLinks() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findWithLinks"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=findWithLinks"); CloseableHttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); @@ -188,9 +203,9 @@ public class SearchSearchServerR4Test { */ @Test public void testReturnLinksWithAddressStrategy() throws Exception { - ourServlet.setServerAddressStrategy(new HardcodedServerAddressStrategy("https://blah.com/base")); + ourServer.setServerAddressStrategy(new HardcodedServerAddressStrategy("https://blah.com/base")); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findWithLinks"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=findWithLinks"); CloseableHttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); @@ -214,7 +229,7 @@ public class SearchSearchServerR4Test { * Load the second page */ String urlPart = linkNext.substring(linkNext.indexOf('?')); - String link = "http://localhost:" + ourPort + urlPart; + String link = ourServer.getBaseUrl() + urlPart; httpGet = new HttpGet(link); status = ourClient.execute(httpGet); @@ -235,7 +250,7 @@ public class SearchSearchServerR4Test { @Test public void testSearchById() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=aaa"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_id=aaa"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -249,7 +264,7 @@ public class SearchSearchServerR4Test { @Test public void testSearchByIdUsingClient() { - IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort); + IGenericClient client = ourCtx.newRestfulGenericClient(ourServer.getBaseUrl()); Bundle bundle = client .search() @@ -265,7 +280,7 @@ public class SearchSearchServerR4Test { @Test public void testSearchByPost() throws Exception { - HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search"); + HttpPost filePost = new HttpPost(ourServer.getBaseUrl() + "/Patient/_search"); // add parameters to the post method List parameters = new ArrayList<>(); @@ -290,7 +305,7 @@ public class SearchSearchServerR4Test { */ @Test public void testSearchByPostWithInvalidPostUrl() throws Exception { - HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient?name=Central"); // should end with + HttpPost filePost = new HttpPost(ourServer.getBaseUrl() + "/Patient?name=Central"); // should end with // _search // add parameters to the post method @@ -314,7 +329,7 @@ public class SearchSearchServerR4Test { */ @Test public void testSearchByPostWithMissingContentType() throws Exception { - HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient?name=Central"); // should end with + HttpPost filePost = new HttpPost(ourServer.getBaseUrl() + "/Patient?name=Central"); // should end with // _search HttpEntity sendentity = new ByteArrayEntity(new byte[] { 1, 2, 3, 4 }); @@ -333,7 +348,7 @@ public class SearchSearchServerR4Test { */ @Test public void testSearchByPostWithParamsInBodyAndUrl() throws Exception { - HttpPost filePost = new HttpPost("http://localhost:" + ourPort + "/Patient/_search?name=Central"); + HttpPost filePost = new HttpPost(ourServer.getBaseUrl() + "/Patient/_search?name=Central"); // add parameters to the post method List parameters = new ArrayList<>(); @@ -359,7 +374,7 @@ public class SearchSearchServerR4Test { @Test public void testSearchCompartment() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/fooCompartment"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/123/fooCompartment"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); ourLog.info(responseContent); @@ -375,7 +390,7 @@ public class SearchSearchServerR4Test { @Test public void testSearchGetWithUnderscoreSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/_search?subject%3APatient=100&name=3141-9%2C8302-2%2C8287-5%2C39156-5"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Observation/_search?subject%3APatient=100&name=3141-9%2C8302-2%2C8287-5%2C39156-5"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); @@ -395,7 +410,7 @@ public class SearchSearchServerR4Test { @Test public void testSearchIncludesParametersIncludes() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchIncludes&_include=foo&_include:recurse=bar"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchIncludes&_include=foo&_include:recurse=bar"); CloseableHttpResponse status = ourClient.execute(httpGet); IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); @@ -408,7 +423,7 @@ public class SearchSearchServerR4Test { @Test public void testSearchIncludesParametersIncludesList() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchIncludesList&_include=foo&_include:recurse=bar"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchIncludesList&_include=foo&_include:recurse=bar"); CloseableHttpResponse status = ourClient.execute(httpGet); IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); @@ -421,7 +436,7 @@ public class SearchSearchServerR4Test { @Test public void testSearchIncludesParametersNone() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchIncludes"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=searchIncludes"); CloseableHttpResponse status = ourClient.execute(httpGet); IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); @@ -433,7 +448,7 @@ public class SearchSearchServerR4Test { @Test public void testSearchWithOrList() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?findPatientWithOrList=aaa,bbb"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?findPatientWithOrList=aaa,bbb"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -449,7 +464,7 @@ public class SearchSearchServerR4Test { @Test public void testSearchWithTokenParameter() throws Exception { String token = UrlUtil.escapeUrlParam("http://www.dmix.gov/vista/2957|301"); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?tokenParam=" + token); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?tokenParam=" + token); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); IOUtils.closeQuietly(status.getEntity().getContent()); @@ -464,7 +479,7 @@ public class SearchSearchServerR4Test { @Test public void testSpecificallyNamedQueryGetsPrecedence() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?AAA=123"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?AAA=123"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); @@ -478,7 +493,7 @@ public class SearchSearchServerR4Test { // Now the named query - httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findPatientByAAA&AAA=123"); + httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=findPatientByAAA&AAA=123"); status = ourClient.execute(httpGet); responseContent = IOUtils.toString(status.getEntity().getContent(), Charset.defaultCharset()); @@ -493,37 +508,9 @@ public class SearchSearchServerR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - ourServlet.getFhirContext().setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator()); - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(10)); - - ourServlet.setResourceProviders(patientProvider, new DummyObservationResourceProvider()); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - ourDefaultAddressStrategy = ourServlet.getServerAddressStrategy(); - } - public static class DummyObservationResourceProvider implements IResourceProvider { @Override @@ -675,7 +662,7 @@ public class SearchSearchServerR4Test { public Patient searchWithRef() { Patient patient = new Patient(); patient.setId("Patient/1/_history/1"); - patient.getManagingOrganization().setReference("http://localhost:" + ourPort + "/Organization/555/_history/666"); + patient.getManagingOrganization().setReference(ourServer.getBaseUrl() + "/Organization/555/_history/666"); return patient; } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSortR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSortR4Test.java index de38b5e2900..a770721dd91 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSortR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SearchSortR4Test.java @@ -3,9 +3,12 @@ package ca.uhn.fhir.rest.server; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.annotation.Sort; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.SortOrderEnum; import ca.uhn.fhir.rest.api.SortSpec; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -14,8 +17,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.HumanName; import org.hl7.fhir.r4.model.Patient; @@ -23,6 +26,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; @@ -32,14 +36,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SearchSortR4Test { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchSortR4Test.class); - private static int ourPort; - private static Server ourServer; private static String ourLastMethod; private static SortSpec ourLastSortSpec; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.JSON) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { ourLastMethod = null; @@ -48,7 +59,7 @@ public class SearchSortR4Test { @Test public void testSearch() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_sort=param1,-param2,param3,-param4"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_sort=param1,-param2,param3,-param4"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String responseContent = IOUtils.toString(status.getEntity().getContent()); @@ -76,35 +87,10 @@ public class SearchSortR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - servlet.setPagingProvider(new FifoMemoryPagingProvider(10)); - - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { + private static class DummyPatientResourceProvider implements IResourceProvider { @Override public Class getResourceType() { diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerConcurrencyTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerConcurrencyTest.java index 45ed11d0b3e..ec77302fa1c 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerConcurrencyTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerConcurrencyTest.java @@ -24,10 +24,10 @@ import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import javax.annotation.Nonnull; -import javax.servlet.ReadListener; -import javax.servlet.ServletInputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.IOException; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionR4Test.java index e76dbb0c678..3c095277e1b 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerInvalidDefinitionR4Test.java @@ -1,5 +1,6 @@ package ca.uhn.fhir.rest.server; +import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.i18n.Msg; import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; @@ -16,6 +17,7 @@ import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.test.utilities.server.MockServletUtil; import com.google.common.collect.Lists; +import jakarta.servlet.ServletException; import org.hamcrest.core.StringContains; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.DateType; @@ -24,8 +26,7 @@ import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.StringType; import org.junit.jupiter.api.Test; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; @@ -39,7 +40,7 @@ public class ServerInvalidDefinitionR4Test extends BaseR4ServerTest { try { startServer(new UpdateWithWrongConditionalUrlType()); fail(); - } catch (ServletException e) { + } catch (ConfigurationException e) { assertThat(e.getCause().toString(), StringContains.containsString("ConfigurationException")); assertThat(e.getCause().toString(), StringContains.containsString( "Parameters annotated with @ConditionalUrlParam must be of type String, found incorrect parameter in method \"public ca.uhn.fhir.rest.api.MethodOutcome ca.uhn.fhir.rest.server.ServerInvalidDefinitionR4Test$UpdateWithWrongConditionalUrlType.update(ca.uhn.fhir.rest.param.TokenParam,org.hl7.fhir.r4.model.Patient)")); @@ -51,7 +52,7 @@ public class ServerInvalidDefinitionR4Test extends BaseR4ServerTest { try { startServer(new UpdateWithWrongResourceType()); fail(); - } catch (ServletException e) { + } catch (ConfigurationException e) { assertThat(e.getCause().toString(), StringContains.containsString("ConfigurationException")); assertThat(e.getCause().toString(), StringContains .containsString("Method 'update' is annotated with @ResourceParam but has a type that is not an implementation of org.hl7.fhir.instance.model.api.IBaseResource or String or byte[]")); @@ -63,7 +64,7 @@ public class ServerInvalidDefinitionR4Test extends BaseR4ServerTest { try { startServer(new ValidateWithWrongModeType()); fail(); - } catch (ServletException e) { + } catch (ConfigurationException e) { assertThat(e.getCause().toString(), StringContains.containsString("ConfigurationException")); assertThat(e.getCause().toString(), StringContains.containsString("Parameter annotated with @Validate.Mode must be of type ca.uhn.fhir.rest.api.ValidationModeEnum")); } @@ -74,7 +75,7 @@ public class ServerInvalidDefinitionR4Test extends BaseR4ServerTest { try { startServer(new ValidateWithWrongProfileType()); fail(); - } catch (ServletException e) { + } catch (ConfigurationException e) { assertThat(e.getCause().toString(), StringContains.containsString("ConfigurationException")); assertThat(e.getCause().toString(), StringContains.containsString("Parameter annotated with @Validate.Profile must be of type java.lang.String")); } @@ -94,8 +95,8 @@ public class ServerInvalidDefinitionR4Test extends BaseR4ServerTest { try { startServer(new MyProvider()); fail(); - } catch (ServletException e) { - assertThat(e.getCause().toString(), StringContains.containsString(Msg.code(288) + "Failure scanning class MyProvider: "+ Msg.code(421) + "Illegal method parameter annotation @OptionalParam on method: public ca.uhn.fhir.rest.api.MethodOutcome ca.uhn.fhir.rest.server.ServerInvalidDefinitionR4Test$1MyProvider.update(org.hl7.fhir.r4.model.StringType)")); + } catch (ConfigurationException e) { + assertThat(e.toString(), StringContains.containsString(Msg.code(288) + "Failure scanning class MyProvider: "+ Msg.code(421) + "Illegal method parameter annotation @OptionalParam on method: public ca.uhn.fhir.rest.api.MethodOutcome ca.uhn.fhir.rest.server.ServerInvalidDefinitionR4Test$1MyProvider.update(org.hl7.fhir.r4.model.StringType)")); } } @@ -121,8 +122,8 @@ public class ServerInvalidDefinitionR4Test extends BaseR4ServerTest { try { startServer(provider); fail(); - } catch (ServletException e) { - assertEquals(Msg.code(288) + "Failure scanning class MyProvider: "+ Msg.code(404) + "@OperationParam detected on method that is not annotated with @Operation: public java.util.List ca.uhn.fhir.rest.server.ServerInvalidDefinitionR4Test$2MyProvider.search(org.hl7.fhir.r4.model.StringType,org.hl7.fhir.r4.model.StringType)", e.getCause().getMessage()); + } catch (ConfigurationException e) { + assertEquals(Msg.code(288) + "Failure scanning class MyProvider: "+ Msg.code(404) + "@OperationParam detected on method that is not annotated with @Operation: public java.util.List ca.uhn.fhir.rest.server.ServerInvalidDefinitionR4Test$2MyProvider.search(org.hl7.fhir.r4.model.StringType,org.hl7.fhir.r4.model.StringType)", e.getMessage()); } } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerMethodSelectionR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerMethodSelectionR4Test.java index 25194f468b3..ac5491144fc 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerMethodSelectionR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerMethodSelectionR4Test.java @@ -1,16 +1,21 @@ package ca.uhn.fhir.rest.server; +import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.rest.annotation.IncludeParam; import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import com.google.common.collect.Lists; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.StringType; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.List; import java.util.Set; @@ -21,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.*; public class ServerMethodSelectionR4Test extends BaseR4ServerTest { - /** * Server method with no _include * Client request with _include @@ -42,7 +46,8 @@ public class ServerMethodSelectionR4Test extends BaseR4ServerTest { startServer(provider); try { - myClient + ourServer + .getFhirClient() .search() .forResource(Patient.class) .where(Patient.NAME.matches().value("foo")) @@ -73,7 +78,8 @@ public class ServerMethodSelectionR4Test extends BaseR4ServerTest { startServer(provider); - Bundle results = myClient + Bundle results = ourServer + .getFhirClient() .search() .forResource(Patient.class) .where(Patient.NAME.matches().value("foo")) @@ -103,7 +109,8 @@ public class ServerMethodSelectionR4Test extends BaseR4ServerTest { startServer(provider); try { - myClient + ourServer + .getFhirClient() .search() .forResource(Patient.class) .where(Patient.NAME.matches().value("foo")) @@ -134,7 +141,8 @@ public class ServerMethodSelectionR4Test extends BaseR4ServerTest { startServer(provider); - Bundle results = myClient + Bundle results = ourServer + .getFhirClient() .search() .forResource(Patient.class) .where(Patient.NAME.matches().value("foo")) diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeR4Test.java index 6544b49186c..c4a6de6f8e7 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/ServerMimetypeR4Test.java @@ -10,7 +10,8 @@ import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.client.MyPatientWithExtensions; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; @@ -21,12 +22,6 @@ import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpTrace; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.CapabilityStatement; import org.hl7.fhir.r4.model.CodeType; @@ -35,16 +30,14 @@ import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.OperationOutcome; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -54,19 +47,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class ServerMimetypeR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ServerMimetypeR4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + private static final FhirContext ourCtx = FhirContext.forR4Cached(); - @BeforeEach - public void before() { - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); - } + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new PatientProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML) + .setDefaultPrettyPrint(false); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); private String readAndReturnContentType(String theAccept) throws IOException { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient"); if (theAccept != null) { httpGet.addHeader(Constants.HEADER_ACCEPT, theAccept); } @@ -79,7 +73,7 @@ public class ServerMimetypeR4Test { @Test public void testConformanceMetadataUsesNewMimetypes() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/metadata"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/metadata"); CloseableHttpResponse status = ourClient.execute(httpGet); try { String content = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -99,7 +93,7 @@ public class ServerMimetypeR4Test { String enc = ourCtx.newJsonParser().encodeResourceToString(p); String expectedResponseContent = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\"},\"name\":[{\"family\":\"FAMILY\"}]}"; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_JSON + "; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -120,7 +114,7 @@ public class ServerMimetypeR4Test { String enc = ourCtx.newJsonParser().encodeResourceToString(p); String expectedResponseContent = "{\"resourceType\":\"OperationOutcome\",\"issue\":[{\"diagnostics\":\"FAMILY\"}]}"; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_JSON_NEW + "; charset=utf-8"))); httpPost.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); HttpResponse status = ourClient.execute(httpPost); @@ -142,7 +136,7 @@ public class ServerMimetypeR4Test { String enc = ourCtx.newJsonParser().encodeResourceToString(p); String expectedResponseContent = "{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\"},\"name\":[{\"family\":\"FAMILY\"}]}"; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_JSON + "; charset=utf-8"))); httpPost.addHeader(Constants.HEADER_ACCEPT, Constants.CT_FHIR_JSON_NEW); HttpResponse status = ourClient.execute(httpPost); @@ -164,7 +158,7 @@ public class ServerMimetypeR4Test { String enc = ourCtx.newXmlParser().encodeResourceToString(p); String expectedResponseContent = ""; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_XML + "; charset=utf-8"))); httpPost.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME); HttpResponse status = ourClient.execute(httpPost); @@ -186,7 +180,7 @@ public class ServerMimetypeR4Test { String enc = ourCtx.newXmlParser().encodeResourceToString(p); String expectedResponseContent = ""; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_XML_NEW + "; charset=utf-8"))); HttpResponse status = ourClient.execute(httpPost); @@ -207,7 +201,7 @@ public class ServerMimetypeR4Test { String enc = ourCtx.newXmlParser().encodeResourceToString(p); String expectedResponseContent = ""; - HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient"); + HttpPost httpPost = new HttpPost(ourServer.getBaseUrl() + "/Patient"); httpPost.setEntity(new StringEntity(enc, ContentType.parse(Constants.CT_FHIR_XML + "; charset=utf-8"))); httpPost.addHeader(Constants.HEADER_ACCEPT, Constants.CT_FHIR_XML_NEW); HttpResponse status = ourClient.execute(httpPost); @@ -224,7 +218,7 @@ public class ServerMimetypeR4Test { @Test public void testHttpTraceNotEnabled() throws Exception { - HttpTrace req = new HttpTrace("http://localhost:" + ourPort + "/Patient"); + HttpTrace req = new HttpTrace(ourServer.getBaseUrl() + "/Patient"); CloseableHttpResponse status = ourClient.execute(req); try { ourLog.info(status.toString()); @@ -242,7 +236,7 @@ public class ServerMimetypeR4Test { return "TRACK"; } }; - req.setURI(new URI("http://localhost:" + ourPort + "/Patient")); + req.setURI(new URI(ourServer.getBaseUrl() + "/Patient")); CloseableHttpResponse status = ourClient.execute(req); try { @@ -258,7 +252,7 @@ public class ServerMimetypeR4Test { */ @Test public void testResponseContentTypesJson() throws IOException { - ourServlet.setDefaultResponseEncoding(EncodingEnum.XML); + ourServer.setDefaultResponseEncoding(EncodingEnum.XML); // None given assertEquals("application/fhir+xml", readAndReturnContentType(null)); @@ -281,7 +275,7 @@ public class ServerMimetypeR4Test { */ @Test public void testResponseContentTypesXml() throws IOException { - ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON); + ourServer.setDefaultResponseEncoding(EncodingEnum.JSON); // None given assertEquals("application/fhir+json", readAndReturnContentType(null)); @@ -302,7 +296,7 @@ public class ServerMimetypeR4Test { @Test public void testSearchWithFormatJsonLegacy() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_JSON); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=" + Constants.CT_FHIR_JSON); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -318,7 +312,7 @@ public class ServerMimetypeR4Test { @Test public void testSearchWithFormatJsonNew() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_JSON_NEW); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=" + Constants.CT_FHIR_JSON_NEW); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -334,7 +328,7 @@ public class ServerMimetypeR4Test { @Test public void testSearchWithFormatJsonSimple() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=json"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -350,7 +344,7 @@ public class ServerMimetypeR4Test { @Test public void testSearchWithFormatXmlLegacy() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_XML); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=" + Constants.CT_FHIR_XML); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -367,7 +361,7 @@ public class ServerMimetypeR4Test { @Test public void testSearchWithFormatXmlNew() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=" + Constants.CT_FHIR_XML_NEW); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=" + Constants.CT_FHIR_XML_NEW); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -384,7 +378,7 @@ public class ServerMimetypeR4Test { @Test public void testSearchWithFormatXmlSimple() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_format=xml"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_format=xml"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8); @@ -399,7 +393,7 @@ public class ServerMimetypeR4Test { } private List toStrings(List theFormat) { - ArrayList retVal = new ArrayList(); + ArrayList retVal = new ArrayList<>(); for (CodeType next : theFormat) { retVal.add(next.asStringValue()); } @@ -434,7 +428,7 @@ public class ServerMimetypeR4Test { @Search public List search() { - ArrayList retVal = new ArrayList(); + ArrayList retVal = new ArrayList<>(); MyPatientWithExtensions p0 = new MyPatientWithExtensions(); p0.setId(new IdType("Patient/0")); @@ -453,31 +447,7 @@ public class ServerMimetypeR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - PatientProvider patientProvider = new PatientProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - ourServlet = new RestfulServer(ourCtx); - - ourServlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(ourServlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SummaryParamR4Test.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SummaryParamR4Test.java index 155a8c89825..8f93d6d1f68 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SummaryParamR4Test.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/SummaryParamR4Test.java @@ -7,7 +7,9 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.SummaryEnum; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; @@ -17,8 +19,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.IdType; @@ -29,6 +31,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.io.IOException; import java.util.Collections; @@ -46,13 +49,19 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class SummaryParamR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SummaryParamR4Test.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static SummaryEnum ourLastSummary; private static List ourLastSummaryList; - private static int ourPort; - private static Server ourServer; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .registerProvider(new DummyMedicationRequestProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @BeforeEach public void before() { @@ -63,7 +72,7 @@ public class SummaryParamR4Test { @Test public void testReadSummaryData() throws Exception { verifyXmlAndJson( - "http://localhost:" + ourPort + "/Patient/1?_summary=" + SummaryEnum.DATA.getCode(), + ourServer.getBaseUrl() + "/Patient/1?_summary=" + SummaryEnum.DATA.getCode(), Patient.class, patient -> { String responseContent = ourCtx.newXmlParser().encodeResourceToString(patient); @@ -80,7 +89,7 @@ public class SummaryParamR4Test { @Test public void testReadSummaryText() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1?_summary=" + SummaryEnum.TEXT.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient/1?_summary=" + SummaryEnum.TEXT.getCode()); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); ourLog.info(responseContent); @@ -97,7 +106,7 @@ public class SummaryParamR4Test { @Test public void testReadSummaryTextWithMandatory() throws Exception { - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/MedicationRequest/1?_summary=" + SummaryEnum.TEXT.getCode()); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/MedicationRequest/1?_summary=" + SummaryEnum.TEXT.getCode()); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); ourLog.info(responseContent); @@ -114,7 +123,7 @@ public class SummaryParamR4Test { @Test public void testReadSummaryTrue() throws Exception { - String url = "http://localhost:" + ourPort + "/Patient/1?_summary=" + SummaryEnum.TRUE.getCode(); + String url = ourServer.getBaseUrl() + "/Patient/1?_summary=" + SummaryEnum.TRUE.getCode(); verifyXmlAndJson( url, Patient.class, @@ -133,7 +142,7 @@ public class SummaryParamR4Test { @Test public void testSearchSummaryCount() throws Exception { - String url = "http://localhost:" + ourPort + "/Patient?_pretty=true&_summary=" + SummaryEnum.COUNT.getCode(); + String url = ourServer.getBaseUrl() + "/Patient?_pretty=true&_summary=" + SummaryEnum.COUNT.getCode(); verifyXmlAndJson( url, bundle -> { @@ -150,7 +159,7 @@ public class SummaryParamR4Test { @Test public void testSearchSummaryCountAndData() throws Exception { - String url = "http://localhost:" + ourPort + "/Patient?_pretty=true&_summary=" + SummaryEnum.COUNT.getCode() + "," + SummaryEnum.DATA.getCode(); + String url = ourServer.getBaseUrl() + "/Patient?_pretty=true&_summary=" + SummaryEnum.COUNT.getCode() + "," + SummaryEnum.DATA.getCode(); verifyXmlAndJson( url, bundle -> { @@ -166,7 +175,7 @@ public class SummaryParamR4Test { @Test public void testSearchSummaryData() throws Exception { - String url = "http://localhost:" + ourPort + "/Patient?_summary=" + SummaryEnum.DATA.getCode(); + String url = ourServer.getBaseUrl() + "/Patient?_summary=" + SummaryEnum.DATA.getCode(); verifyXmlAndJson( url, bundle -> { @@ -183,7 +192,7 @@ public class SummaryParamR4Test { @Test public void testSearchSummaryFalse() throws Exception { - String url = "http://localhost:" + ourPort + "/Patient?_summary=false"; + String url = ourServer.getBaseUrl() + "/Patient?_summary=false"; verifyXmlAndJson( url, bundle -> { @@ -199,7 +208,7 @@ public class SummaryParamR4Test { @Test public void testSearchSummaryText() throws Exception { - String url = "http://localhost:" + ourPort + "/Patient?_summary=" + SummaryEnum.TEXT.getCode(); + String url = ourServer.getBaseUrl() + "/Patient?_summary=" + SummaryEnum.TEXT.getCode(); verifyXmlAndJson( url, bundle -> { @@ -216,7 +225,7 @@ public class SummaryParamR4Test { @Test public void testSearchSummaryTextWithMandatory() throws Exception { - String url = "http://localhost:" + ourPort + "/MedicationRequest?_summary=" + SummaryEnum.TEXT.getCode() + "&_pretty=true"; + String url = ourServer.getBaseUrl() + "/MedicationRequest?_summary=" + SummaryEnum.TEXT.getCode() + "&_pretty=true"; verifyXmlAndJson( url, bundle -> { @@ -234,7 +243,7 @@ public class SummaryParamR4Test { @Test public void testSearchSummaryTextMulti() throws Exception { - String url = "http://localhost:" + ourPort + "/Patient?_query=multi&_summary=" + SummaryEnum.TEXT.getCode(); + String url = ourServer.getBaseUrl() + "/Patient?_query=multi&_summary=" + SummaryEnum.TEXT.getCode(); verifyXmlAndJson( url, bundle -> { @@ -251,7 +260,7 @@ public class SummaryParamR4Test { @Test public void testSearchSummaryTrue() throws Exception { - String url = "http://localhost:" + ourPort + "/Patient?_summary=" + SummaryEnum.TRUE.getCode(); + String url = ourServer.getBaseUrl() + "/Patient?_summary=" + SummaryEnum.TRUE.getCode(); verifyXmlAndJson( url, bundle -> { @@ -268,7 +277,7 @@ public class SummaryParamR4Test { @Test public void testSearchSummaryWithTextAndOthers() throws Exception { - String url = "http://localhost:" + ourPort + "/Patient?_summary=text&_summary=data"; + String url = ourServer.getBaseUrl() + "/Patient?_summary=text&_summary=data"; try (CloseableHttpResponse status = ourClient.execute(new HttpGet(url))) { String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); ourLog.info(responseContent); @@ -373,29 +382,7 @@ public class SummaryParamR4Test { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); - - ServletHandler proxyHandler = new ServletHandler(); - RestfulServer servlet = new RestfulServer(ourCtx); - - servlet.setResourceProviders(new DummyPatientResourceProvider(), new DummyMedicationRequestProvider()); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - } diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ConsentInterceptorTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ConsentInterceptorTest.java index 784bd9d68c9..237e72a218c 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ConsentInterceptorTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ConsentInterceptorTest.java @@ -47,10 +47,11 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.util.Assert; -import javax.servlet.ReadListener; -import javax.servlet.ServletInputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ExceptionHandlingInterceptorTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ExceptionHandlingInterceptorTest.java index 06362fa443d..e133f302a34 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ExceptionHandlingInterceptorTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ExceptionHandlingInterceptorTest.java @@ -27,8 +27,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hamcrest.core.StringContains; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.OperationOutcome; diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ExceptionInterceptorMethodTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ExceptionInterceptorMethodTest.java index 1b7d6b7f344..aa128750d69 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ExceptionInterceptorMethodTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/ExceptionInterceptorMethodTest.java @@ -2,12 +2,16 @@ package ca.uhn.fhir.rest.server.interceptor; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.Search; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.RequestDetails; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; +import ca.uhn.fhir.test.utilities.HttpClientExtension; import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; @@ -17,18 +21,19 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.ee10.servlet.ServletHandler; +import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentCaptor; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.util.List; import java.util.concurrent.TimeUnit; @@ -41,23 +46,28 @@ import static org.mockito.Mockito.when; public class ExceptionInterceptorMethodTest { - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); + private static final FhirContext ourCtx = FhirContext.forR4Cached(); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ExceptionInterceptorMethodTest.class); - private static int ourPort; - private static Server ourServer; - private static RestfulServer servlet; private IServerInterceptor myInterceptor; + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .setDefaultResponseEncoding(EncodingEnum.XML); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); + @BeforeEach public void before() { myInterceptor = mock(IServerInterceptor.class); - servlet.getInterceptorService().registerInterceptor(myInterceptor); + ourServer.getInterceptorService().registerInterceptor(myInterceptor); } @AfterEach public void after() { - servlet.getInterceptorService().unregisterInterceptor(myInterceptor); + ourServer.getInterceptorService().unregisterInterceptor(myInterceptor); } @Test @@ -67,7 +77,7 @@ public class ExceptionInterceptorMethodTest { when(myInterceptor.incomingRequestPostProcessed(any(RequestDetails.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); when(myInterceptor.handleException(any(RequestDetails.class), any(BaseServerResponseException.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(true); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=throwUnprocessableEntityException"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=throwUnprocessableEntityException"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { ourLog.info(IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8)); assertEquals(422, status.getStatusLine().getStatusCode()); @@ -94,7 +104,7 @@ public class ExceptionInterceptorMethodTest { return false; }); - HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=throwUnprocessableEntityException"); + HttpGet httpGet = new HttpGet(ourServer.getBaseUrl() + "/Patient?_query=throwUnprocessableEntityException"); try (CloseableHttpResponse status = ourClient.execute(httpGet)) { String responseContent = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8); ourLog.info(responseContent); @@ -106,33 +116,12 @@ public class ExceptionInterceptorMethodTest { @AfterAll public static void afterClassClearContext() throws Exception { - JettyUtil.closeServer(ourServer); TestUtil.randomizeLocaleAndTimezone(); } - @BeforeAll - public static void beforeClass() throws Exception { - ourServer = new Server(0); + - DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); - - ServletHandler proxyHandler = new ServletHandler(); - servlet = new RestfulServer(ourCtx); - servlet.setResourceProviders(patientProvider); - ServletHolder servletHolder = new ServletHolder(servlet); - proxyHandler.addServletWithMapping(servletHolder, "/*"); - ourServer.setHandler(proxyHandler); - JettyUtil.startServer(ourServer); - ourPort = JettyUtil.getPortForStartedServer(ourServer); - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setConnectionManager(connectionManager); - ourClient = builder.build(); - - } - - public static class DummyPatientResourceProvider implements IResourceProvider { + private static class DummyPatientResourceProvider implements IResourceProvider { @Override public Class getResourceType() { diff --git a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/InjectionAttackTest.java b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/InjectionAttackTest.java index 220ec958e59..73ccf4884bc 100644 --- a/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/InjectionAttackTest.java +++ b/hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/InjectionAttackTest.java @@ -6,31 +6,26 @@ import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.Constants; +import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.param.TokenParam; +import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.IResourceProvider; -import ca.uhn.fhir.rest.server.RestfulServer; -import ca.uhn.fhir.test.utilities.JettyUtil; +import ca.uhn.fhir.test.utilities.HttpClientExtension; +import ca.uhn.fhir.test.utilities.server.RestfulServerExtension; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; import com.google.common.base.Charsets; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Patient; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -39,17 +34,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class InjectionAttackTest { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(InjectionAttackTest.class); - private static CloseableHttpClient ourClient; - private static FhirContext ourCtx = FhirContext.forR4(); - private static int ourPort; - private static Server ourServer; - private static RestfulServer ourServlet; + private static final FhirContext ourCtx = FhirContext.forR4Cached(); + + @RegisterExtension + public RestfulServerExtension ourServer = new RestfulServerExtension(ourCtx) + .registerProvider(new DummyPatientResourceProvider()) + .withPagingProvider(new FifoMemoryPagingProvider(100)) + .registerInterceptor(new ResponseHighlighterInterceptor()) + .setDefaultResponseEncoding(EncodingEnum.JSON); + + @RegisterExtension + private HttpClientExtension ourClient = new HttpClientExtension(); @Test public void testPreventHtmlInjectionViaInvalidContentType() throws Exception { - String requestUrl = "http://localhost:" + - ourPort + - "/Patient/123"; + String requestUrl = ourServer.getBaseUrl() + "/Patient/123"; // XML HTML HttpGet httpGet = new HttpGet(requestUrl); @@ -65,8 +64,7 @@ public class InjectionAttackTest { @Test public void testPreventHtmlInjectionViaInvalidParameterName() throws Exception { - String requestUrl = "http://localhost:" + - ourPort + + String requestUrl = ourServer.getBaseUrl() + "/Patient?a" + UrlUtil.escapeUrlParam("