diff --git a/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/AbstractServiceDelegate.java b/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/AbstractServiceDelegate.java index 35c03c73f..f796f1d69 100644 --- a/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/AbstractServiceDelegate.java +++ b/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/AbstractServiceDelegate.java @@ -70,7 +70,7 @@ public final void execute(DelegateExecution execution) throws Exception // Error boundary event, do not stop process execution catch (BpmnError error) { - logger.debug("Error while executing service delegate " + getClass().getName(), error); + logger.debug("Error while executing service delegate {}", getClass().getName(), error); logger.error( "Process {} encountered error boundary event in step {} for task {}, error-code: {}, message: {}", execution.getProcessDefinitionId(), execution.getActivityInstanceId(), @@ -82,7 +82,7 @@ public final void execute(DelegateExecution execution) throws Exception // Not an error boundary event, stop process execution catch (Exception exception) { - logger.debug("Error while executing service delegate " + getClass().getName(), exception); + logger.debug("Error while executing service delegate {}", getClass().getName(), exception); logger.error("Process {} has fatal error in step {} for task {}, reason: {} - {}", execution.getProcessDefinitionId(), execution.getActivityInstanceId(), api.getTaskHelper().getLocalVersionlessAbsoluteUrl(variables.getStartTask()), @@ -148,7 +148,9 @@ private void updateAndHandleException(Task task) } catch (Exception e) { - logger.error("Unable to update Task " + api.getTaskHelper().getLocalVersionlessAbsoluteUrl(task), e); + logger.debug("Unable to update Task {}", api.getTaskHelper().getLocalVersionlessAbsoluteUrl(task), e); + logger.error("Unable to update Task {}: {} - {}", api.getTaskHelper().getLocalVersionlessAbsoluteUrl(task), + e.getClass().getName(), e.getMessage()); } } } diff --git a/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/AbstractTaskMessageSend.java b/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/AbstractTaskMessageSend.java index fb478d339..72ed51b48 100644 --- a/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/AbstractTaskMessageSend.java +++ b/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/AbstractTaskMessageSend.java @@ -197,12 +197,13 @@ protected void doExecute(DelegateExecution execution, Variables variables) throw catch (Exception e) { String exceptionMessage = e.getMessage(); - if (e instanceof WebApplicationException && (e.getMessage() == null || e.getMessage().isBlank())) + if (e instanceof WebApplicationException w && (e.getMessage() == null || e.getMessage().isBlank())) { - StatusType statusInfo = ((WebApplicationException) e).getResponse().getStatusInfo(); + StatusType statusInfo = w.getResponse().getStatusInfo(); exceptionMessage = statusInfo.getStatusCode() + " " + statusInfo.getReasonPhrase(); } + logger.debug("Error while sending Task", e); String errorMessage = "Task " + instantiatesCanonical + " send failed [recipient: " + target.getOrganizationIdentifierValue() + ", endpoint: " + target.getEndpointIdentifierValue() + ", businessKey: " + businessKey @@ -210,7 +211,6 @@ protected void doExecute(DelegateExecution execution, Variables variables) throw + ", message: " + messageName + ", error: " + e.getClass().getName() + " - " + exceptionMessage + "]"; logger.warn(errorMessage); - logger.debug("Error while sending Task", e); if (execution.getBpmnModelElementInstance() instanceof IntermediateThrowEvent) handleIntermediateThrowEventError(execution, variables, e, errorMessage); @@ -227,7 +227,7 @@ else if (execution.getBpmnModelElementInstance() instanceof SendTask) protected void handleIntermediateThrowEventError(DelegateExecution execution, Variables variables, Exception exception, String errorMessage) { - logger.debug("Error while executing Task message send " + getClass().getName(), exception); + logger.debug("Error while executing Task message send {}", getClass().getName(), exception); logger.error("Process {} has fatal error in step {} for task {}, reason: {} - {}", execution.getProcessDefinitionId(), execution.getActivityInstanceId(), api.getTaskHelper().getLocalVersionlessAbsoluteUrl(variables.getStartTask()), @@ -242,7 +242,7 @@ protected void handleIntermediateThrowEventError(DelegateExecution execution, Va protected void handleEndEventError(DelegateExecution execution, Variables variables, Exception exception, String errorMessage) { - logger.debug("Error while executing Task message send " + getClass().getName(), exception); + logger.debug("Error while executing Task message send {}", getClass().getName(), exception); logger.error("Process {} has fatal error in step {} for task {}, reason: {} - {}", execution.getProcessDefinitionId(), execution.getActivityInstanceId(), api.getTaskHelper().getLocalVersionlessAbsoluteUrl(variables.getStartTask()), @@ -275,8 +275,8 @@ protected void handleSendTaskError(DelegateExecution execution, Variables variab // if we are not a multi instance message send task or all sends have failed (targets emtpy) else { - logger.debug("Error while executing Task message send " + getClass().getName(), exception); - logger.error("Process {} has fatal error in step {} for task {}, last reason: {} - ", + logger.debug("Error while executing Task message send {}", getClass().getName(), exception); + logger.error("Process {} has fatal error in step {} for task {}, last reason: {} - {}", execution.getProcessDefinitionId(), execution.getActivityInstanceId(), api.getTaskHelper().getLocalVersionlessAbsoluteUrl(variables.getStartTask()), exception.getClass().getName(), exception.getMessage()); @@ -342,7 +342,9 @@ private void updateAndHandleException(Task task) } catch (Exception e) { - logger.error("Unable to update Task " + api.getTaskHelper().getLocalVersionlessAbsoluteUrl(task), e); + logger.debug("Unable to update Task {}", api.getTaskHelper().getLocalVersionlessAbsoluteUrl(task), e); + logger.error("Unable to update Task {}: {} - {}", api.getTaskHelper().getLocalVersionlessAbsoluteUrl(task), + e.getClass().getName(), e.getMessage()); } } diff --git a/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/DefaultUserTaskListener.java b/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/DefaultUserTaskListener.java index 444a5d757..69a1a85ea 100644 --- a/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/DefaultUserTaskListener.java +++ b/dsf-bpe/dsf-bpe-process-api-v1/src/main/java/dev/dsf/bpe/v1/activity/DefaultUserTaskListener.java @@ -95,7 +95,7 @@ public final void notify(DelegateTask userTask) } catch (Exception exception) { - logger.debug("Error while executing user task listener " + getClass().getName(), exception); + logger.debug("Error while executing user task listener {}", getClass().getName(), exception); logger.error("Process {} has fatal error in step {} for task {}, reason: {} - {}", execution.getProcessDefinitionId(), execution.getActivityInstanceId(), api.getTaskHelper().getLocalVersionlessAbsoluteUrl(variables.getStartTask()), @@ -255,7 +255,9 @@ private void updateAndHandleException(Task task) } catch (Exception e) { - logger.error("Unable to update Task " + api.getTaskHelper().getLocalVersionlessAbsoluteUrl(task), e); + logger.debug("Unable to update Task {}", api.getTaskHelper().getLocalVersionlessAbsoluteUrl(task), e); + logger.error("Unable to update Task {}: {} - {}", api.getTaskHelper().getLocalVersionlessAbsoluteUrl(task), + e.getClass().getName(), e.getMessage()); } } } diff --git a/dsf-bpe/dsf-bpe-process-api-v1/src/test/java/dev/dsf/bpe/start/ExampleStarter.java b/dsf-bpe/dsf-bpe-process-api-v1/src/test/java/dev/dsf/bpe/start/ExampleStarter.java index ee307c371..e92baed6f 100644 --- a/dsf-bpe/dsf-bpe-process-api-v1/src/test/java/dev/dsf/bpe/start/ExampleStarter.java +++ b/dsf-bpe/dsf-bpe-process-api-v1/src/test/java/dev/dsf/bpe/start/ExampleStarter.java @@ -106,9 +106,8 @@ private void start(Resource resource) throws Exception { FhirWebserviceClient client = createClient(baseUrl); - if (resource instanceof Bundle) + if (resource instanceof Bundle bundle) { - Bundle bundle = (Bundle) resource; bundle.getEntry().stream().map(e -> e.getResource().getResourceType()).filter(ResourceType.Task::equals) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Bundle does not contain a Task resource")); diff --git a/dsf-bpe/dsf-bpe-server-jetty/src/main/java/dev/dsf/bpe/BpeJettyServer.java b/dsf-bpe/dsf-bpe-server-jetty/src/main/java/dev/dsf/bpe/BpeJettyServer.java index a4f1787b3..2179eced6 100755 --- a/dsf-bpe/dsf-bpe-server-jetty/src/main/java/dev/dsf/bpe/BpeJettyServer.java +++ b/dsf-bpe/dsf-bpe-server-jetty/src/main/java/dev/dsf/bpe/BpeJettyServer.java @@ -9,7 +9,7 @@ import dev.dsf.common.jetty.Log4jInitializer; import dev.dsf.tools.db.DbMigrator; -public class BpeJettyServer +public final class BpeJettyServer { static { @@ -19,6 +19,10 @@ public class BpeJettyServer Log4jInitializer.initializeLog4j(); } + private BpeJettyServer() + { + } + public static void main(String[] args) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( diff --git a/dsf-bpe/dsf-bpe-server-jetty/src/main/java/dev/dsf/bpe/BpeJettyServerHttps.java b/dsf-bpe/dsf-bpe-server-jetty/src/main/java/dev/dsf/bpe/BpeJettyServerHttps.java index 432bf3f43..eda4803f4 100755 --- a/dsf-bpe/dsf-bpe-server-jetty/src/main/java/dev/dsf/bpe/BpeJettyServerHttps.java +++ b/dsf-bpe/dsf-bpe-server-jetty/src/main/java/dev/dsf/bpe/BpeJettyServerHttps.java @@ -9,7 +9,7 @@ import dev.dsf.common.jetty.Log4jInitializer; import dev.dsf.tools.db.DbMigrator; -public class BpeJettyServerHttps +public final class BpeJettyServerHttps { static { @@ -19,6 +19,10 @@ public class BpeJettyServerHttps Log4jInitializer.initializeLog4j(); } + private BpeJettyServerHttps() + { + } + public static void main(String[] args) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/FallbackSerializerFactoryImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/FallbackSerializerFactoryImpl.java index 31a491736..6f8846de2 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/FallbackSerializerFactoryImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/FallbackSerializerFactoryImpl.java @@ -135,14 +135,13 @@ else if (value.getValue() != null) return null; } - @SuppressWarnings("rawtypes") private String getName(TypedValue value) { if (value == null) return null; - if (value instanceof PrimitiveValue) - return ((PrimitiveValue) value).getType().getJavaType().getName(); + if (value instanceof PrimitiveValue p) + return p.getType().getJavaType().getName(); else if (value.getValue() != null) return value.getClass().getName(); else if (value.getType() != null) diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateActivityBehavior.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateActivityBehavior.java index d7880b8d4..fa4abdc7b 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateActivityBehavior.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateActivityBehavior.java @@ -36,20 +36,16 @@ protected ActivityBehavior getActivityBehaviorInstance(ActivityExecution executi Object delegateInstance = instantiateDelegate(processKeyAndVersion, className, fieldDeclarations); - if (delegateInstance instanceof ActivityBehavior) - { - return new CustomActivityBehavior((ActivityBehavior) delegateInstance); - } - else if (delegateInstance instanceof JavaDelegate) - { - return new ServiceTaskJavaDelegateActivityBehavior((JavaDelegate) delegateInstance); - } + if (delegateInstance instanceof ActivityBehavior b) + return new CustomActivityBehavior(b); + + else if (delegateInstance instanceof JavaDelegate d) + return new ServiceTaskJavaDelegateActivityBehavior(d); + else - { throw LOG.missingDelegateParentClassException(delegateInstance.getClass().getName(), JavaDelegate.class.getName(), ActivityBehavior.class.getName()); - } - }; + } private Object instantiateDelegate(ProcessIdAndVersion processKeyAndVersion, String className, List fieldDeclarations) diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateExecutionListener.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateExecutionListener.java index 703f20a40..83d72f4ea 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateExecutionListener.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateExecutionListener.java @@ -54,15 +54,12 @@ protected ExecutionListener getExecutionListenerInstance(ProcessIdAndVersion pro { Object delegateInstance = instantiateDelegate(processKeyAndVersion, className, fieldDeclarations); - if (delegateInstance instanceof ExecutionListener) - { - return (ExecutionListener) delegateInstance; - } + if (delegateInstance instanceof ExecutionListener l) + return l; + else - { throw new ProcessEngineException( delegateInstance.getClass().getName() + " doesn't implement " + ExecutionListener.class); - } } private Object instantiateDelegate(ProcessIdAndVersion processKeyAndVersion, String className, diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateTaskListener.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateTaskListener.java index d019ad4e8..47dc7ee2c 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateTaskListener.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/camunda/MultiVersionClassDelegateTaskListener.java @@ -53,15 +53,12 @@ protected TaskListener getTaskListenerInstance(ProcessIdAndVersion processKeyAnd { Object delegateInstance = instantiateDelegate(processKeyAndVersion, className, fieldDeclarations); - if (delegateInstance instanceof TaskListener) - { - return (TaskListener) delegateInstance; - } + if (delegateInstance instanceof TaskListener l) + return l; + else - { throw new ProcessEngineException( delegateInstance.getClass().getName() + " doesn't implement " + TaskListener.class); - } } private Object instantiateDelegate(ProcessIdAndVersion processKeyAndVersion, String className, diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/client/FhirClientProviderImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/client/FhirClientProviderImpl.java index 476518d7d..8bf9cd6da 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/client/FhirClientProviderImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/client/FhirClientProviderImpl.java @@ -200,7 +200,9 @@ public void disconnectAll() } catch (Exception e) { - logger.warn("Error while disconnecting websocket client", e); + logger.debug("Error while disconnecting websocket client", e); + logger.warn("Error while disconnecting websocket client: {} - {}", e.getClass().getName(), + e.getMessage()); } } } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/listener/EndListener.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/listener/EndListener.java index 66d8305f4..4dbcc8194 100755 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/listener/EndListener.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/listener/EndListener.java @@ -47,7 +47,7 @@ public void doNotify(DelegateExecution execution, ListenerVariables variables) t updateIfInprogress(task); boolean subProcess = execution.getParentId() != null && !execution.getParentId().equals(execution.getProcessInstanceId()); - logEnd(logger, subProcess, task, subProcess ? variables.getStartTask() : null); + logEnd(subProcess, task, subProcess ? variables.getStartTask() : null); } variables.onEnd(); @@ -78,11 +78,13 @@ private void updateAndHandleException(Task task) } catch (Exception e) { - logger.error("Unable to update Task " + getLocalVersionlessAbsoluteUrl(task), e); + logger.debug("Unable to update Task {}", getLocalVersionlessAbsoluteUrl(task), e); + logger.error("Unable to update Task {}: {} - {}", getLocalVersionlessAbsoluteUrl(task), + e.getClass().getName(), e.getMessage()); } } - private void logEnd(Logger logger, boolean subProcess, Task endTask, Task mainTask) + private void logEnd(boolean subProcess, Task endTask, Task mainTask) { String processUrl = endTask.getInstantiatesCanonical(); String businessKey = getFirstInputParameter(endTask, BpmnMessage.businessKey()); @@ -111,7 +113,7 @@ private void logEnd(Logger logger, boolean subProcess, Task endTask, Task mainTa processUrl, getCurrentTime(), endTaskUrl, requester, businessKey, correlationKey); else logger.info("Process {} finished at {} [task: {}, requester: {}, business-key: {}]", processUrl, - getCurrentTime(), endTaskUrl, requester, businessKey, correlationKey); + getCurrentTime(), endTaskUrl, requester, businessKey); } } } \ No newline at end of file diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/mail/SmtpMailService.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/mail/SmtpMailService.java index c5220e696..5a02e0dde 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/mail/SmtpMailService.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/mail/SmtpMailService.java @@ -281,6 +281,7 @@ private Optional toInternetAddress(String fromAddress) } catch (AddressException e) { + logger.debug("Unable to create {} from {}", InternetAddress.class.getName(), fromAddress, e); logger.warn("Unable to create {} from {}: {} - {}", InternetAddress.class.getName(), fromAddress, e.getClass().getName(), e.getMessage()); @@ -347,7 +348,9 @@ public SSLSocketFactory createSslSocketFactory(KeyStore trustStore, KeyStore key } catch (UnrecoverableKeyException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) { + logger.debug("Unable to create custom ssl socket factory", e); logger.warn("Unable to create custom ssl socket factory: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } } @@ -372,7 +375,7 @@ private SMIMESignedGenerator createSmimeSignedGenerator(String fromAddress, KeyS Optional pivateKey = getFirstPrivateKey(signStore, signStorePassword); if (pivateKey.isEmpty()) { - logger.warn("Mail signing certificate store has no private key, not signing mails", fromAddress); + logger.warn("Mail signing certificate store has no private key, not signing mails"); return null; } @@ -535,7 +538,9 @@ public void send(String subject, MimeBodyPart body, Consumer messag } catch (MessagingException e) { + logger.debug("Unable to send message", e); logger.warn("Unable to send message: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/AbstractProcessPlugin.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/AbstractProcessPlugin.java index 5cec5ce37..77e6a4cd2 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/AbstractProcessPlugin.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/AbstractProcessPlugin.java @@ -579,23 +579,24 @@ private AnnotationConfigApplicationContext createApplicationContext() .toArray(Class[]::new)); context.setEnvironment(environment); context.refresh(); + return context; } catch (BeanCreationException e) { - logger.error("Unable to create spring application context for process plugin {}-{}: {} {}", - getDefinitionName(), getDefinitionVersion(), e.getClass().getSimpleName(), e.getMessage()); - logger.debug("Unable to create spring application context for process plugin " + getDefinitionName() + "-" - + getDefinitionVersion() + ", bean with error " + e.getBeanName(), e); + logger.debug("Unable to create spring application context for process plugin {}-{}, bean with error {}", + getDefinitionName(), getDefinitionVersion(), e.getBeanName(), e); + logger.error("Unable to create spring application context for process plugin {}-{}: {} - {}", + getDefinitionName(), getDefinitionVersion(), e.getClass().getName(), e.getMessage()); return null; } catch (Exception e) { - logger.error("Unable to create spring application context for process plugin {}-{}: {} {}", - getDefinitionName(), getDefinitionVersion(), e.getClass().getSimpleName(), e.getMessage()); - logger.debug("Unable to create spring application context for process plugin " + getDefinitionName() + "-" - + getDefinitionVersion(), e); + logger.debug("Unable to create spring application context for process plugin {}-{}", getDefinitionName(), + getDefinitionVersion(), e); + logger.error("Unable to create spring application context for process plugin {}-{}: {} - {}", + getDefinitionName(), getDefinitionVersion(), e.getClass().getName(), e.getMessage()); return null; } @@ -615,6 +616,7 @@ private Function loadBpmnModelOrNull(String localOrgan { logger.warn("Ignoring BPMN model {} from process plugin {}-{}: Filename not ending in '{}'", file, getDefinitionName(), getDefinitionVersion(), BPMN_SUFFIX); + return null; } @@ -632,6 +634,7 @@ file, getDefinitionName(), getDefinitionVersion(), VERSION_PLACEHOLDER_PATTERN_S logger.warn( "Ignoring BPMN model {} from process plugin {}-{}: File not readable, process plugin class loader getResourceAsStream returned null", file, getDefinitionName(), getDefinitionVersion()); + return null; } @@ -699,8 +702,11 @@ file, getDefinitionName(), getDefinitionVersion(), VERSION_PLACEHOLDER_PATTERN_S } catch (IOException e) { + logger.debug("Ignoring BPMN model {} from process plugin {}-{}", file, getDefinitionName(), + getDefinitionVersion(), e); logger.warn("Ignoring BPMN model {} from process plugin {}-{}: {} - {}", file, getDefinitionName(), getDefinitionVersion(), e.getClass().getName(), e.getMessage()); + return null; } }; @@ -730,8 +736,10 @@ private boolean isValid(BpmnFileAndModel fileAndModel) } catch (Exception e) { + logger.debug("BPMN file {} not valid", fileAndModel.getFile(), e); logger.warn("BPMN file {} not valid: {} - {}", fileAndModel.getFile(), e.getClass().getName(), e.getMessage()); + return false; } @@ -909,14 +917,17 @@ private Class loadClass(ProcessIdAndVersion processKeyAndVersion, String elem try { ClassLoader classLoader = getProcessPluginClassLoader(); + return classLoader.loadClass(className); } catch (ClassNotFoundException e) { - logger.warn("{} '{}' defined in process {}, element {} not found", expectedInterface.getSimpleName(), - className, processKeyAndVersion.toString(), elementId); - logger.debug(expectedInterface.getSimpleName() + " '" + className + "' defined in process " - + processKeyAndVersion.toString() + " not found", e); + logger.debug("{} '{}' defined in process {}, element {} not found", expectedInterface.getSimpleName(), + className, processKeyAndVersion.toString(), elementId, e); + logger.warn("{} '{}' defined in process {}, element {} not found: {} - {}", + expectedInterface.getSimpleName(), className, processKeyAndVersion.toString(), elementId, + e.getClass().getName(), e.getMessage()); + return null; } } @@ -929,12 +940,14 @@ private boolean isPrototypeBeanAvailable(ProcessIdAndVersion processKeyAndVersio { logger.warn("Unable to find prototype bean of type {} for element {} in process {}", serviceClass.getName(), elementId, processKeyAndVersion.toString()); + return false; } else if (beanNames.length > 1) { logger.warn("Unable to find unique prototype bean of type {} for element {} in process {}, found {}", serviceClass.getName(), elementId, processKeyAndVersion.toString(), beanNames.length); + return false; } else @@ -981,6 +994,7 @@ private Function loadFhirResourceOrNull(String localOrg { logger.warn("Ignoring FHIR resource {} from process plugin {}-{}: Filename not ending in '{}' or '{}'", file, getDefinitionName(), getDefinitionVersion(), JSON_SUFFIX, XML_SUFFIX); + return null; } @@ -1015,36 +1029,40 @@ file, getDefinitionName(), getDefinitionVersion(), VERSION_PLACEHOLDER_PATTERN_S IBaseResource resource = newParser(file).parseResource(content); - if (resource instanceof ActivityDefinition && isValid((ActivityDefinition) resource, file)) + if (resource instanceof ActivityDefinition a && isValid(a, file)) return FileAndResource.of(file, (Resource) resource); - else if (resource instanceof CodeSystem && isValid((CodeSystem) resource, file)) + else if (resource instanceof CodeSystem c && isValid(c, file)) return FileAndResource.of(file, (Resource) resource); - else if (resource instanceof Library && isValid((Library) resource, file)) + else if (resource instanceof Library l && isValid(l, file)) return FileAndResource.of(file, (Resource) resource); - else if (resource instanceof Measure && isValid((Measure) resource, file)) + else if (resource instanceof Measure m && isValid(m, file)) return FileAndResource.of(file, (Resource) resource); - else if (resource instanceof NamingSystem && isValid((NamingSystem) resource, file)) + else if (resource instanceof NamingSystem n && isValid(n, file)) return FileAndResource.of(file, (Resource) resource); - else if (resource instanceof Questionnaire && isValid((Questionnaire) resource, file)) + else if (resource instanceof Questionnaire q && isValid(q, file)) return FileAndResource.of(file, (Resource) resource); - else if (resource instanceof StructureDefinition && isValid((StructureDefinition) resource, file)) + else if (resource instanceof StructureDefinition s && isValid(s, file)) return FileAndResource.of(file, (Resource) resource); - else if (resource instanceof Task && isValid((Task) resource, file, localOrganizationIdentifierValue)) + else if (resource instanceof Task t && isValid(t, file, localOrganizationIdentifierValue)) return FileAndResource.of(file, (Resource) resource); - else if (resource instanceof ValueSet && isValid((ValueSet) resource, file)) + else if (resource instanceof ValueSet v && isValid(v, file)) return FileAndResource.of(file, (Resource) resource); else { logger.warn( "Ignoring FHIR resource {} from process plugin {}-{}: Not a ActivityDefinition, CodeSystem, Library, Measure, NamingSystem, Questionnaire, StructureDefinition, Task or ValueSet", file, getDefinitionName(), getDefinitionVersion()); + return null; } } catch (IOException e) { + logger.debug("Ignoring FHIR resource {} from process plugin {}-{}", file, getDefinitionName(), + getDefinitionVersion(), e); logger.warn("Ignoring FHIR resource {} from process plugin {}-{}: {} - {}", file, getDefinitionName(), getDefinitionVersion(), e.getClass().getName(), e.getMessage()); + return null; } }; @@ -1302,6 +1320,7 @@ private Predicate hasMatchingActivityDefinition( "Ignoring BPMN model {} from process plugin {}-{}: No FHIR metadata resources found for process-id '{}'", model.getFile(), getDefinitionName(), getDefinitionVersion(), model.getProcessIdAndVersion().getId()); + return false; } @@ -1314,6 +1333,7 @@ private Predicate hasMatchingActivityDefinition( "Ignoring BPMN model {} from process plugin {}-{}: No ActivityDefinition found for process-id '{}'", model.getFile(), getDefinitionName(), getDefinitionVersion(), model.getProcessIdAndVersion().getId()); + return false; } @@ -1331,6 +1351,7 @@ private Predicate hasMatchingActivityDefinition( "Ignoring BPMN model {} from process plugin {}-{}: Found ActivityDefinition.url does not match process id (url: '{}' vs. process-id '{}')", model.getFile(), getDefinitionName(), getDefinitionVersion(), url, model.getProcessIdAndVersion().getId()); + return false; } } @@ -1364,7 +1385,7 @@ private boolean instantiatesCanonicalMatchesProcessIdAndIdentifierValid( ProcessIdAndVersion expectedProcessIdAndVersion, FileAndResource fileAndResource) { String instantiatesCanonical = ((Task) fileAndResource.getResource()).getInstantiatesCanonical(); - String identifierValue = TaskIdentifier.findFirst(((Task) fileAndResource.getResource())) + String identifierValue = TaskIdentifier.findFirst((Task) fileAndResource.getResource()) .map(Identifier::getValue).get(); Matcher instantiatesCanonicalMatcher = INSTANTIATES_CANONICAL_PATTERN.matcher(instantiatesCanonical); diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/BpmnProcessStateChangeServiceImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/BpmnProcessStateChangeServiceImpl.java index ecf9c57da..848bc562c 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/BpmnProcessStateChangeServiceImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/BpmnProcessStateChangeServiceImpl.java @@ -60,7 +60,10 @@ private Map getStates() } catch (SQLException e) { - logger.warn("Error while retrieving process states from db", e); + logger.debug("Error while retrieving process states from db", e); + logger.warn("Error while retrieving process states from db: {} - {}", e.getClass().getName(), + e.getMessage()); + throw new RuntimeException(e); } } @@ -98,7 +101,7 @@ else if (draft.contains(process)) newProcessStates.put(process, newState); - logger.debug("{}: {} -> {}", process.toString(), oldState, newState); + logger.debug("Process {} state change: {} -> {}", process.toString(), oldState, newState); // NEW -> ACTIVE : - (new process active by default) // NEW -> DRAFT : - (new process active by default) @@ -159,7 +162,9 @@ private void updateStates(Map states) } catch (SQLException e) { - logger.warn("Error while updating process states in db", e); + logger.debug("Error while updating process states in db", e); + logger.warn("Error while updating process states in db: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/FhirResourceHandlerImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/FhirResourceHandlerImpl.java index 5c39cf7bc..ac257afdd 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/FhirResourceHandlerImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/FhirResourceHandlerImpl.java @@ -142,8 +142,7 @@ public void applyStateChangesAndStoreNewResourcesInDb(Map entries = resourceValues.stream() - .map(r -> r.toBundleEntry(localWebserviceClient.getBaseUrl())).collect(Collectors.toList()); + List entries = resourceValues.stream().map(ProcessesResource::toBundleEntry).toList(); batchBundle.setEntry(entries); try @@ -167,17 +166,23 @@ public void applyStateChangesAndStoreNewResourcesInDb(Map logger.warn("Response status for {} not 200 OK but {}, missing resource will not be added", resource.getSearchBundleEntryUrl(), entry.getResponse().getStatus()); } - else if (!entry.hasResource() || !(entry.getResource() instanceof Bundle) - || !(BundleType.SEARCHSET.equals(((Bundle) entry.getResource()).getType()))) + else if (!entry.hasResource() || !(entry.getResource() instanceof Bundle b) + || !BundleType.SEARCHSET.equals(b.getType())) { logger.warn("Response for {} not a searchset Bundle, missing resource will not be added", resource.getSearchBundleEntryUrl()); @@ -389,7 +394,10 @@ private Map> getResourceInfosFromDb() } catch (SQLException e) { - logger.warn("Error while retrieving resource infos from db", e); + logger.debug("Error while retrieving resource infos from db", e); + logger.warn("Error while retrieving resource infos from db: {} - {}", e.getClass().getName(), + e.getMessage()); + throw new RuntimeException(e); } } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessPluginLoaderImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessPluginLoaderImpl.java index 6c2b8fe1b..d7928897f 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessPluginLoaderImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessPluginLoaderImpl.java @@ -84,7 +84,9 @@ else if (!p.getFileName().toString().endsWith(".jar")) } catch (IOException e) { - logger.warn("Error loading process plugins", e); + logger.debug("Error loading process plugins", e); + logger.warn("Error loading process plugins: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } } @@ -132,8 +134,10 @@ else if (!p.getFileName().toString().endsWith(".jar")) } catch (Exception e) { - logger.warn("Ignoring {}: Unable to load process plugin {} - {}", jar.toString(), e.getClass().getName(), + logger.debug("Ignoring {}: Unable to load process plugin", jar.toString(), e); + logger.warn("Ignoring {}: Unable to load process plugin: {} - {}", jar.toString(), e.getClass().getName(), e.getMessage()); + return null; } } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessPluginManagerImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessPluginManagerImpl.java index 6371227d1..bd9996cef 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessPluginManagerImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessPluginManagerImpl.java @@ -206,11 +206,12 @@ private Consumer> onProcesse } catch (Exception e) { - logger.warn("Error while executing {} bean {} for process plugin {}, {} - {}", + logger.debug("Error while executing {} bean {} for process plugin {}", + ProcessPluginDeploymentStateListener.class.getName(), entry.getKey(), + plugin.getJarFile().toString(), e); + logger.warn("Error while executing {} bean {} for process plugin {}: {} - {}", ProcessPluginDeploymentStateListener.class.getName(), entry.getKey(), plugin.getJarFile().toString(), e.getClass().getName(), e.getMessage()); - logger.debug("Error while executing " + ProcessPluginDeploymentStateListener.class.getName() + " bean " - + entry.getKey() + " for process plugin " + plugin.getJarFile().toString(), e); } }; } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessState.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessState.java index 341b222c9..76166e309 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessState.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessState.java @@ -6,7 +6,7 @@ public enum ProcessState private final int priority; - private ProcessState(int priority) + ProcessState(int priority) { this.priority = priority; } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessesResource.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessesResource.java index e5617a13d..00d565c9a 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessesResource.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/plugin/ProcessesResource.java @@ -33,24 +33,24 @@ public static ProcessesResource from(Resource resource) { Objects.requireNonNull(resource, "resource"); - if (resource instanceof ActivityDefinition) - return fromMetadataResource((ActivityDefinition) resource); - else if (resource instanceof CodeSystem) - return fromMetadataResource((CodeSystem) resource); - else if (resource instanceof Library) - return fromMetadataResource((Library) resource); - else if (resource instanceof Measure) - return fromMetadataResource((Measure) resource); - else if (resource instanceof NamingSystem) - return fromNamingSystem((NamingSystem) resource); - else if (resource instanceof Questionnaire) - return fromMetadataResource((Questionnaire) resource); - else if (resource instanceof StructureDefinition) - return fromMetadataResource((StructureDefinition) resource); - else if (resource instanceof Task) - return fromTask((Task) resource); - else if (resource instanceof ValueSet) - return fromMetadataResource((ValueSet) resource); + if (resource instanceof ActivityDefinition a) + return fromMetadataResource(a); + else if (resource instanceof CodeSystem c) + return fromMetadataResource(c); + else if (resource instanceof Library l) + return fromMetadataResource(l); + else if (resource instanceof Measure m) + return fromMetadataResource(m); + else if (resource instanceof NamingSystem n) + return fromNamingSystem(n); + else if (resource instanceof Questionnaire q) + return fromMetadataResource(q); + else if (resource instanceof StructureDefinition s) + return fromMetadataResource(s); + else if (resource instanceof Task t) + return fromTask(t); + else if (resource instanceof ValueSet v) + return fromMetadataResource(v); else throw new IllegalArgumentException( "MetadataResource of type " + resource.getClass().getName() + " not supported"); @@ -167,7 +167,7 @@ public boolean shouldExist() && ProcessState.RETIRED.equals(getNewProcessState())); } - public BundleEntryComponent toBundleEntry(String baseUrl) + public BundleEntryComponent toBundleEntry() { switch (getOldProcessState()) { @@ -176,11 +176,11 @@ public BundleEntryComponent toBundleEntry(String baseUrl) case NEW: return fromNew(); case ACTIVE: - return fromActive(baseUrl); + return fromActive(); case DRAFT: - return fromDraft(baseUrl); + return fromDraft(); case RETIRED: - return fromRetired(baseUrl); + return fromRetired(); case EXCLUDED: return fromExcluded(); default: @@ -219,14 +219,14 @@ private BundleEntryComponent fromNew() } } - private BundleEntryComponent fromActive(String baseUrl) + private BundleEntryComponent fromActive() { switch (getNewProcessState()) { case DRAFT: - return updateToDraft(baseUrl); + return updateToDraft(); case RETIRED: - return updateToRetired(baseUrl); + return updateToRetired(); case EXCLUDED: return delete(); default: @@ -235,16 +235,16 @@ private BundleEntryComponent fromActive(String baseUrl) } } - private BundleEntryComponent fromDraft(String baseUrl) + private BundleEntryComponent fromDraft() { switch (getNewProcessState()) { case ACTIVE: - return updateToActive(baseUrl); + return updateToActive(); case DRAFT: - return updateToDraft(baseUrl); + return updateToDraft(); case RETIRED: - return updateToRetired(baseUrl); + return updateToRetired(); case EXCLUDED: return delete(); default: @@ -253,14 +253,14 @@ private BundleEntryComponent fromDraft(String baseUrl) } } - private BundleEntryComponent fromRetired(String baseUrl) + private BundleEntryComponent fromRetired() { switch (getNewProcessState()) { case ACTIVE: - return updateToActive(baseUrl); + return updateToActive(); case DRAFT: - return updateToDraft(baseUrl); + return updateToDraft(); case EXCLUDED: return delete(); default: @@ -287,24 +287,24 @@ private BundleEntryComponent fromExcluded() private BundleEntryComponent createAsActive() { - if (getResource() instanceof MetadataResource) - ((MetadataResource) getResource()).setStatus(PublicationStatus.ACTIVE); + if (getResource() instanceof MetadataResource m) + m.setStatus(PublicationStatus.ACTIVE); return create(); } private BundleEntryComponent createAsDraft() { - if (getResource() instanceof MetadataResource) - ((MetadataResource) getResource()).setStatus(PublicationStatus.DRAFT); + if (getResource() instanceof MetadataResource m) + m.setStatus(PublicationStatus.DRAFT); return create(); } private BundleEntryComponent createAsRetired() { - if (getResource() instanceof MetadataResource) - ((MetadataResource) getResource()).setStatus(PublicationStatus.RETIRED); + if (getResource() instanceof MetadataResource m) + m.setStatus(PublicationStatus.RETIRED); return create(); } @@ -323,31 +323,31 @@ private BundleEntryComponent create() return entry; } - private BundleEntryComponent updateToActive(String baseUrl) + private BundleEntryComponent updateToActive() { - if (getResource() instanceof MetadataResource) - ((MetadataResource) getResource()).setStatus(PublicationStatus.ACTIVE); + if (getResource() instanceof MetadataResource m) + m.setStatus(PublicationStatus.ACTIVE); - return update(baseUrl); + return update(); } - private BundleEntryComponent updateToDraft(String baseUrl) + private BundleEntryComponent updateToDraft() { - if (getResource() instanceof MetadataResource) - ((MetadataResource) getResource()).setStatus(PublicationStatus.DRAFT); + if (getResource() instanceof MetadataResource m) + m.setStatus(PublicationStatus.DRAFT); - return update(baseUrl); + return update(); } - private BundleEntryComponent updateToRetired(String baseUrl) + private BundleEntryComponent updateToRetired() { - if (getResource() instanceof MetadataResource) - ((MetadataResource) getResource()).setStatus(PublicationStatus.RETIRED); + if (getResource() instanceof MetadataResource m) + m.setStatus(PublicationStatus.RETIRED); - return update(baseUrl); + return update(); } - private BundleEntryComponent update(String baseUrl) + private BundleEntryComponent update() { BundleEntryComponent entry = new BundleEntryComponent(); entry.setResource(getResource()); diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/spring/config/PostStartupConfig.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/spring/config/PostStartupConfig.java index 494b0d45d..d74714e78 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/spring/config/PostStartupConfig.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/spring/config/PostStartupConfig.java @@ -28,11 +28,10 @@ public void onContextRefreshedEvent(ContextRefreshedEvent event) pluginConfig.processPluginManager().loadAndDeployPlugins(); logger.info("Deploying process plugins [Done]"); - logger.info("Staring process engine ..."); + logger.info("Starting process engine ..."); camundaConfig.processEngineConfiguration().getJobExecutor().start(); - logger.info("Staring process engine [Done]"); + logger.info("Starting process engine [Done]"); - logger.info("Connecting to websockets ..."); fhirConfig.fhirConnectorTask().connect(); fhirConfig.fhirConnectorQuestionnaireResponse().connect(); // websocket connect is an async operation diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/spring/config/WebsocketConfig.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/spring/config/WebsocketConfig.java index 6e734d994..9894ca95e 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/spring/config/WebsocketConfig.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/spring/config/WebsocketConfig.java @@ -52,7 +52,7 @@ public SubscriptionHandlerFactory taskSubscriptionHandlerFactory() @Bean public FhirConnector fhirConnectorTask() { - return new FhirConnectorImpl<>("Task", fhirClientConfig.clientProvider(), taskSubscriptionHandlerFactory(), + return new FhirConnectorImpl<>(Task.class, fhirClientConfig.clientProvider(), taskSubscriptionHandlerFactory(), fhirConfig.fhirContext(), propertiesConfig.getTaskSubscriptionSearchParameter(), propertiesConfig.getWebsocketRetrySleepMillis(), propertiesConfig.getWebsocketMaxRetries()); } @@ -74,7 +74,7 @@ public SubscriptionHandlerFactory questionnaireResponseSu @Bean public FhirConnector fhirConnectorQuestionnaireResponse() { - return new FhirConnectorImpl<>("QuestionnaireResponse", fhirClientConfig.clientProvider(), + return new FhirConnectorImpl<>(QuestionnaireResponse.class, fhirClientConfig.clientProvider(), questionnaireResponseSubscriptionHandlerFactory(), fhirConfig.fhirContext(), propertiesConfig.getQuestionnaireResponseSubscriptionSearchParameter(), propertiesConfig.getWebsocketRetrySleepMillis(), propertiesConfig.getWebsocketMaxRetries()); diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/EventResourceHandlerImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/EventResourceHandlerImpl.java index badb1ac82..0810bbc53 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/EventResourceHandlerImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/EventResourceHandlerImpl.java @@ -51,7 +51,9 @@ private void writeLastEventTime(Date lastUpdated) } catch (SQLException e) { + logger.debug("Unable to write last event time to db", e); logger.warn("Unable to write last event time to db: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/EventType.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/EventType.java index e6531758f..81bda0949 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/EventType.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/EventType.java @@ -6,7 +6,7 @@ public enum EventType private final String value; - private EventType(String value) + EventType(String value) { this.value = value; } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/ExistingResourceLoaderImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/ExistingResourceLoaderImpl.java index a84ecc023..8382f53a4 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/ExistingResourceLoaderImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/ExistingResourceLoaderImpl.java @@ -112,7 +112,9 @@ private Optional readLastEventTime() } catch (SQLException e) { + logger.debug("Unable to read last event time from db", e); logger.warn("Unable to read last event time from db: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } } @@ -125,7 +127,9 @@ private void writeLastEventTime(Date lastUpdated) } catch (SQLException e) { + logger.debug("Unable to write last event time to db", e); logger.warn("Unable to write last event time to db: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/FhirConnectorImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/FhirConnectorImpl.java index 10f862372..9db5e3c48 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/FhirConnectorImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/FhirConnectorImpl.java @@ -19,6 +19,7 @@ import org.springframework.web.util.UriComponentsBuilder; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.rest.api.Constants; import dev.dsf.bpe.client.FhirClientProvider; @@ -29,7 +30,8 @@ public class FhirConnectorImpl implements FhirConnector, Ini { private static final Logger logger = LoggerFactory.getLogger(FhirConnectorImpl.class); - private final String resourcePath; + private final Class resourceType; + private final String resourceName; private final FhirClientProvider clientProvider; private final FhirContext fhirContext; private final SubscriptionHandlerFactory subscriptionHandlerFactory; @@ -37,11 +39,12 @@ public class FhirConnectorImpl implements FhirConnector, Ini private final int maxRetries; private final Map> subscriptionSearchParameter; - public FhirConnectorImpl(String resourcePath, FhirClientProvider clientProvider, + public FhirConnectorImpl(Class resourceType, FhirClientProvider clientProvider, SubscriptionHandlerFactory subscriptionHandlerFactory, FhirContext fhirContext, String subscriptionSearchParameter, long retrySleepMillis, int maxRetries) { - this.resourcePath = resourcePath; + this.resourceType = resourceType; + this.resourceName = resourceType == null ? null : resourceType.getAnnotation(ResourceDef.class).name(); this.clientProvider = clientProvider; this.subscriptionHandlerFactory = subscriptionHandlerFactory; this.fhirContext = fhirContext; @@ -50,7 +53,7 @@ public FhirConnectorImpl(String resourcePath, FhirClientProvider clientProvider, this.maxRetries = maxRetries; } - private static Map> parse(String queryParameters, String expectedPath) + private Map> parse(String queryParameters, String expectedPath) { if (expectedPath != null && !expectedPath.isBlank()) { @@ -72,8 +75,16 @@ private static Map> parse(String queryParameters, String ex @Override public void afterPropertiesSet() throws Exception { + Objects.requireNonNull(resourceType, "resourceType"); Objects.requireNonNull(clientProvider, "clientProvider"); + Objects.requireNonNull(subscriptionHandlerFactory, "subscriptionHandlerFactory"); Objects.requireNonNull(fhirContext, "fhirContext"); + Objects.requireNonNull(subscriptionSearchParameter, "subscriptionSearchParameter"); + + if (retrySleepMillis < 0) + throw new IllegalArgumentException("retrySleepMillis < 0"); + + // maxRetries < 0 => retry forever } @Override @@ -82,15 +93,26 @@ public void connect() logger.debug("Retrieving Subscription and connecting to websocket"); CompletableFuture.supplyAsync(this::retrieveWebsocketSubscription, Executors.newSingleThreadExecutor()) - .thenApply(this::loadExistingResources).thenAccept(this::connectWebsocket).exceptionally(this::onError); + .thenApply(this::loadNewResources).thenAccept(this::connectWebsocket).exceptionally(this::onError); } private Subscription retrieveWebsocketSubscription() { - if (maxRetries >= 0) - return retry(this::doRetrieveWebsocketSubscription); - else - return retryForever(this::doRetrieveWebsocketSubscription); + try + { + if (maxRetries >= 0) + return retry(this::doRetrieveWebsocketSubscription); + else + return retryForever(this::doRetrieveWebsocketSubscription); + } + catch (Exception e) + { + logger.debug("Error while retrieving {} websocket subscription", resourceName, e); + logger.warn("Error while retrieving {} websocket subscription: {} - {}", resourceName, + e.getClass().getName(), e.getMessage()); + + throw e; + } } private Subscription retry(Supplier supplier) @@ -107,8 +129,8 @@ private Subscription retry(Supplier supplier) if (retryCounter < maxRetries) { logger.warn( - "Error while retrieving websocket subscription ({}), trying again in {} ms (retry {} of {})", - e.getMessage(), retrySleepMillis, retryCounter + 1, maxRetries); + "Error while retrieving {} websocket subscription ({}), trying again in {} ms (retry {} of {})", + resourceName, e.getMessage(), retrySleepMillis, retryCounter + 1, maxRetries); try { Thread.sleep(retrySleepMillis); @@ -122,7 +144,9 @@ private Subscription retry(Supplier supplier) } } - logger.error("Error while retrieving websocket subscription ({}), giving up", lastException.getMessage()); + logger.warn("Error while retrieving {} websocket subscription ({}), giving up", resourceName, + lastException.getMessage()); + throw lastException; } @@ -136,8 +160,8 @@ private Subscription retryForever(Supplier supplier) } catch (RuntimeException e) { - logger.warn("Error while retrieving websocket subscription ({}), trying again in {} ms (retry {})", - e.getMessage(), retrySleepMillis, retryCounter); + logger.warn("Error while retrieving {} websocket subscription ({}), trying again in {} ms (retry {})", + resourceName, e.getMessage(), retrySleepMillis, retryCounter); try { Thread.sleep(retrySleepMillis); @@ -151,7 +175,7 @@ private Subscription retryForever(Supplier supplier) private Subscription doRetrieveWebsocketSubscription() { - logger.debug("Retrieving websocket subscription"); + logger.debug("Retrieving {} websocket subscription ...", resourceName); Bundle bundle = clientProvider.getLocalWebserviceClient().searchWithStrictHandling(Subscription.class, subscriptionSearchParameter); @@ -173,51 +197,72 @@ private Subscription doRetrieveWebsocketSubscription() return subscription; } - private Subscription loadExistingResources(Subscription subscription) + private Subscription loadNewResources(Subscription subscription) { - logger.debug("Downloading existing resources"); - - FhirWebserviceClient client = clientProvider.getLocalWebserviceClient(); - ExistingResourceLoader existingResourceLoader = subscriptionHandlerFactory - .createExistingResourceLoader(client); - Map> subscriptionCriteria = parse(subscription.getCriteria(), resourcePath); - existingResourceLoader.readExistingResources(subscriptionCriteria); - - return subscription; - } + try + { + logger.info("Downloading new {} resources ...", resourceName); - private void connectWebsocket(Subscription subscription) - { - logger.debug("Connecting to websocket"); + FhirWebserviceClient client = clientProvider.getLocalWebserviceClient(); + ExistingResourceLoader existingResourceLoader = subscriptionHandlerFactory + .createExistingResourceLoader(client); + Map> subscriptionCriteria = parse(subscription.getCriteria(), + resourceType.getAnnotation(ResourceDef.class).name()); + existingResourceLoader.readExistingResources(subscriptionCriteria); - WebsocketClient client = clientProvider.getLocalWebsocketClient(() -> connect(), - subscription.getIdElement().getIdPart()); + logger.info("Downloading new {} resources [Done]", resourceName); - EventType eventType = toEventType(subscription.getChannel().getPayload()); - if (EventType.PING.equals(eventType)) + return subscription; + } + catch (Exception e) { - Map> subscriptionCriteria = parse(subscription.getCriteria(), resourcePath); - setPingEventHandler(client, subscription.getIdElement().getIdPart(), subscriptionCriteria); + logger.debug("Error while downloading new {} resources", resourceName, e); + logger.warn("Error while downloading new {} resources: {} - {}", resourceName, e.getClass().getName(), + e.getMessage()); + + throw e; } - else - setResourceEventHandler(client, eventType); + } + private void connectWebsocket(Subscription subscription) + { try { - logger.info("Connecting websocket to local FHIR server with subscription id {}", + WebsocketClient client = clientProvider.getLocalWebsocketClient(() -> connect(), subscription.getIdElement().getIdPart()); + + EventType eventType = toEventType(subscription.getChannel().getPayload()); + if (EventType.PING.equals(eventType)) + { + Map> subscriptionCriteria = parse(subscription.getCriteria(), + resourceType.getAnnotation(ResourceDef.class).name()); + setPingEventHandler(client, subscription.getIdElement().getIdPart(), subscriptionCriteria); + } + else + setResourceEventHandler(client, eventType); + + logger.info("Connecting {} websocket to local DSF FHIR server, subscription: {} ...", resourceName, + subscription.getIdElement().getIdPart()); + client.connect(); } catch (Exception e) { - logger.warn("Error while connecting websocket to local FHIR server", e); + logger.debug("Unable to connect {} websocket to local DSF FHIR server", resourceName, e); + logger.warn("Unable to connect {} websocket to local DSF FHIR server: {} - {}", resourceName, + e.getClass().getName(), e.getMessage()); + throw e; } } private Void onError(Throwable t) { - logger.error("Error while connecting to websocket", t); + // no debug log, exception previously logged by retrieveWebsocketSubscription, loadNewResources and + // connectWebsocket methods + logger.error("Error while loading existing {} resources and connecting websocket: {} - {}", resourceName, + t.getClass().getName(), t.getMessage()); + return null; } @@ -280,6 +325,7 @@ private IParser configureParser(IParser p) { p.setStripVersionsFromReferences(false); p.setOverrideResourceIdWithBundleEntryFullUrl(false); + return p; } } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/QuestionnaireResponseHandler.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/QuestionnaireResponseHandler.java index 5370ce0e9..bb3446dd6 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/QuestionnaireResponseHandler.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/QuestionnaireResponseHandler.java @@ -71,7 +71,8 @@ public void onResource(QuestionnaireResponse questionnaireResponse) } catch (Exception e) { - logger.warn("Unable to complete UserTask", e); + logger.debug("Unable to complete UserTask", e); + logger.warn("Unable to complete UserTask: {} - {}", e.getClass().getName(), e.getMessage()); } } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/TaskHandler.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/TaskHandler.java index d46085737..7b22e0ab8 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/TaskHandler.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/subscription/TaskHandler.java @@ -151,17 +151,26 @@ public void onResource(Task task) } catch (MismatchingMessageCorrelationException e) { - logger.warn("Unable to handle Task with id {}: {}", task.getId(), e.getMessage()); + logger.debug("Unable to handle Task with id {}", task.getId(), e); + logger.warn("Unable to handle Task with id {}: {} - {}", task.getId(), e.getClass().getName(), + e.getMessage()); + updateTaskFailed(task, "Unable to correlate Task"); } catch (ProcessNotFoundException e) { - logger.warn("Unable to handle Task with id {}: {}", task.getId(), e.getMessage()); + logger.debug("Unable to handle Task with id {}", task.getId(), e); + logger.warn("Unable to handle Task with id {}: {} - {}", task.getId(), e.getClass().getName(), + e.getMessage()); + updateTaskFailed(task, e.getShortMessage()); } catch (Exception e) { - logger.error("Unable to handle Task with id " + task.getId(), e); + logger.debug("Unable to handle Task with id {}", task.getId(), e); + logger.error("Unable to handle Task with id {}: {} - {}", task.getId(), e.getClass().getName(), + e.getMessage()); + updateTaskFailed(task, e); } } @@ -180,9 +189,11 @@ private void updateTaskFailed(Task task, String message) { webserviceClient.update(task); } - catch (Exception ex) + catch (Exception e) { - logger.error("Unable to update Task with id {} (status failed)", task.getId()); + logger.debug("Unable to update Task with id {} (status failed)", task.getId(), e); + logger.error("Unable to update Task with id {} (status failed): {} - {}", task.getId(), + e.getClass().getName(), e.getMessage()); } } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/v1/service/MailServiceImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/v1/service/MailServiceImpl.java index 1fcf78455..34aead27e 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/v1/service/MailServiceImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/v1/service/MailServiceImpl.java @@ -10,9 +10,9 @@ public class MailServiceImpl implements MailService, InitializingBean { - private dev.dsf.bpe.v1.service.MailService delegate; + private MailService delegate; - public MailServiceImpl(dev.dsf.bpe.v1.service.MailService delegate) + public MailServiceImpl(MailService delegate) { this.delegate = delegate; } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/FhirResourceValues.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/FhirResourceValues.java index 656f545bd..8adaf566c 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/FhirResourceValues.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/FhirResourceValues.java @@ -11,7 +11,7 @@ public final class FhirResourceValues { - public static interface FhirResourceValue extends PrimitiveValue + public interface FhirResourceValue extends PrimitiveValue { } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/FhirResourcesListValues.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/FhirResourcesListValues.java index 99486430c..467039354 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/FhirResourcesListValues.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/FhirResourcesListValues.java @@ -13,7 +13,7 @@ public final class FhirResourcesListValues { - public static interface FhirResourcesListValue extends PrimitiveValue + public interface FhirResourcesListValue extends PrimitiveValue { @SuppressWarnings("unchecked") default List getFhirResources() diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/TargetValues.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/TargetValues.java index 999437411..de91ea92f 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/TargetValues.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/TargetValues.java @@ -10,7 +10,7 @@ public final class TargetValues { - public static interface TargetValue extends PrimitiveValue + public interface TargetValue extends PrimitiveValue { } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/TargetsValues.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/TargetsValues.java index 8fd5175b8..0c571ab55 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/TargetsValues.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/TargetsValues.java @@ -10,7 +10,7 @@ public final class TargetsValues { - public static interface TargetsValue extends PrimitiveValue + public interface TargetsValue extends PrimitiveValue { } diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/VariablesImpl.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/VariablesImpl.java index 57db062ad..941e7e752 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/VariablesImpl.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/variables/VariablesImpl.java @@ -24,7 +24,6 @@ import dev.dsf.bpe.variables.FhirResourceValues.FhirResourceValue; import dev.dsf.bpe.variables.FhirResourcesListValues.FhirResourcesListValue; import dev.dsf.bpe.variables.TargetValues.TargetValue; -import dev.dsf.bpe.variables.TargetsValues.TargetsValue; public class VariablesImpl implements Variables, ListenerVariables { @@ -129,17 +128,14 @@ public Targets createTargets(List targets) public void setTargets(Targets targets) throws IllegalArgumentException { if (targets == null) - { execution.setVariable(BpmnExecutionVariables.TARGETS, null); - return; - } - if (!(targets instanceof TargetsImpl)) + else if (targets instanceof TargetsImpl t) + execution.setVariable(BpmnExecutionVariables.TARGETS, TargetsValues.create(t)); + + else throw new IllegalArgumentException( "Given targets implementing class " + targets.getClass().getName() + " not supported"); - - TargetsValue variable = targets == null ? null : TargetsValues.create((TargetsImpl) targets); - execution.setVariable(BpmnExecutionVariables.TARGETS, variable); } @Override diff --git a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/webservice/RootService.java b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/webservice/RootService.java index c29fad0ef..ad336748d 100644 --- a/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/webservice/RootService.java +++ b/dsf-bpe/dsf-bpe-server/src/main/java/dev/dsf/bpe/webservice/RootService.java @@ -58,11 +58,8 @@ public Response root(@Context UriInfo uri, @Context SecurityContext securityCont private String getDisplayName(SecurityContext securityContext) { Principal userPrincipal = securityContext.getUserPrincipal(); - if (userPrincipal != null && userPrincipal instanceof Identity) - { - Identity identity = (Identity) userPrincipal; + if (userPrincipal != null && userPrincipal instanceof Identity identity) return identity.getDisplayName(); - } else return "?"; diff --git a/dsf-common/dsf-common-auth/src/main/java/dev/dsf/common/auth/conf/RoleConfig.java b/dsf-common/dsf-common-auth/src/main/java/dev/dsf/common/auth/conf/RoleConfig.java index 920a39cfa..10cf4d071 100644 --- a/dsf-common/dsf-common-auth/src/main/java/dev/dsf/common/auth/conf/RoleConfig.java +++ b/dsf-common/dsf-common-auth/src/main/java/dev/dsf/common/auth/conf/RoleConfig.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -34,7 +35,7 @@ public class RoleConfig private static final String EMAIL_PATTERN_STRING = "^[\\w!#$%&'*+/=?`{\\|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{\\|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"; private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_PATTERN_STRING); - public class Mapping + public static final class Mapping { private final String name; @@ -127,36 +128,29 @@ public String toString() public RoleConfig(Object config, Function dsfRoleFactory, Function practitionerRoleFactory) { - if (config != null && config instanceof List) + if (config != null && config instanceof List l) { - @SuppressWarnings("unchecked") - List cList = (List) config; - cList.forEach(mapping -> + l.forEach(mapping -> { - if (mapping != null && mapping instanceof Map) + if (mapping != null && mapping instanceof Map m) { - @SuppressWarnings("unchecked") - Map m = (Map) mapping; m.forEach((mappingKey, mappingValues) -> { if (mappingKey != null && mappingKey instanceof String && mappingValues != null - && mappingValues instanceof Map) + && mappingValues instanceof Map v) { - @SuppressWarnings("unchecked") - Map properties = (Map) mappingValues; - - // Map List thumbprints = null, emails = null, tokenRoles = null, tokenGroups = null; List dsfRoles = null; List practitionerRoles = null; - for (Entry p : properties.entrySet()) + + for (Entry property : v.entrySet()) { - if (p.getKey() != null && p.getKey() instanceof String) + if (property.getKey() != null && property.getKey() instanceof String key) { - switch ((String) p.getKey()) + switch (key) { case PROPERTY_THUMBPRINT: - thumbprints = getValues(p.getValue()).stream().map(value -> + thumbprints = getValues(property.getValue()).stream().map(value -> { if (value == null || value.isBlank()) { @@ -175,8 +169,9 @@ else if (!THUMBPRINT_PATTERN.matcher(value.trim()).matches()) return value.trim(); }).filter(g -> g != null).toList(); break; + case PROPERTY_EMAIL: - emails = getValues(p.getValue()).stream().map(value -> + emails = getValues(property.getValue()).stream().map(value -> { if (value == null || value.isBlank()) { @@ -195,8 +190,9 @@ else if (!EMAIL_PATTERN.matcher(value.trim()).matches()) return value.trim(); }).filter(g -> g != null).toList(); break; + case PROPERTY_TOKEN_ROLE: - tokenRoles = getValues(p.getValue()).stream().map(value -> + tokenRoles = getValues(property.getValue()).stream().map(value -> { if (value == null || value.isBlank()) { @@ -208,8 +204,9 @@ else if (!EMAIL_PATTERN.matcher(value.trim()).matches()) return value.trim(); }).filter(g -> g != null).toList(); break; + case PROPERTY_TOKEN_GROUP: - tokenGroups = getValues(p.getValue()).stream().map(value -> + tokenGroups = getValues(property.getValue()).stream().map(value -> { if (value == null || value.isBlank()) { @@ -221,8 +218,9 @@ else if (!EMAIL_PATTERN.matcher(value.trim()).matches()) return value.trim(); }).filter(g -> g != null).toList(); break; + case PROPERTY_DSF_ROLE: - dsfRoles = getValues(p.getValue()).stream().map(value -> + dsfRoles = getValues(property.getValue()).stream().map(value -> { if (value == null || value.isBlank()) { @@ -239,8 +237,9 @@ else if (!EMAIL_PATTERN.matcher(value.trim()).matches()) return dsfRole; }).filter(r -> r != null).toList(); break; + case PROPERTY_PRACTITIONER_ROLE: - practitionerRoles = getValues(p.getValue()).stream().map(value -> + practitionerRoles = getValues(property.getValue()).stream().map(value -> { if (value == null || value.isBlank()) { @@ -259,10 +258,11 @@ else if (!EMAIL_PATTERN.matcher(value.trim()).matches()) return coding; }).filter(r -> r != null).toList(); break; + default: logger.warn( "Unknown role config property '{}' expected one of {}, ignoring property in rule '{}'", - p.getKey(), PROPERTIES, mappingKey); + property.getKey(), PROPERTIES, mappingKey); } } } @@ -273,10 +273,10 @@ else if (!EMAIL_PATTERN.matcher(value.trim()).matches()) else if (mappingKey != null && mappingKey instanceof String && (mappingValues == null || !(mappingValues instanceof Map))) { - logger.warn("Ignoring invalud rule '{}'", mappingKey); + logger.warn("Ignoring invalid rule '{}', no value specified or value not map", mappingKey); } else - logger.warn("Ignoring invalud rule '{}'", mappingKey); + logger.warn("Ignoring invalid rule '{}'", Objects.toString(mappingKey)); }); } else @@ -288,10 +288,10 @@ else if (mappingKey != null && mappingKey instanceof String @SuppressWarnings("unchecked") private static List getValues(Object o) { - if (o instanceof String) - return Collections.singletonList((String) o); - else if (o instanceof List) - return ((List) o); + if (o instanceof String s) + return Collections.singletonList(s); + else if (o instanceof List l) + return l; else return Collections.emptyList(); } diff --git a/dsf-common/dsf-common-config/src/main/java/dev/dsf/common/config/ProxyConfigImpl.java b/dsf-common/dsf-common-config/src/main/java/dev/dsf/common/config/ProxyConfigImpl.java index 561629a69..da9dfaaeb 100644 --- a/dsf-common/dsf-common-config/src/main/java/dev/dsf/common/config/ProxyConfigImpl.java +++ b/dsf-common/dsf-common-config/src/main/java/dev/dsf/common/config/ProxyConfigImpl.java @@ -137,7 +137,7 @@ public boolean isNoProxyUrl(String targetUrl) } catch (URISyntaxException e) { - logger.debug("Given targetUrl '{}' is malformed, {}", targetUrl, e.getMessage()); + logger.debug("Given targetUrl '{}' is malformed: {}", targetUrl, e.getMessage()); return false; } } diff --git a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/ClientCertificateAuthenticator.java b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/ClientCertificateAuthenticator.java index aa7f67b3f..d8cf5b7f7 100644 --- a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/ClientCertificateAuthenticator.java +++ b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/ClientCertificateAuthenticator.java @@ -58,6 +58,7 @@ public Authentication validateRequest(ServletRequest request, ServletResponse re if (certificates == null || certificates.length <= 0) { logger.warn("X509Certificate could not be retrieved, sending unauthorized"); + return Authentication.UNAUTHENTICATED; } @@ -67,8 +68,10 @@ public Authentication validateRequest(ServletRequest request, ServletResponse re } catch (CertificateException e) { + logger.debug("Unable to validate client certificates, sending unauthorized", e); logger.warn("Unable to validate client certificates, sending unauthorized: {} - {}", e.getClass().getName(), e.getMessage()); + return Authentication.UNAUTHENTICATED; } @@ -76,6 +79,7 @@ public Authentication validateRequest(ServletRequest request, ServletResponse re if (user == null) { logger.warn("User '{}' not found, sending unauthorized", getSubjectDn(certificates)); + return Authentication.UNAUTHENTICATED; } @@ -95,7 +99,9 @@ private X509TrustManager createX509TrustManager(KeyStore clientTrustStore) } catch (NoSuchAlgorithmException | KeyStoreException e) { + logger.debug("Unable to create trust manager", e); logger.warn("Unable to create trust manager: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } } @@ -109,7 +115,9 @@ private X509Certificate[] getCaCertificates(KeyStore keyStore) } catch (KeyStoreException | InvalidAlgorithmParameterException e) { + logger.debug("Unable to extract trust anchors", e); logger.warn("Unable to extract trust anchors: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } } diff --git a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfLoginService.java b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfLoginService.java index 0f6abb93a..094604611 100644 --- a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfLoginService.java +++ b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfLoginService.java @@ -19,7 +19,7 @@ public class DsfLoginService implements LoginService { - private final class UserIdentityImpl implements UserIdentity + private static final class UserIdentityImpl implements UserIdentity { private final Principal principal; @@ -72,12 +72,12 @@ public UserIdentity login(String username, Object credentials, ServletRequest re return null; Principal principal = null; - if (credentials instanceof X509Certificate[]) - principal = identityProvider.getIdentity((X509Certificate[]) credentials); - else if (credentials instanceof OpenIdCredentials) - principal = identityProvider.getIdentity(new DsfOpenIdCredentialsImpl((OpenIdCredentials) credentials)); - else if (credentials instanceof String) - principal = identityProvider.getIdentity(new DsfOpenIdCredentialsImpl((String) credentials)); + if (credentials instanceof X509Certificate[] c) + principal = identityProvider.getIdentity(c); + else if (credentials instanceof OpenIdCredentials o) + principal = identityProvider.getIdentity(new DsfOpenIdCredentialsImpl(o)); + else if (credentials instanceof String s) + principal = identityProvider.getIdentity(new DsfOpenIdCredentialsImpl(s)); if (principal == null) return null; diff --git a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdConfiguration.java b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdConfiguration.java index e10da116d..173714c8a 100644 --- a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdConfiguration.java +++ b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdConfiguration.java @@ -80,7 +80,7 @@ public RSAPublicKey getPublicKeyById(String kid) return key.get(); else { - logger.warn("Unable to retrieve key with id " + kid); + logger.warn("Unable to retrieve key with id {}", kid); return null; } } @@ -100,7 +100,9 @@ public String getPrivateKeyId() } catch (InterruptedException | ExecutionException | TimeoutException e) { + logger.debug("Unable to retrieve keys from {}: {} - {}", jwksUri, e); logger.warn("Unable to retrieve keys from {}: {} - {}", jwksUri, e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } } diff --git a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdCredentialsImpl.java b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdCredentialsImpl.java index c8a1da1b1..c0d8c9a11 100644 --- a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdCredentialsImpl.java +++ b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdCredentialsImpl.java @@ -48,13 +48,13 @@ public Map getAccessToken() public Long getLongClaim(String key) { Object o = getAccessToken().get(key); - return o instanceof Long ? (Long) o : null; + return o instanceof Long l ? l : null; } @Override public String getStringClaimOrDefault(String key, String defaultValue) { Object o = getAccessToken().getOrDefault(key, defaultValue); - return o instanceof String ? (String) o : defaultValue; + return o instanceof String s ? s : defaultValue; } } diff --git a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdLoginService.java b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdLoginService.java index b74e51ac3..5755488cc 100644 --- a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdLoginService.java +++ b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/auth/DsfOpenIdLoginService.java @@ -34,9 +34,11 @@ public UserIdentity login(String identifier, Object credentials, ServletRequest { openIdCredentials.redeemAuthCode(configuration); } - catch (Throwable e) + catch (Exception e) { - logger.warn("Unable to redeem auth code", e); + logger.debug("Unable to redeem auth code", e); + logger.warn("Unable to redeem auth code: {} - {}", e.getClass().getName(), e.getMessage()); + return null; } @@ -46,11 +48,9 @@ public UserIdentity login(String identifier, Object credentials, ServletRequest @Override public boolean validate(UserIdentity user) { - if (!(user.getUserPrincipal() instanceof PractitionerIdentity)) + if (!(user.getUserPrincipal() instanceof PractitionerIdentity identity)) return false; - PractitionerIdentity identity = (PractitionerIdentity) user.getUserPrincipal(); - if (identity.getCredentials().isEmpty()) { logger.warn("No credentials"); diff --git a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/config/AbstractJettyConfig.java b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/config/AbstractJettyConfig.java index 27f19d0c6..a68f0302f 100644 --- a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/config/AbstractJettyConfig.java +++ b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/config/AbstractJettyConfig.java @@ -233,8 +233,7 @@ public JettyServer jettyServer(ConfigurableEnvironment environment) Collectors.toMap(e -> Objects.toString(e.getKey()), e -> Objects.toString(e.getValue()))); return new JettyServer(apiConnector(), statusConnector(), mavenServerModuleName(), contextPath, - servletContainerInitializers(), initParameters, clientCertificateTrustStore(), - this::configureSecurityHandler); + servletContainerInitializers(), initParameters, this::configureSecurityHandler); } private KeyStore serverCertificateKeyStore(char[] keyStorePassword) diff --git a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/jetty/HttpClientWithGetRetry.java b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/jetty/HttpClientWithGetRetry.java index 412a3232b..51ee2dbd6 100644 --- a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/jetty/HttpClientWithGetRetry.java +++ b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/jetty/HttpClientWithGetRetry.java @@ -45,15 +45,15 @@ public ContentResponse GETWithRetryOnConnectException(int times, URI uri) } catch (InterruptedException | ExecutionException | TimeoutException | RuntimeException e) { - Throwable cause = e; while (!(cause instanceof ConnectException) && cause.getCause() != null) cause = cause.getCause(); if (cause instanceof ConnectException && times > 1) { - logger.warn("Error while accessing {}: {}", uri == null ? "null" : uri.toString(), e.getMessage()); - logger.warn("ConnectException: trying again in 5s"); + logger.debug("Error while accessing {}, trying again in 5s", uri == null ? "null" : uri.toString(), e); + logger.warn("Error while accessing {}, trying again in 5s: {} - {}", + uri == null ? "null" : uri.toString(), e.getClass().getName(), e.getMessage()); try { Thread.sleep(5000); @@ -66,8 +66,9 @@ public ContentResponse GETWithRetryOnConnectException(int times, URI uri) } else if (cause instanceof UnknownHostException && times > 1) { - logger.warn("Error while accessing {}: {}", uri == null ? "null" : uri.toString(), e.getMessage()); - logger.warn("UnknownHostException: trying again in 10s"); + logger.debug("Error while accessing {}, trying again in 10s", uri == null ? "null" : uri.toString(), e); + logger.warn("Error while accessing {}, trying again in 10s: {} - {}", + uri == null ? "null" : uri.toString(), e.getClass().getName(), e.getMessage()); try { Thread.sleep(10_000); @@ -80,7 +81,10 @@ else if (cause instanceof UnknownHostException && times > 1) } else { - logger.error("Error while accessing {}: {}", uri == null ? "null" : uri.toString(), e.getMessage()); + logger.debug("Error while accessing {}", uri == null ? "null" : uri.toString(), e); + logger.warn("Error while accessing {}: {} - {}", uri == null ? "null" : uri.toString(), + e.getClass().getName(), e.getMessage()); + throw e; } } diff --git a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/jetty/JettyServer.java b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/jetty/JettyServer.java index 6682cffc5..9bdeec99e 100644 --- a/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/jetty/JettyServer.java +++ b/dsf-common/dsf-common-jetty/src/main/java/dev/dsf/common/jetty/JettyServer.java @@ -1,6 +1,7 @@ package dev.dsf.common.jetty; import java.io.IOException; +import java.io.Writer; import java.net.InetSocketAddress; import java.net.StandardSocketOptions; import java.nio.channels.ServerSocketChannel; @@ -39,6 +40,7 @@ import de.rwh.utils.crypto.CertificateHelper; import jakarta.servlet.ServletContainerInitializer; import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; public final class JettyServer { @@ -110,13 +112,15 @@ public static Function statusConnector(ServerSocketChan } catch (IOException e) { - logger.warn("Unable to open server socket channel: {}", e.getMessage()); + logger.debug("Unable to open server socket channel", e); + logger.warn("Unable to open server socket channel: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } }; } - public static final Function httpConnector(String host, int port, + public static Function httpConnector(String host, int port, String clientCertificateHeaderName) { return server -> @@ -131,7 +135,7 @@ public static final Function httpConnector(String host, }; } - public static final Function httpConnector(ServerSocketChannel channel, + public static Function httpConnector(ServerSocketChannel channel, String clientCertificateHeaderName) { return server -> @@ -147,7 +151,9 @@ public static final Function httpConnector(ServerSocket } catch (IOException e) { - logger.warn("Unable to open server socket channel: {}", e.getMessage()); + logger.debug("Unable to open server socket channel", e); + logger.warn("Unable to open server socket channel: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } }; @@ -171,7 +177,9 @@ server, sslConnectionFactory(clientCertificateTrustStore, serverCertificateKeySt } catch (IOException e) { - logger.warn("Unable to open server socket channel: {}", e.getMessage()); + logger.debug("Unable to open server socket channel", e); + logger.warn("Unable to open server socket channel: {} - {}", e.getClass().getName(), e.getMessage()); + throw new RuntimeException(e); } }; @@ -236,7 +244,9 @@ private static void logCertificateConfig(KeyStore trustStore, KeyStore keyStore) } catch (KeyStoreException e) { - logger.warn("Error while printing trust store / key store config", e); + logger.debug("Error while printing trust store / key store config", e); + logger.warn("Error while printing trust store / key store config: {} - {}", e.getClass().getName(), + e.getMessage()); } } @@ -249,8 +259,7 @@ private static void logCertificateConfig(KeyStore trustStore, KeyStore keyStore) public JettyServer(Function apiConnectorProvider, Function statusConnectorProvider, String mavenServerModuleName, String contextPath, List> servletContainerInitializers, - Map initParameters, KeyStore clientTrustStore, - BiConsumer> securityHandlerConfigurer) + Map initParameters, BiConsumer> securityHandlerConfigurer) { server = new Server(threadPool()); apiConnector = apiConnectorProvider.apply(server); @@ -316,15 +325,15 @@ private ErrorHandler statusCodeOnlyErrorHandler() return new ErrorHandler() { @Override - protected void writeErrorPage(jakarta.servlet.http.HttpServletRequest request, java.io.Writer writer, - int code, String message, boolean showStacks) throws java.io.IOException + protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, + boolean showStacks) throws IOException { - logger.warn("Error {}: {}", code, message); + logger.info("Error {}: {}", code, message); } }; } - public final void start() + public void start() { Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); @@ -344,14 +353,14 @@ public final void start() e.addSuppressed(e1); } - if (e instanceof RuntimeException) - throw (RuntimeException) e; + if (e instanceof RuntimeException r) + throw r; else throw new RuntimeException(e); } } - public final void stop() + public void stop() { logger.info("Stopping jetty server ..."); try @@ -367,7 +376,7 @@ public final void stop() /** * @return null if server not started or web application failed to start */ - public final ServletContext getServletContext() + public ServletContext getServletContext() { return webAppContext == null ? null : webAppContext.getServletContext(); } diff --git a/dsf-common/dsf-common-status/src/main/java/dev/dsf/common/status/webservice/StatusService.java b/dsf-common/dsf-common-status/src/main/java/dev/dsf/common/status/webservice/StatusService.java index 888e028ce..0ade6c89e 100644 --- a/dsf-common/dsf-common-status/src/main/java/dev/dsf/common/status/webservice/StatusService.java +++ b/dsf-common/dsf-common-status/src/main/java/dev/dsf/common/status/webservice/StatusService.java @@ -62,9 +62,8 @@ public Response status(@Context UriInfo uri, @Context HttpHeaders headers, @Cont { String errorMessage = getErrorMessage(e); + logger.debug("Error while accessing DB", e); logger.error("Error while accessing DB: {}", errorMessage); - if (logger.isDebugEnabled()) - logger.debug("Error while accessing DB", e); return Response.serverError().entity(errorMessage).build(); } diff --git a/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/All.java b/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/All.java index df14d0a99..05e65770c 100644 --- a/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/All.java +++ b/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/All.java @@ -58,8 +58,8 @@ private boolean isAuthorized(Identity identity) private Set getPractitionerRoles(Identity identity) { - if (identity instanceof PractitionerIdentity) - return ((PractitionerIdentity) identity).getPractionerRoles(); + if (identity instanceof PractitionerIdentity p) + return p.getPractionerRoles(); else return Collections.emptySet(); } @@ -130,7 +130,7 @@ public boolean recipientMatches(Extension recipientExtension) private boolean matches(Extension extension, String url) { return extension != null && url.equals(extension.getUrl()) && extension.hasValue() - && extension.getValue() instanceof Coding && matches((Coding) extension.getValue()); + && extension.getValue() instanceof Coding value && matches(value); } private boolean hasMatchingPractitionerExtension(List extensions) @@ -142,8 +142,8 @@ private boolean hasMatchingPractitionerExtension(List extensions) private boolean practitionerExtensionMatches(Extension extension) { return ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_PRACTITIONER.equals(extension.getUrl()) - && extension.hasValue() && extension.getValue() instanceof Coding - && practitionerRoleMatches((Coding) extension.getValue()); + && extension.hasValue() && extension.getValue() instanceof Coding value + && practitionerRoleMatches(value); } private boolean practitionerRoleMatches(Coding coding) @@ -205,13 +205,10 @@ private static Optional fromPractitionerRequester(Coding coding, if (practitionerRoles.size() == 1) { Extension practitionerRole = practitionerRoles.get(0); - if (practitionerRole.hasValue() && practitionerRole.getValue() instanceof Coding) + if (practitionerRole.hasValue() && practitionerRole.getValue() instanceof Coding value + && value.hasSystem() && value.hasCode() && practitionerRoleExists.test(coding)) { - Coding practitionerRoleCoding = (Coding) practitionerRole.getValue(); - if (practitionerRoleCoding.hasSystem() && practitionerRoleCoding.hasCode() - && practitionerRoleExists.test(coding)) - return Optional.of( - new All(true, practitionerRoleCoding.getSystem(), practitionerRoleCoding.getCode())); + return Optional.of(new All(true, value.getSystem(), value.getCode())); } } } @@ -223,10 +220,10 @@ public static Optional fromRecipient(Coding coding) { if (coding != null && coding.hasSystem() && ProcessAuthorizationHelper.PROCESS_AUTHORIZATION_SYSTEM.equals(coding.getSystem()) - && coding.hasCode()) + && coding.hasCode() + && ProcessAuthorizationHelper.PROCESS_AUTHORIZATION_VALUE_LOCAL_ALL.equals(coding.getCode())) { - if (ProcessAuthorizationHelper.PROCESS_AUTHORIZATION_VALUE_LOCAL_ALL.equals(coding.getCode())) - return Optional.of(new All(true, null, null)); + return Optional.of(new All(true, null, null)); // remote not allowed for recipient } diff --git a/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/Organization.java b/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/Organization.java index aa85d7d08..9cfed6494 100644 --- a/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/Organization.java +++ b/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/Organization.java @@ -76,8 +76,8 @@ private boolean hasOrganizationIdentifier(org.hl7.fhir.r4.model.Organization org private Set getPractitionerRoles(Identity identity) { - if (identity instanceof PractitionerIdentity) - return ((PractitionerIdentity) identity).getPractionerRoles(); + if (identity instanceof PractitionerIdentity p) + return p.getPractionerRoles(); else return Collections.emptySet(); } @@ -162,9 +162,8 @@ public boolean recipientMatches(Extension recipientExtension) private boolean matches(Extension extension, String url, boolean needsPractitionerRole) { return extension != null && url.equals(extension.getUrl()) && extension.hasValue() - && extension.getValue() instanceof Coding && matches((Coding) extension.getValue()) - && extension.getValue().hasExtension() - && hasMatchingOrganizationExtension(extension.getValue().getExtension(), needsPractitionerRole); + && extension.getValue() instanceof Coding value && matches(value) && value.hasExtension() + && hasMatchingOrganizationExtension(value.getExtension(), needsPractitionerRole); } private boolean hasMatchingOrganizationExtension(List extensions, boolean needsPractitionerRole) @@ -184,8 +183,8 @@ && hasMatchingSubOrganizationExtension(extension.getExtension()) else { return extension -> ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_ORGANIZATION - .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Identifier - && organizationIdentifierMatches((Identifier) extension.getValue()); + .equals(extension.getUrl()) && extension.hasValue() + && extension.getValue() instanceof Identifier value && organizationIdentifierMatches(value); } } @@ -204,8 +203,8 @@ private boolean hasMatchingSubOrganizationExtension(List extensions) private boolean subOrganizationExtensionMatches(Extension extension) { return ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_ORGANIZATION_PRACTITIONER_ORGANIZATION - .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Identifier - && organizationIdentifierMatches((Identifier) extension.getValue()); + .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Identifier value + && organizationIdentifierMatches(value); } private boolean hasMatchingPractitionerExtension(List extensions) @@ -216,8 +215,8 @@ private boolean hasMatchingPractitionerExtension(List extensions) private boolean practitionerExtensionMatches(Extension extension) { return ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_ORGANIZATION_PRACTITIONER_PRACTITIONER_ROLE - .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Coding - && practitionerRoleMatches((Coding) extension.getValue()); + .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Coding value + && practitionerRoleMatches(value); } private boolean practitionerRoleMatches(Coding coding) @@ -275,10 +274,10 @@ public static Optional fromRecipient(Coding coding, { if (coding != null && coding.hasSystem() && ProcessAuthorizationHelper.PROCESS_AUTHORIZATION_SYSTEM.equals(coding.getSystem()) - && coding.hasCode()) + && coding.hasCode() + && ProcessAuthorizationHelper.PROCESS_AUTHORIZATION_VALUE_LOCAL_ORGANIZATION.equals(coding.getCode())) { - if (ProcessAuthorizationHelper.PROCESS_AUTHORIZATION_VALUE_LOCAL_ORGANIZATION.equals(coding.getCode())) - return from(true, coding, organizationWithIdentifierExists).map(r -> (Recipient) r); + return from(true, coding, organizationWithIdentifierExists).map(r -> (Recipient) r); } return Optional.empty(); @@ -295,12 +294,11 @@ private static Optional from(boolean localIdentity, Coding if (organizations.size() == 1) { Extension organization = organizations.get(0); - if (organization.hasValue() && organization.getValue() instanceof Identifier) + if (organization.hasValue() && organization.getValue() instanceof Identifier identifier + && ProcessAuthorizationHelper.ORGANIZATION_IDENTIFIER_SYSTEM.equals(identifier.getSystem()) + && organizationWithIdentifierExists.test(identifier)) { - Identifier identifier = (Identifier) organization.getValue(); - if (ProcessAuthorizationHelper.ORGANIZATION_IDENTIFIER_SYSTEM.equals(identifier.getSystem()) - && organizationWithIdentifierExists.test(identifier)) - return Optional.of(new Organization(localIdentity, identifier.getValue(), null, null)); + return Optional.of(new Organization(localIdentity, identifier.getValue(), null, null)); } } } @@ -335,20 +333,16 @@ private static Optional fromPractitionerRequester(Coding coding, Extension organization = organizations.get(0); Extension practitionerRole = practitionerRoles.get(0); - if (organization.hasValue() && organization.getValue() instanceof Identifier - && practitionerRole.hasValue() && practitionerRole.getValue() instanceof Coding) + if (organization.hasValue() && organization.getValue() instanceof Identifier organizationIdentifier + && practitionerRole.hasValue() + && practitionerRole.getValue() instanceof Coding practitionerRoleCoding + && ProcessAuthorizationHelper.ORGANIZATION_IDENTIFIER_SYSTEM + .equals(organizationIdentifier.getSystem()) + && organizationWithIdentifierExists.test(organizationIdentifier) + && practitionerRoleExists.test(practitionerRoleCoding)) { - Identifier organizationIdentifier = (Identifier) organization.getValue(); - Coding practitionerRoleCoding = (Coding) practitionerRole.getValue(); - - if (ProcessAuthorizationHelper.ORGANIZATION_IDENTIFIER_SYSTEM - .equals(organizationIdentifier.getSystem()) - && organizationWithIdentifierExists.test(organizationIdentifier) - && practitionerRoleExists.test(practitionerRoleCoding)) - { - return Optional.of(new Organization(true, organizationIdentifier.getValue(), - practitionerRoleCoding.getSystem(), practitionerRoleCoding.getCode())); - } + return Optional.of(new Organization(true, organizationIdentifier.getValue(), + practitionerRoleCoding.getSystem(), practitionerRoleCoding.getCode())); } } } diff --git a/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/ProcessAuthorizationHelperImpl.java b/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/ProcessAuthorizationHelperImpl.java index 5090d1bde..3702b79fc 100644 --- a/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/ProcessAuthorizationHelperImpl.java +++ b/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/ProcessAuthorizationHelperImpl.java @@ -197,8 +197,7 @@ private boolean isProcessAuthorizationValid(Extension processAuthorization, Pred return isMessageNameValid(messageNames.get(0)) && isTaskProfileValid(taskProfiles.get(0), profileExists) && isRequestersValid(requesters, practitionerRoleExists, organizationWithIdentifierExists, organizationRoleExists) - && isRecipientsValid(recipients, practitionerRoleExists, organizationWithIdentifierExists, - organizationRoleExists); + && isRecipientsValid(recipients, organizationWithIdentifierExists, organizationRoleExists); } private boolean isMessageNameValid(Extension messageName) @@ -207,8 +206,8 @@ private boolean isMessageNameValid(Extension messageName) .equals(messageName.getUrl())) return false; - return messageName.hasValue() && messageName.getValue() instanceof StringType - && !((StringType) messageName.getValue()).getValueAsString().isBlank(); + return messageName.hasValue() && messageName.getValue() instanceof StringType value + && !value.getValueAsString().isBlank(); } private boolean isTaskProfileValid(Extension taskProfile, Predicate profileExists) @@ -217,8 +216,8 @@ private boolean isTaskProfileValid(Extension taskProfile, Predicate requesters, Predicate practitionerRoleExists, @@ -235,10 +234,10 @@ private boolean isRequesterValid(Extension requester, Predicate practiti || !ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_REQUESTER.equals(requester.getUrl())) return false; - if (requester.hasValue() && requester.getValue() instanceof Coding) + if (requester.hasValue() && requester.getValue() instanceof Coding value) { - return requesterFrom((Coding) requester.getValue(), practitionerRoleExists, - organizationWithIdentifierExists, organizationRoleExists).isPresent(); + return requesterFrom(value, practitionerRoleExists, organizationWithIdentifierExists, + organizationRoleExists).isPresent(); } return false; @@ -269,31 +268,30 @@ private Optional requesterFrom(Coding coding, Predicate pract return Optional.empty(); } - private boolean isRecipientsValid(List recipients, Predicate practitionerRoleExists, + private boolean isRecipientsValid(List recipients, Predicate organizationWithIdentifierExists, Predicate organizationRoleExists) { - return recipients.stream().allMatch(r -> isRecipientValid(r, practitionerRoleExists, - organizationWithIdentifierExists, organizationRoleExists)); + return recipients.stream() + .allMatch(r -> isRecipientValid(r, organizationWithIdentifierExists, organizationRoleExists)); } - private boolean isRecipientValid(Extension recipient, Predicate practitionerRoleExists, - Predicate organizationWithIdentifierExists, Predicate organizationRoleExists) + private boolean isRecipientValid(Extension recipient, Predicate organizationWithIdentifierExists, + Predicate organizationRoleExists) { if (recipient == null || !ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_RECIPIENT.equals(recipient.getUrl())) return false; - if (recipient.hasValue() && recipient.getValue() instanceof Coding) + if (recipient.hasValue() && recipient.getValue() instanceof Coding value) { - return recipientFrom((Coding) recipient.getValue(), practitionerRoleExists, - organizationWithIdentifierExists, organizationRoleExists).isPresent(); + return recipientFrom(value, organizationWithIdentifierExists, organizationRoleExists).isPresent(); } return false; } - private Optional recipientFrom(Coding coding, Predicate practitionerRoleExists, - Predicate organizationWithIdentifierExists, Predicate organizationRoleExists) + private Optional recipientFrom(Coding coding, Predicate organizationWithIdentifierExists, + Predicate organizationRoleExists) { switch (coding.getCode()) { @@ -343,7 +341,7 @@ public Stream getRecipients(ActivityDefinition activityDefinition, St .equals(e.getUrl())) .filter(Extension::hasValue).filter(e -> e.getValue() instanceof Coding) .map(e -> (Coding) e.getValue()) - .flatMap(coding -> recipientFrom(coding, c -> true, i -> true, c -> true).stream()); + .flatMap(coding -> recipientFrom(coding, i -> true, c -> true).stream()); } private Optional getAuthorizationExtension(ActivityDefinition activityDefinition, String processUrl, diff --git a/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/Role.java b/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/Role.java index 34d24fde8..a5d07be4d 100644 --- a/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/Role.java +++ b/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/process/Role.java @@ -117,8 +117,8 @@ private boolean hasParentOrganizationMemberRole(org.hl7.fhir.r4.model.Organizati private Set getPractitionerRoles(Identity identity) { - if (identity instanceof PractitionerIdentity) - return ((PractitionerIdentity) identity).getPractionerRoles(); + if (identity instanceof PractitionerIdentity p) + return p.getPractionerRoles(); else return Collections.emptySet(); } @@ -213,9 +213,8 @@ public boolean recipientMatches(Extension recipientExtension) private boolean matches(Extension extension, String url, boolean needsPractitionerRole) { return extension != null && url.equals(extension.getUrl()) && extension.hasValue() - && extension.getValue() instanceof Coding && matches((Coding) extension.getValue()) - && extension.getValue().hasExtension() && hasMatchingParentOrganizationRoleExtension( - extension.getValue().getExtension(), needsPractitionerRole); + && extension.getValue() instanceof Coding value && matches(value) && value.hasExtension() + && hasMatchingParentOrganizationRoleExtension(value.getExtension(), needsPractitionerRole); } private boolean hasMatchingParentOrganizationRoleExtension(List extension, boolean needsPractitionerRole) @@ -250,8 +249,8 @@ private boolean hasMatchingParentOrganizationExtension(List extension private boolean parentOrganizationExtensionMatches(Extension extension) { return ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_PARENT_ORGANIZATION_ROLE_PARENT_ORGANIZATION - .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Identifier - && parentOrganizationIdentifierMatches((Identifier) extension.getValue()); + .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Identifier value + && parentOrganizationIdentifierMatches(value); } private boolean parentOrganizationIdentifierMatches(Identifier identifier) @@ -269,8 +268,8 @@ private boolean hasMatchingOrganizationRoleExtension(List extensions) private boolean organizationRoleExtensionMatches(Extension extension) { return ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_PARENT_ORGANIZATION_ROLE_ORGANIZATION_ROLE - .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Coding - && organizationRoleMatches((Coding) extension.getValue()); + .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Coding value + && organizationRoleMatches(value); } private boolean organizationRoleMatches(Coding coding) @@ -287,8 +286,8 @@ private boolean hasMatchingPractitionerRoleExtension(List extensions) private boolean practitionerRoleExtensionMatches(Extension extension) { return ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_PARENT_ORGANIZATION_ROLE_PRACTITIONER_PRACTITIONER_ROLE - .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Coding - && practitionerRoleMatches((Coding) extension.getValue()); + .equals(extension.getUrl()) && extension.hasValue() && extension.getValue() instanceof Coding value + && practitionerRoleMatches(value); } private boolean practitionerRoleMatches(Coding coding) @@ -348,11 +347,10 @@ public static Optional fromRecipient(Coding coding, { if (coding != null && coding.hasSystem() && ProcessAuthorizationHelper.PROCESS_AUTHORIZATION_SYSTEM.equals(coding.getSystem()) - && coding.hasCode()) + && coding.hasCode() + && ProcessAuthorizationHelper.PROCESS_AUTHORIZATION_VALUE_LOCAL_ROLE.equals(coding.getCode())) { - if (ProcessAuthorizationHelper.PROCESS_AUTHORIZATION_VALUE_LOCAL_ROLE.equals(coding.getCode())) - return from(true, coding, organizationWithIdentifierExists, organizationRoleExists) - .map(r -> (Recipient) r); + return from(true, coding, organizationWithIdentifierExists, organizationRoleExists).map(r -> (Recipient) r); } return Optional.empty(); @@ -367,6 +365,7 @@ private static Optional from(boolean localIdentity, Coding coding, .filter(e -> ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_PARENT_ORGANIZATION_ROLE .equals(e.getUrl())) .collect(Collectors.toList()); + if (parentOrganizationRoles.size() == 1) { Extension parentOrganizationRole = parentOrganizationRoles.get(0); @@ -380,25 +379,23 @@ private static Optional from(boolean localIdentity, Coding coding, .filter(e -> ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_PARENT_ORGANIZATION_ROLE_ORGANIZATION_ROLE .equals(e.getUrl())) .collect(Collectors.toList()); + if (parentOrganizations.size() == 1 && organizationRoles.size() == 1) { Extension parentOrganization = parentOrganizations.get(0); Extension organizationRole = organizationRoles.get(0); - if (parentOrganization.hasValue() && parentOrganization.getValue() instanceof Identifier - && organizationRole.hasValue() && organizationRole.getValue() instanceof Coding) + if (parentOrganization.hasValue() + && parentOrganization.getValue() instanceof Identifier parentOrganizationIdentifier + && organizationRole.hasValue() + && organizationRole.getValue() instanceof Coding organizationRoleCoding + && ProcessAuthorizationHelper.ORGANIZATION_IDENTIFIER_SYSTEM + .equals(parentOrganizationIdentifier.getSystem()) + && organizationWithIdentifierExists.test(parentOrganizationIdentifier) + && organizationRoleExists.test(organizationRoleCoding)) { - Identifier parentOrganizationIdentifier = (Identifier) parentOrganization.getValue(); - Coding organizationRoleCoding = (Coding) organizationRole.getValue(); - - if (ProcessAuthorizationHelper.ORGANIZATION_IDENTIFIER_SYSTEM - .equals(parentOrganizationIdentifier.getSystem()) - && organizationWithIdentifierExists.test(parentOrganizationIdentifier) - && organizationRoleExists.test(organizationRoleCoding)) - { - return Optional.of(new Role(localIdentity, parentOrganizationIdentifier.getValue(), - organizationRoleCoding.getSystem(), organizationRoleCoding.getCode(), null, null)); - } + return Optional.of(new Role(localIdentity, parentOrganizationIdentifier.getValue(), + organizationRoleCoding.getSystem(), organizationRoleCoding.getCode(), null, null)); } } } @@ -418,6 +415,7 @@ private static Optional fromPractitionerRequester(Coding coding, .filter(e -> ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_PARENT_ORGANIZATION_ROLE_PRACTITIONER .equals(e.getUrl())) .collect(Collectors.toList()); + if (parentOrganizationRolePractitioners.size() == 1) { Extension parentOrganizationRolePractitioner = parentOrganizationRolePractitioners.get(0); @@ -436,30 +434,28 @@ private static Optional fromPractitionerRequester(Coding coding, .filter(e -> ProcessAuthorizationHelper.EXTENSION_PROCESS_AUTHORIZATION_PARENT_ORGANIZATION_ROLE_PRACTITIONER_PRACTITIONER_ROLE .equals(e.getUrl())) .collect(Collectors.toList()); + if (parentOrganizations.size() == 1 && organizationRoles.size() == 1 && practitionerRoles.size() == 1) { Extension parentOrganization = parentOrganizations.get(0); Extension organizationRole = organizationRoles.get(0); Extension practitionerRole = practitionerRoles.get(0); - if (parentOrganization.hasValue() && parentOrganization.getValue() instanceof Identifier - && organizationRole.hasValue() && organizationRole.getValue() instanceof Coding - && practitionerRole.hasValue() && practitionerRole.getValue() instanceof Coding) + if (parentOrganization.hasValue() + && parentOrganization.getValue() instanceof Identifier parentOrganizationIdentifier + && organizationRole.hasValue() + && organizationRole.getValue() instanceof Coding organizationRoleCoding + && practitionerRole.hasValue() + && practitionerRole.getValue() instanceof Coding practitionerRoleCoding + && ProcessAuthorizationHelper.ORGANIZATION_IDENTIFIER_SYSTEM + .equals(parentOrganizationIdentifier.getSystem()) + && organizationWithIdentifierExists.test(parentOrganizationIdentifier) + && organizationRoleExists.test(organizationRoleCoding) + && practitionerRoleExists.test(practitionerRoleCoding)) { - Identifier parentOrganizationIdentifier = (Identifier) parentOrganization.getValue(); - Coding organizationRoleCoding = (Coding) organizationRole.getValue(); - Coding practitionerRoleCoding = (Coding) practitionerRole.getValue(); - - if (ProcessAuthorizationHelper.ORGANIZATION_IDENTIFIER_SYSTEM - .equals(parentOrganizationIdentifier.getSystem()) - && organizationWithIdentifierExists.test(parentOrganizationIdentifier) - && organizationRoleExists.test(organizationRoleCoding) - && practitionerRoleExists.test(practitionerRoleCoding)) - { - return Optional.of(new Role(true, parentOrganizationIdentifier.getValue(), - organizationRoleCoding.getSystem(), organizationRoleCoding.getCode(), - practitionerRoleCoding.getSystem(), practitionerRoleCoding.getCode())); - } + return Optional.of(new Role(true, parentOrganizationIdentifier.getValue(), + organizationRoleCoding.getSystem(), organizationRoleCoding.getCode(), + practitionerRoleCoding.getSystem(), practitionerRoleCoding.getCode())); } } } diff --git a/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/read/ReadAccessHelperImpl.java b/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/read/ReadAccessHelperImpl.java index 5aff0e3bb..8be941dd4 100644 --- a/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/read/ReadAccessHelperImpl.java +++ b/dsf-fhir/dsf-fhir-auth/src/main/java/dev/dsf/fhir/authorization/read/ReadAccessHelperImpl.java @@ -351,8 +351,8 @@ private boolean isValidOrganizationReadAccessTag(Coding coding, private boolean isValidExtensionReadAccesOrganization(Extension extension, Predicate organizationWithIdentifierExists) { - return extension.hasValue() && extension.getValue() instanceof Identifier - && isValidOrganizationIdentifier((Identifier) extension.getValue(), organizationWithIdentifierExists); + return extension.hasValue() && extension.getValue() instanceof Identifier value + && isValidOrganizationIdentifier(value, organizationWithIdentifierExists); } private boolean isValidOrganizationIdentifier(Identifier identifier, @@ -390,15 +390,15 @@ private boolean isValidExtensionReadAccessParentOrganizationMemberRoleParentOrga Predicate organizationWithIdentifierExists) { return e.hasUrl() && EXTENSION_READ_ACCESS_PARENT_ORGANIZATION_ROLE_PARENT_ORGANIZATION.equals(e.getUrl()) - && e.hasValue() && e.getValue() instanceof Identifier - && isValidOrganizationIdentifier((Identifier) e.getValue(), organizationWithIdentifierExists); + && e.hasValue() && e.getValue() instanceof Identifier value + && isValidOrganizationIdentifier(value, organizationWithIdentifierExists); } private boolean isValidExtensionReadAccessParentOrganizationMemberRoleRole(Extension e, Predicate roleExists) { return e.hasUrl() && EXTENSION_READ_ACCESS_PARENT_ORGANIZATION_ROLE_ORGANIZATION_ROLE.equals(e.getUrl()) - && e.hasValue() && e.getValue() instanceof Coding && isValidRole((Coding) e.getValue(), roleExists); + && e.hasValue() && e.getValue() instanceof Coding value && isValidRole(value, roleExists); } private boolean isValidRole(Coding coding, Predicate roleExists) diff --git a/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/adapter/FhirAdapter.java b/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/adapter/FhirAdapter.java index 16f773e90..e3c8faf62 100755 --- a/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/adapter/FhirAdapter.java +++ b/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/adapter/FhirAdapter.java @@ -82,10 +82,10 @@ public BaseResource readFrom(Class type, Type genericType, Annotat private BaseResource fixResource(BaseResource resource) { - if (resource instanceof Bundle) - return fixBundle((Bundle) resource); - else if (resource instanceof Binary) - return fixBinary((Binary) resource); + if (resource instanceof Bundle b) + return fixBundle(b); + else if (resource instanceof Binary b) + return fixBinary(b); else return resource; } diff --git a/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/prefer/PreferHandlingType.java b/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/prefer/PreferHandlingType.java index 31781b33a..de8cec364 100644 --- a/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/prefer/PreferHandlingType.java +++ b/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/prefer/PreferHandlingType.java @@ -6,7 +6,7 @@ public enum PreferHandlingType private final String headerValue; - private PreferHandlingType(String headerValue) + PreferHandlingType(String headerValue) { this.headerValue = headerValue; } diff --git a/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/prefer/PreferReturnType.java b/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/prefer/PreferReturnType.java index 6a3877d3f..aa368074f 100644 --- a/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/prefer/PreferReturnType.java +++ b/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/prefer/PreferReturnType.java @@ -6,7 +6,7 @@ public enum PreferReturnType private final String headerValue; - private PreferReturnType(String headerValue) + PreferReturnType(String headerValue) { this.headerValue = headerValue; } diff --git a/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/service/ReferenceCleanerImpl.java b/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/service/ReferenceCleanerImpl.java index 4d40f332f..601018d91 100644 --- a/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/service/ReferenceCleanerImpl.java +++ b/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/service/ReferenceCleanerImpl.java @@ -15,7 +15,7 @@ public class ReferenceCleanerImpl implements ReferenceCleaner { private static final Logger logger = LoggerFactory.getLogger(ReferenceCleanerImpl.class); - private ReferenceExtractor referenceExtractor; + private final ReferenceExtractor referenceExtractor; public ReferenceCleanerImpl(ReferenceExtractor referenceExtractor) { @@ -50,11 +50,8 @@ public R cleanReferenceResourcesIfBundle(R resource) if (resource == null) return null; - if (resource instanceof Bundle) - { - Bundle bundle = (Bundle) resource; - bundle.getEntry().stream().map(e -> e.getResource()).forEach(this::fixBundleEntry); - } + if (resource instanceof Bundle b) + b.getEntry().stream().map(e -> e.getResource()).forEach(this::fixBundleEntry); return resource; } @@ -71,10 +68,10 @@ private void fixBundleEntry(Resource resource) references.filter(ResourceReference::hasReference).forEach(r -> r.getReference().setResource(null)); - if (resource instanceof DomainResource && ((DomainResource) resource).hasContained()) + if (resource instanceof DomainResource d && d.hasContained()) { logger.warn("{} has contained resources, removing resources", resource.getClass().getName()); - ((DomainResource) resource).setContained(null); + d.setContained(null); } } } diff --git a/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/service/ResourceReference.java b/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/service/ResourceReference.java index 8a07122b7..7dccd6930 100644 --- a/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/service/ResourceReference.java +++ b/dsf-fhir/dsf-fhir-rest-adapter/src/main/java/dev/dsf/fhir/service/ResourceReference.java @@ -1,22 +1,5 @@ package dev.dsf.fhir.service; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.ATTACHMENT_CONDITIONAL_URL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.ATTACHMENT_LITERAL_EXTERNAL_URL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.ATTACHMENT_LITERAL_INTERNAL_URL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.ATTACHMENT_TEMPORARY_URL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.ATTACHMENT_UNKNOWN_URL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.CONDITIONAL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.LITERAL_EXTERNAL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.LITERAL_INTERNAL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.LOGICAL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.RELATED_ARTEFACT_CONDITIONAL_URL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.RELATED_ARTEFACT_LITERAL_EXTERNAL_URL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.RELATED_ARTEFACT_LITERAL_INTERNAL_URL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.RELATED_ARTEFACT_TEMPORARY_URL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.RELATED_ARTEFACT_UNKNOWN_URL; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.TEMPORARY; -import static dev.dsf.fhir.service.ResourceReference.ReferenceType.UNKNOWN; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -95,7 +78,7 @@ public class ResourceReference + "|SupplyDelivery|SupplyRequest|Task|TerminologyCapabilities|TestReport|TestScript|ValueSet" + "|VerificationResult|VisionPrescription)" + "(?\\?.*)"); - public static enum ReferenceType + public enum ReferenceType { /** * temporary reference starting with urn:uuid: @@ -279,24 +262,24 @@ public ReferenceType getType(String localServerBase) { Matcher tempIdRefMatcher = TEMP_ID_PATTERN.matcher(relatedArtifact.getUrl()); if (tempIdRefMatcher.matches()) - return RELATED_ARTEFACT_TEMPORARY_URL; + return ReferenceType.RELATED_ARTEFACT_TEMPORARY_URL; Matcher idRefMatcher = ID_PATTERN.matcher(relatedArtifact.getUrl()); if (idRefMatcher.matches()) { IdType id = new IdType(relatedArtifact.getUrl()); if (!id.isAbsolute() || localServerBase.equals(id.getBaseUrl())) - return RELATED_ARTEFACT_LITERAL_INTERNAL_URL; + return ReferenceType.RELATED_ARTEFACT_LITERAL_INTERNAL_URL; else - return RELATED_ARTEFACT_LITERAL_EXTERNAL_URL; + return ReferenceType.RELATED_ARTEFACT_LITERAL_EXTERNAL_URL; } Matcher conditionalRefMatcher = CONDITIONAL_REF_PATTERN.matcher(relatedArtifact.getUrl()); if (conditionalRefMatcher.matches()) - return RELATED_ARTEFACT_CONDITIONAL_URL; + return ReferenceType.RELATED_ARTEFACT_CONDITIONAL_URL; } - return RELATED_ARTEFACT_UNKNOWN_URL; + return ReferenceType.RELATED_ARTEFACT_UNKNOWN_URL; } else if (attachment != null) { @@ -304,24 +287,24 @@ else if (attachment != null) { Matcher tempIdRefMatcher = TEMP_ID_PATTERN.matcher(attachment.getUrl()); if (tempIdRefMatcher.matches()) - return ATTACHMENT_TEMPORARY_URL; + return ReferenceType.ATTACHMENT_TEMPORARY_URL; Matcher idRefMatcher = ID_PATTERN.matcher(attachment.getUrl()); if (idRefMatcher.matches()) { IdType id = new IdType(attachment.getUrl()); if (!id.isAbsolute() || localServerBase.equals(id.getBaseUrl())) - return ATTACHMENT_LITERAL_INTERNAL_URL; + return ReferenceType.ATTACHMENT_LITERAL_INTERNAL_URL; else - return ATTACHMENT_LITERAL_EXTERNAL_URL; + return ReferenceType.ATTACHMENT_LITERAL_EXTERNAL_URL; } Matcher conditionalRefMatcher = CONDITIONAL_REF_PATTERN.matcher(attachment.getUrl()); if (conditionalRefMatcher.matches()) - return ATTACHMENT_CONDITIONAL_URL; + return ReferenceType.ATTACHMENT_CONDITIONAL_URL; } - return ATTACHMENT_UNKNOWN_URL; + return ReferenceType.ATTACHMENT_UNKNOWN_URL; } else if (reference != null) { @@ -329,29 +312,29 @@ else if (reference != null) { Matcher tempIdRefMatcher = TEMP_ID_PATTERN.matcher(reference.getReference()); if (tempIdRefMatcher.matches()) - return TEMPORARY; + return ReferenceType.TEMPORARY; Matcher idRefMatcher = ID_PATTERN.matcher(reference.getReference()); if (idRefMatcher.matches()) { IdType id = new IdType(reference.getReference()); if (!id.isAbsolute() || localServerBase.equals(id.getBaseUrl())) - return LITERAL_INTERNAL; + return ReferenceType.LITERAL_INTERNAL; else - return LITERAL_EXTERNAL; + return ReferenceType.LITERAL_EXTERNAL; } Matcher conditionalRefMatcher = CONDITIONAL_REF_PATTERN.matcher(reference.getReference()); if (conditionalRefMatcher.matches()) - return CONDITIONAL; + return ReferenceType.CONDITIONAL; } else if (reference.hasType() && reference.hasIdentifier() && reference.getIdentifier().hasSystem() && reference.getIdentifier().hasValue()) { - return LOGICAL; + return ReferenceType.LOGICAL; } - return UNKNOWN; + return ReferenceType.UNKNOWN; } else throw new IllegalStateException("Either reference or relatedArtifact expected"); @@ -373,8 +356,8 @@ public String getServerBase(String localServerBase) { Objects.requireNonNull(localServerBase, "localServerBase"); - if (EnumSet.of(LITERAL_EXTERNAL, RELATED_ARTEFACT_LITERAL_EXTERNAL_URL, ATTACHMENT_LITERAL_EXTERNAL_URL) - .contains(getType(localServerBase))) + if (EnumSet.of(ReferenceType.LITERAL_EXTERNAL, ReferenceType.RELATED_ARTEFACT_LITERAL_EXTERNAL_URL, + ReferenceType.ATTACHMENT_LITERAL_EXTERNAL_URL).contains(getType(localServerBase))) return new IdType(getValue()).getBaseUrl(); else return ""; diff --git a/dsf-fhir/dsf-fhir-server-jetty/src/main/java/dev/dsf/fhir/FhirJettyServer.java b/dsf-fhir/dsf-fhir-server-jetty/src/main/java/dev/dsf/fhir/FhirJettyServer.java index 70e57346e..604dce0cb 100755 --- a/dsf-fhir/dsf-fhir-server-jetty/src/main/java/dev/dsf/fhir/FhirJettyServer.java +++ b/dsf-fhir/dsf-fhir-server-jetty/src/main/java/dev/dsf/fhir/FhirJettyServer.java @@ -9,7 +9,7 @@ import dev.dsf.fhir.config.FhirHttpJettyConfig; import dev.dsf.tools.db.DbMigrator; -public class FhirJettyServer +public final class FhirJettyServer { static { @@ -19,6 +19,10 @@ public class FhirJettyServer Log4jInitializer.initializeLog4j(); } + private FhirJettyServer() + { + } + public static void main(String[] args) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( diff --git a/dsf-fhir/dsf-fhir-server-jetty/src/main/java/dev/dsf/fhir/FhirJettyServerHttps.java b/dsf-fhir/dsf-fhir-server-jetty/src/main/java/dev/dsf/fhir/FhirJettyServerHttps.java index 11cce5dba..f49c1b02b 100755 --- a/dsf-fhir/dsf-fhir-server-jetty/src/main/java/dev/dsf/fhir/FhirJettyServerHttps.java +++ b/dsf-fhir/dsf-fhir-server-jetty/src/main/java/dev/dsf/fhir/FhirJettyServerHttps.java @@ -9,7 +9,7 @@ import dev.dsf.fhir.config.FhirHttpsJettyConfig; import dev.dsf.tools.db.DbMigrator; -public class FhirJettyServerHttps +public final class FhirJettyServerHttps { static { @@ -19,6 +19,10 @@ public class FhirJettyServerHttps Log4jInitializer.initializeLog4j(); } + private FhirJettyServerHttps() + { + } + public static void main(String[] args) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( diff --git a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/AbstractHtmlAdapter.java b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/AbstractHtmlAdapter.java new file mode 100644 index 000000000..9038f58bb --- /dev/null +++ b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/AbstractHtmlAdapter.java @@ -0,0 +1,51 @@ +package dev.dsf.fhir.adapter; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Objects; + +import org.hl7.fhir.r4.model.Resource; + +public abstract class AbstractHtmlAdapter +{ + protected static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + protected static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); + protected static final DateTimeFormatter DATE_TIME_DISPLAY_FORMAT = DateTimeFormatter + .ofPattern("dd.MM.yyyy HH:mm:ss"); + + /** + * @param date + * may be null + * @param formatter + * not null + * @return empty String if given date is null + */ + protected String format(Date date, DateTimeFormatter formatter) + { + Objects.requireNonNull(formatter, "formatter"); + + if (date == null) + return ""; + else + return formatter.format(LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault())); + } + + /** + * @param resource + * may be null + * @param formatter + * not null + * @return empty String if given resource is null or has no meta or meta.lastUpdated + */ + protected String formatLastUpdated(Resource resource, DateTimeFormatter formatter) + { + Objects.requireNonNull(formatter, "formatter"); + + if (resource == null || !resource.hasMeta() || !resource.getMeta().hasLastUpdated()) + return ""; + else + return format(resource.getMeta().getLastUpdated(), formatter); + } +} diff --git a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/EndpointHtmlGenerator.java b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/EndpointHtmlGenerator.java index 025b2b332..20184749a 100644 --- a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/EndpointHtmlGenerator.java +++ b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/EndpointHtmlGenerator.java @@ -27,7 +27,7 @@ public void writeHtml(URI resourceUri, Endpoint resource, OutputStreamWriter out out.write("\n"); writeMeta(resource, out); - writeRow("Status", (resource.hasStatus() ? resource.getStatus().toCode() : ""), out); + writeRow("Status", resource.hasStatus() ? resource.getStatus().toCode() : "", out); writeSectionHeader("Endpoint", out); diff --git a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/HtmlFhirAdapter.java b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/HtmlFhirAdapter.java index 4d6758264..f0238da18 100644 --- a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/HtmlFhirAdapter.java +++ b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/HtmlFhirAdapter.java @@ -176,12 +176,11 @@ public void writeTo(Resource resource, Class type, Type genericType, Annotati out.write("
\n"); Principal userPrincipal = securityContext.getUserPrincipal(); - if (userPrincipal instanceof Identity) + if (userPrincipal instanceof Identity i) { - Identity identity = (Identity) userPrincipal; out.write(""); out.write("Hello, "); - out.write(identity.getDisplayName()); + out.write(i.getDisplayName()); out.write("\n"); } @@ -344,7 +343,7 @@ private URI toURI(String str) private Optional getResourceUrlString(Resource resource) throws MalformedURLException { - if (resource instanceof Resource && resource.getIdElement().hasIdPart()) + if (resource.getIdElement().hasIdPart()) { if (!uriInfo.getPath().contains("_history")) return Optional.of(String.format("%s/%s/%s", serverBaseUrl, resource.getIdElement().getResourceType(), @@ -354,9 +353,8 @@ private Optional getResourceUrlString(Resource resource) throws Malforme String.format("%s/%s/%s/_history/%s", serverBaseUrl, resource.getIdElement().getResourceType(), resource.getIdElement().getIdPart(), resource.getIdElement().getVersionIdPart())); } - else if (resource instanceof Bundle && !resource.getIdElement().hasIdPart()) - return ((Bundle) resource).getLink().stream().filter(c -> "self".equals(c.getRelation())).findFirst() - .map(c -> c.getUrl()); + else if (resource instanceof Bundle b && !resource.getIdElement().hasIdPart()) + return b.getLink().stream().filter(c -> "self".equals(c.getRelation())).findFirst().map(c -> c.getUrl()); else return Optional.empty(); } @@ -494,9 +492,7 @@ private Optional getResourceName(Resource resource, String uuid) return new IdType(c.getResponse().getLocation()).getResourceType(); }).findFirst(); } - else if (resource instanceof Resource) - return Optional.of(resource.getClass().getAnnotation(ResourceDef.class).name()); else - return Optional.empty(); + return Optional.of(resource.getClass().getAnnotation(ResourceDef.class).name()); } } diff --git a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/InputHtmlGenerator.java b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/InputHtmlGenerator.java index 29b31fe87..3559463d2 100644 --- a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/InputHtmlGenerator.java +++ b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/InputHtmlGenerator.java @@ -2,7 +2,6 @@ import java.io.IOException; import java.io.OutputStreamWriter; -import java.text.SimpleDateFormat; import java.util.List; import java.util.Map; import java.util.Optional; @@ -23,12 +22,8 @@ import org.hl7.fhir.r4.model.Type; import org.hl7.fhir.r4.model.UriType; -public abstract class InputHtmlGenerator +public abstract class InputHtmlGenerator extends AbstractHtmlAdapter { - protected static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); - protected static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); - protected static final SimpleDateFormat DATE_TIME_DISPLAY_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - protected void writeDisplayRow(String text, String elementName, boolean display, OutputStreamWriter out) throws IOException { @@ -116,7 +111,7 @@ else if (type instanceof DecimalType d) } else if (type instanceof DateType d) { - String date = d.hasValue() ? DATE_FORMAT.format(d.getValue()) : ""; + String date = d.hasValue() ? format(d.getValue(), DATE_FORMAT) : ""; writeInputFieldValueInput("date", date, elementName, elementIndex, writable, out); } else if (type instanceof TimeType t) @@ -126,12 +121,12 @@ else if (type instanceof TimeType t) } else if (type instanceof DateTimeType dt) { - String dateTime = dt.hasValue() ? DATE_TIME_FORMAT.format(dt.getValue()) : ""; + String dateTime = dt.hasValue() ? format(dt.getValue(), DATE_TIME_FORMAT) : ""; writeInputFieldValueInput("datetime-local", dateTime, elementName, elementIndex, writable, out); } else if (type instanceof InstantType i) { - String dateTime = i.hasValue() ? DATE_TIME_FORMAT.format(i.getValue()) : ""; + String dateTime = i.hasValue() ? format(i.getValue(), DATE_TIME_FORMAT) : ""; writeInputFieldValueInput("datetime-local", dateTime, elementName, elementIndex, writable, out); } else if (type instanceof UriType u) @@ -190,7 +185,7 @@ private void writeInputFieldValueInput(String type, String value, String element { out.write("
\n"); writeInput(type, value, elementName, elementIndex, Optional.empty(), writable, out); - writePlaceholderButton(elementName, value, writable, out); + writePlaceholderButton(writable, out); out.write("
\n"); } @@ -199,13 +194,13 @@ private void writeInputFieldSystemCodeInput(String system, String code, String e { out.write("
\n"); writeInput("url", system, elementName + "-system", elementIndex, Optional.empty(), writable, out); - writePlaceholderButton(elementName + "-system", system, writable, out); + writePlaceholderButton(writable, out); out.write("
\n"); out.write("
\n"); writeInput("text", code, elementName + "-code", elementIndex, Optional.of("identifier-coding-code"), writable, out); - writePlaceholderButton(elementName + "-code", code, writable, out); + writePlaceholderButton(writable, out); out.write("
\n"); } @@ -217,8 +212,7 @@ private void writeInput(String type, String value, String elementName, int eleme + (writable ? "placeholder=\"" + value + "\"" : "value=\"" + value + "\"") + ">\n"); } - private void writePlaceholderButton(String elementName, String value, boolean writable, OutputStreamWriter out) - throws IOException + private void writePlaceholderButton(boolean writable, OutputStreamWriter out) throws IOException { if (writable) { diff --git a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/OrganizationHtmlGenerator.java b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/OrganizationHtmlGenerator.java index 814b5f4da..293beef5d 100644 --- a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/OrganizationHtmlGenerator.java +++ b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/OrganizationHtmlGenerator.java @@ -92,9 +92,9 @@ public void writeHtml(URI resourceUri, Organization resource, OutputStreamWriter if (contact.hasName()) writeRow("Name", - (contact.getName().getNameAsSingleString() != null + contact.getName().getNameAsSingleString() != null ? contact.getName().getNameAsSingleString() - : ""), + : "", out); if (contact.hasAddress()) @@ -135,11 +135,11 @@ private void writeRowWithContacts(List contacts, OutputStreamWrite if (eMail.isPresent()) writeRowWithAdditionalRowClasses("eMail", eMail.get().getValue(), - (phone.isPresent() ? "contact-element-50 contact-element-margin" : "contact-element-100"), out); + phone.isPresent() ? "contact-element-50 contact-element-margin" : "contact-element-100", out); if (phone.isPresent()) writeRowWithAdditionalRowClasses("Phone", phone.get().getValue(), - (eMail.isPresent() ? "contact-element-50" : "contact-element-100"), out); + eMail.isPresent() ? "contact-element-50" : "contact-element-100", out); out.write("
\n"); } diff --git a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/QuestionnaireResponseHtmlGenerator.java b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/QuestionnaireResponseHtmlGenerator.java index d7d57bc2d..413cc56f4 100644 --- a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/QuestionnaireResponseHtmlGenerator.java +++ b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/QuestionnaireResponseHtmlGenerator.java @@ -57,9 +57,7 @@ public void writeHtml(URI resourceUri, QuestionnaireResponse questionnaireRespon + " / " + (questionnaireResponse.getIdElement() == null ? "" : questionnaireResponse.getIdElement().getVersionIdPart()) + "\n"); - out.write("
  • Last Updated: " - + (questionnaireResponse.getMeta().getLastUpdated() == null ? "" - : DATE_TIME_DISPLAY_FORMAT.format(questionnaireResponse.getMeta().getLastUpdated())) + out.write("
  • Last Updated: " + formatLastUpdated(questionnaireResponse, DATE_TIME_DISPLAY_FORMAT) + "
  • \n"); out.write("
  • Status: " + (questionnaireResponse.getStatus() == null ? "" : questionnaireResponse.getStatus().toCode()) diff --git a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/ResourceHtmlGenerator.java b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/ResourceHtmlGenerator.java index b41adffd2..d367f1ac2 100644 --- a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/ResourceHtmlGenerator.java +++ b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/ResourceHtmlGenerator.java @@ -4,15 +4,12 @@ import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; -import java.text.SimpleDateFormat; import java.util.List; import org.hl7.fhir.r4.model.Resource; -public abstract class ResourceHtmlGenerator +public abstract class ResourceHtmlGenerator extends AbstractHtmlAdapter { - protected static final SimpleDateFormat DATE_TIME_DISPLAY_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - protected String getServerBaseUrlPath(String serverBaseUrl) { try @@ -39,8 +36,8 @@ protected void writeMeta(Resource resource, OutputStreamWriter out) throws IOExc if (resource.getMeta().hasLastUpdated()) { - writeRowWithAdditionalRowClasses("Last Updated", - DATE_TIME_DISPLAY_FORMAT.format(resource.getMeta().getLastUpdated()), "last-updated", out); + writeRowWithAdditionalRowClasses("Last Updated", formatLastUpdated(resource, DATE_TIME_DISPLAY_FORMAT), + "last-updated", out); } out.write("\n"); diff --git a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/SearchBundleHtmlGenerator.java b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/SearchBundleHtmlGenerator.java index bca3631b5..e1599729d 100644 --- a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/SearchBundleHtmlGenerator.java +++ b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/SearchBundleHtmlGenerator.java @@ -5,7 +5,6 @@ import java.net.MalformedURLException; import java.net.URI; import java.net.URL; -import java.text.SimpleDateFormat; import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -40,9 +39,8 @@ import jakarta.ws.rs.core.MultivaluedMap; -public class SearchBundleHtmlGenerator extends InputHtmlGenerator implements HtmlGenerator +public class SearchBundleHtmlGenerator extends AbstractHtmlAdapter implements HtmlGenerator { - private static final SimpleDateFormat DATE_TIME_DISPLAY_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); private static final String INSTANTIATES_CANONICAL_PATTERN_STRING = "(?http[s]{0,1}://(?(?:(?:[a-zA-Z0-9]{1,63}|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])\\.)+(?:[a-zA-Z0-9]{1,63}))" + "/bpe/Process/(?[a-zA-Z0-9-]+))\\|(?\\d+\\.\\d+)$"; private static final Pattern INSTANTIATES_CANONICAL_PATTERN = Pattern @@ -317,14 +315,6 @@ private String createResourceLink(Reference reference) } } - private String toLastUpdated(Resource resource) - { - if (resource == null || !resource.hasMeta() || !resource.getMeta().hasLastUpdated()) - return ""; - else - return DATE_TIME_DISPLAY_FORMAT.format(resource.getMeta().getLastUpdated()); - } - private String getTaskRow(Task resource) { String domain = "", processName = "", processVersion = ""; @@ -364,7 +354,8 @@ private String getTaskRow(Task resource) ? resource.getRequester().getIdentifier().getValue() : "") + "" - + businessKeyOrIdentifier + "" + toLastUpdated(resource) + ""; + + businessKeyOrIdentifier + "" + formatLastUpdated(resource, DATE_TIME_DISPLAY_FORMAT) + + ""; } private Predicate isStringParam(String system, String code) @@ -386,7 +377,8 @@ private String getQuestionnaireResponseRow(QuestionnaireResponse resource) + createResourceLink(resource) + "" + (resource.hasStatus() ? resource.getStatus().toCode() : "") + "" + (resource.hasQuestionnaire() ? resource.getQuestionnaire().replaceAll("\\|", " \\| ") : "") - + "" + businessKey + "" + toLastUpdated(resource) + ""; + + "" + businessKey + "" + + formatLastUpdated(resource, DATE_TIME_DISPLAY_FORMAT) + ""; } private String getIdentifierValues(D resource, Function hasIdentifier, @@ -414,7 +406,8 @@ private String getOrganizationRow(Organization resource) return "" + createResourceLink(resource) + "" + (resource.hasActive() ? resource.getActive() : "") + "" + identifier + "" + name + "" - + createResourceLink(resource.getEndpoint()) + "" + toLastUpdated(resource) + ""; + + createResourceLink(resource.getEndpoint()) + "" + + formatLastUpdated(resource, DATE_TIME_DISPLAY_FORMAT) + ""; } private String getOrganizationAffiliationRow(OrganizationAffiliation resource) @@ -428,7 +421,7 @@ private String getOrganizationAffiliationRow(OrganizationAffiliation resource) + "" + createResourceLink(resource.getOrganization()) + "" + createResourceLink(resource.getParticipatingOrganization()) + "" + role + "" + createResourceLink(resource.getEndpoint()) - + "" + toLastUpdated(resource) + ""; + + "" + formatLastUpdated(resource, DATE_TIME_DISPLAY_FORMAT) + ""; } private String getEndpointRow(Endpoint resource) @@ -442,6 +435,6 @@ private String getEndpointRow(Endpoint resource) + (resource.hasStatus() ? resource.getStatus().toCode() : "") + "" + identifier + "" + name + "" + (resource.hasAddress() ? resource.getAddress() : "") + "" + createResourceLink(resource.getManagingOrganization()) + "" - + toLastUpdated(resource) + ""; + + formatLastUpdated(resource, DATE_TIME_DISPLAY_FORMAT) + ""; } } diff --git a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/TaskHtmlGenerator.java b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/TaskHtmlGenerator.java index 8b016667d..ba0532bf5 100644 --- a/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/TaskHtmlGenerator.java +++ b/dsf-fhir/dsf-fhir-server/src/main/java/dev/dsf/fhir/adapter/TaskHtmlGenerator.java @@ -60,8 +60,7 @@ public void writeHtml(URI resourceUri, Task task, OutputStreamWriter out) throws out.write("