001package ca.cdr.test.app.clients;
002/*-
003 * #%L
004 * Smile CDR - CDR
005 * %%
006 * Copyright (C) 2016 - 2026 Smile CDR, Inc.
007 * %%
008 * All rights reserved.
009 * #L%
010 */
011
012import ca.cdr.api.model.enm.ClientStatusFilterEnum;
013import ca.cdr.api.model.json.AuditEventsJson;
014import ca.cdr.api.model.json.CdaJson.CdaTemplateJson;
015import ca.cdr.api.model.json.CdaJson.CdaTemplateRequestJson;
016import ca.cdr.api.model.json.CdaJson.CdaTemplateResponseJson;
017import ca.cdr.api.model.json.CdaJson.CdaTemplateViewAllResponseJson;
018import ca.cdr.api.model.json.EtlImportProcessFileResponseJson;
019import ca.cdr.api.model.json.LoggerConfigJson;
020import ca.cdr.api.model.json.MdmAlgorithmsListJson;
021import ca.cdr.api.model.json.MdmMetricsJson;
022import ca.cdr.api.model.json.OAuth2ClientDetailsJson;
023import ca.cdr.api.model.json.OAuth2ClientsJson;
024import ca.cdr.api.model.json.OAuth2KeystoreJson;
025import ca.cdr.api.model.json.OAuth2KeystoresJson;
026import ca.cdr.api.model.json.OAuth2RevokeAllWithScopeResponseJson;
027import ca.cdr.api.model.json.OAuth2ServerJson;
028import ca.cdr.api.model.json.OAuth2ServersJson;
029import ca.cdr.api.model.json.OAuth2WritableClientDetailsJson;
030import ca.cdr.api.model.json.PrivacyNoticeAcceptRequestJson;
031import ca.cdr.api.model.json.PrivacyNoticeAcceptanceJson;
032import ca.cdr.api.model.json.PrivacyNoticeJson;
033import ca.cdr.api.model.json.PrivacyNoticeStatusJson;
034import ca.cdr.api.model.json.TransactionLogEventCodesJson;
035import ca.cdr.api.model.json.TransactionLogEventsJson;
036import ca.cdr.api.model.json.UserDetailsJson;
037import ca.cdr.api.model.json.batch2json.AllBatch2JobInstancesJson;
038import ca.cdr.api.model.json.batch2json.Batch2JobInstanceJson;
039import ca.cdr.api.model.json.batch2json.Batch2JobInstancesJson;
040import ca.cdr.test.app.clients.common.HttpClientOwnership;
041import ca.cdr.test.app.clients.common.RequestFactoryUtil;
042import ca.cdr.test.app.clients.common.SmileTestHttpClient;
043import ca.cdr.test.model.NodeConfigurations;
044import ca.uhn.fhir.context.FhirContext;
045import ca.uhn.fhir.context.FhirVersionEnum;
046import com.fasterxml.jackson.core.JsonProcessingException;
047import com.fasterxml.jackson.databind.JsonNode;
048import com.fasterxml.jackson.databind.ObjectMapper;
049import jakarta.annotation.Nonnull;
050import jakarta.annotation.Nullable;
051import org.apache.commons.lang3.Validate;
052import org.hl7.fhir.instance.model.api.IBaseParameters;
053import org.hl7.fhir.instance.model.api.IBaseResource;
054import org.slf4j.Logger;
055import org.slf4j.LoggerFactory;
056import org.springframework.core.ParameterizedTypeReference;
057import org.springframework.http.MediaType;
058import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
059import org.springframework.http.client.support.BasicAuthenticationInterceptor;
060import org.springframework.util.LinkedMultiValueMap;
061import org.springframework.util.MultiValueMap;
062import org.springframework.web.client.HttpClientErrorException;
063import org.springframework.web.client.RestClient;
064import org.springframework.web.client.RestClientException;
065import tools.jackson.core.JacksonException;
066import tools.jackson.databind.json.JsonMapper;
067
068import java.time.Duration;
069import java.util.Map;
070import java.util.Objects;
071import java.util.Optional;
072import java.util.Set;
073
074import static org.testcontainers.shaded.org.awaitility.Awaitility.await;
075
076// Many new methods generated by Claude Sonnet 3.7
077
078/**
079 * AdminJsonRestClient is a client for the Admin API of the CDR.
080 * It currently supports anonymous and http-basic authentication.
081 */
082public class AdminJsonRestClient implements AutoCloseable {
083        private static final Logger ourLog = LoggerFactory.getLogger(AdminJsonRestClient.class);
084        /**
085         * Converts between models and trees the way the client's message converter reads and writes them, except that
086         * an unknown property fails the conversion.
087         */
088        private static final JsonMapper ourJsonMapper =
089                        JsonMapper.builderWithJackson2Defaults().build();
090
091        private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(90);
092        /**
093         * Package-private and non-final so tests can inject a smaller poll interval to exercise multi-iteration
094         * loop semantics without introducing a public setter on the production API.
095         */
096        static Duration POLL_INTERVAL = Duration.ofMillis(500);
097
098        private static final String TARGET_STATUS = "STARTED";
099        private static final String FAILED_TO_START = "FAILED_TO_START";
100        private static final String FAILED_TO_STOP = "FAILED_TO_STOP";
101        private static final String NOT_PRESENT = "<NOT_PRESENT>";
102        private static final String NO_PROCESSES = "<NO_PROCESSES>";
103        private static final String NEVER_OBSERVED = "<NEVER_OBSERVED>";
104
105        final RestClient myRestClient;
106
107        /**
108         * Package-private hook so tests can deterministically observe and control the poll-loop sleep
109         * (e.g. signal a latch when the worker enters the sleep branch, then perform a real interruptible
110         * {@link Thread#sleep(long)}). Production code uses {@link Thread#sleep(long)} directly.
111         */
112        @FunctionalInterface
113        interface InterruptibleSleeper {
114                void sleep(long theMillis) throws InterruptedException;
115        }
116
117        InterruptibleSleeper mySleeper = Thread::sleep;
118
119        /**
120         * The client this one issues on, and whether closing this client should release it.
121         * {@literal null} for a client built from a {@link RestClient} directly, which brought no
122         * connection pool of its own.
123         */
124        private final HttpClientOwnership myOwnership;
125
126        AdminJsonRestClient(RestClient theRestClient) {
127                this(theRestClient, null);
128        }
129
130        private AdminJsonRestClient(RestClient theRestClient, @Nullable HttpClientOwnership theOwnership) {
131                myOwnership = theOwnership;
132                myRestClient = theRestClient;
133        }
134
135        /**
136         * Opens a client authenticating as the given user, over a connection pool of its own.
137         * <p>
138         * The caller owns the pool: open this in a try-with-resources block, or close it from an
139         * {@code @AfterAll} when it is a field. Use
140         * {@link #issuingOn(SmileTestHttpClient, String, String, String)} instead where a client to
141         * issue on already exists.
142         *
143         * @param theBaseUrl the Admin JSON base URL, including port
144         * @param theUsername the user to authenticate as
145         * @param thePassword that user's password
146         */
147        public static @Nonnull AdminJsonRestClient open(
148                        @Nonnull String theBaseUrl, @Nonnull String theUsername, @Nonnull String thePassword) {
149                HttpClientOwnership ownership = HttpClientOwnership.resolve(null);
150
151                return authenticatedClient(ownership, theBaseUrl, theUsername, thePassword);
152        }
153
154        /**
155         * Opens a client sending no credentials, over a connection pool of its own.
156         * <p>
157         * The caller owns the pool — see {@link #open(String, String, String)}.
158         *
159         * @param theBaseUrl the Admin JSON base URL, including port
160         */
161        public static @Nonnull AdminJsonRestClient openAnonymous(@Nonnull String theBaseUrl) {
162                HttpClientOwnership ownership = HttpClientOwnership.resolve(null);
163
164                return new AdminJsonRestClient(
165                                builderForUrlWithJsonDefault(theBaseUrl, ownership.client()).build(), ownership);
166        }
167
168        /**
169         * Builds a client that issues its requests on {@code theHttpClient}, sharing that client's
170         * connection pool and cookie store with everything else built over it. A harness passes its own
171         * client here so that a session established through this client is visible to the harness's
172         * other clients, and so that {@code clearCookies()} reaches this client too.
173         * <p>
174         * The pool stays the caller's: {@link #close()} leaves it open, so there is nothing here for the
175         * caller to release. Use {@link #open(String, String, String)} to build a pool of your own.
176         *
177         * @param theHttpClient the client to issue on, which the caller keeps ownership of
178         * @param theBaseUrl the Admin JSON base URL, including port
179         * @param theUsername the user to authenticate as
180         * @param thePassword that user's password
181         */
182        public static @Nonnull AdminJsonRestClient issuingOn(
183                        @Nonnull SmileTestHttpClient theHttpClient,
184                        @Nonnull String theBaseUrl,
185                        @Nonnull String theUsername,
186                        @Nonnull String thePassword) {
187                return authenticatedClient(HttpClientOwnership.resolve(theHttpClient), theBaseUrl, theUsername, thePassword);
188        }
189
190        private static @Nonnull AdminJsonRestClient authenticatedClient(
191                        @Nonnull HttpClientOwnership theOwnership,
192                        @Nonnull String theBaseUrl,
193                        @Nonnull String theUsername,
194                        @Nonnull String thePassword) {
195                RestClient restClient = builderForUrlWithJsonDefault(theBaseUrl, theOwnership.client())
196                                .requestInterceptor(new BasicAuthenticationInterceptor(theUsername, thePassword))
197                                .build();
198
199                return new AdminJsonRestClient(restClient, theOwnership);
200        }
201
202        /**
203         * @deprecated Use {@link #open(String, String, String)}, whose name says that the client owns the
204         *    connection pool it returns and that the caller has to close it.
205         */
206        @Deprecated(since = "2026.11.R01", forRemoval = true)
207        public static @Nonnull AdminJsonRestClient build(
208                        @Nonnull String theBaseUrl, @Nonnull String theUsername, @Nonnull String thePassword) {
209                return open(theBaseUrl, theUsername, thePassword);
210        }
211
212        /**
213         * @deprecated Use {@link #openAnonymous(String)}, whose name says that the client owns the
214         *    connection pool it returns and that the caller has to close it.
215         */
216        @Deprecated(since = "2026.11.R01", forRemoval = true)
217        public static @Nonnull AdminJsonRestClient buildAnonymous(@Nonnull String theBaseUrl) {
218                return openAnonymous(theBaseUrl);
219        }
220
221        private static @Nonnull RestClient.Builder builderForUrlWithJsonDefault(
222                        String theBaseUrl, @Nonnull SmileTestHttpClient theHttpClient) {
223                HttpComponentsClientHttpRequestFactory requestFactory = RequestFactoryUtil.wrap(theHttpClient);
224
225                return RestClient.builder()
226                                .baseUrl(theBaseUrl)
227                                .requestFactory(requestFactory)
228                                .configureMessageConverters(ClientMessageConverters::configure)
229                                // This sets the default content type to JSON, but allows the actual request to override it.
230                                .defaultRequest(r -> r.accept(MediaType.APPLICATION_JSON));
231        }
232
233        @Nonnull
234        public UserDetailsJson userCreate(String theNode, String theModuleId, UserDetailsJson userDetails) {
235                Validate.notEmpty(theNode, "Node ID is required");
236                Validate.notEmpty(theModuleId, "Module ID is required");
237                Validate.notNull(userDetails, "User does not have an assigned pid.  Use userCreate() to create users.");
238                UserDetailsJson result = myRestClient
239                                .post()
240                                .uri("user-management/{nodeId}/{moduleId}", theNode, theModuleId)
241                                .body(userDetails)
242                                .retrieve()
243                                .body(UserDetailsJson.class);
244                return Objects.requireNonNull(result);
245        }
246
247        @Nonnull
248        public UserDetailsJson userUpdate(UserDetailsJson theUserDetails) {
249                Validate.notEmpty(theUserDetails.getNodeId(), "Node ID is required");
250                Validate.notEmpty(theUserDetails.getModuleId(), "Module ID is required");
251                Validate.notNull(
252                                theUserDetails.getPid(), "User does not have an assigned pid.  Use userCreate() to create users.");
253                UserDetailsJson result = myRestClient
254                                .put()
255                                .uri(
256                                                "user-management/{nodeId}/{moduleId}/{userId}",
257                                                theUserDetails.getNodeId(),
258                                                theUserDetails.getModuleId(),
259                                                theUserDetails.getPid())
260                                .body(theUserDetails)
261                                .retrieve()
262                                .body(UserDetailsJson.class);
263                return Objects.requireNonNull(result);
264        }
265
266        /**
267         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
268         *    or a model class to bind it to
269         */
270        @Nonnull
271        public <T> T userFindByUsername(
272                        String theNodeId, String theModuleId, String theUsername, @Nonnull Class<T> theResponseType) {
273                Validate.notEmpty(theNodeId, "Node ID is required");
274                Validate.notEmpty(theModuleId, "Module ID is required");
275                Validate.notEmpty(theUsername, "username is required");
276                T result = myRestClient
277                                .get()
278                                .uri("user-management/{nodeId}/{moduleId}?searchTerm={username}", theNodeId, theModuleId, theUsername)
279                                .retrieve()
280                                .body(theResponseType);
281                return Objects.requireNonNull(result);
282        }
283
284        /**
285         * @deprecated Use {@link #userFindByUsername(String, String, String, Class)} with Jackson 3's
286         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
287         */
288        @Deprecated(since = "2026.11.R01", forRemoval = true)
289        @Nonnull
290        public JsonNode userFindByUsername(String theNodeId, String theModuleId, String theUsername) {
291                return userFindByUsername(theNodeId, theModuleId, theUsername, JsonNode.class);
292        }
293
294        /**
295         * Find users by username and return the result as a String that can be used with ObjectMapper
296         *
297         * @param theNodeId   The node ID
298         * @param theModuleId The module ID
299         * @param theUsername The username to search for
300         * @return The JSON string representation of the result
301         */
302        @Nonnull
303        public String userFindByUsernameAsString(String theNodeId, String theModuleId, String theUsername) {
304                return userFindByUsername(theNodeId, theModuleId, theUsername, tools.jackson.databind.JsonNode.class)
305                                .toString();
306        }
307
308        /**
309         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
310         *    or a model class to bind it to
311         */
312        @Nonnull
313        public <T> T userFindAll(String theNodeId, String theModuleId, int thePageSize, @Nonnull Class<T> theResponseType) {
314                Validate.notEmpty(theNodeId, "Node ID is required");
315                Validate.notEmpty(theModuleId, "Module ID is required");
316                T result = myRestClient
317                                .get()
318                                .uri("user-management/{nodeId}/{moduleId}?pageSize={pageSize}", theNodeId, theModuleId, thePageSize)
319                                .retrieve()
320                                .body(theResponseType);
321                return Objects.requireNonNull(result);
322        }
323
324        /**
325         * @deprecated Use {@link #userFindAll(String, String, int, Class)} with Jackson 3's
326         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
327         */
328        @Deprecated(since = "2026.11.R01", forRemoval = true)
329        @Nonnull
330        public JsonNode userFindAll(String theNodeId, String theModuleId, int thePageSize) {
331                return userFindAll(theNodeId, theModuleId, thePageSize, JsonNode.class);
332        }
333
334        /**
335         * Find all users and return the result as a String that can be used with ObjectMapper
336         *
337         * @param theNodeId   The node ID
338         * @param theModuleId The module ID
339         * @param thePageSize The page size
340         * @return The JSON string representation of the result
341         */
342        @Nonnull
343        public String userFindAllAsString(String theNodeId, String theModuleId, int thePageSize) {
344                return userFindAll(theNodeId, theModuleId, thePageSize, tools.jackson.databind.JsonNode.class)
345                                .toString();
346        }
347
348        @Nonnull
349        public UserDetailsJson userFetchByPid(String theNodeId, String theModuleId, Long thePid) {
350                Validate.notEmpty(theNodeId, "Node ID is required");
351                Validate.notEmpty(theModuleId, "Module ID is required");
352                Validate.notNull(thePid, "User does not have an assigned pid.  Use userCreate() to create users.");
353                UserDetailsJson result = myRestClient
354                                .get()
355                                .uri("user-management/{nodeId}/{moduleId}/{userId}", theNodeId, theModuleId, thePid)
356                                .retrieve()
357                                .body(UserDetailsJson.class);
358                return Objects.requireNonNull(result);
359        }
360
361        /**
362         * Get the module configuration for a specific node and module
363         *
364         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
365         *    or a model class to bind it to
366         */
367        @Nonnull
368        public <T> T getModuleConfig(String theNodeId, String theModuleId, @Nonnull Class<T> theResponseType) {
369                Validate.notEmpty(theNodeId, "Node ID is required");
370                Validate.notEmpty(theModuleId, "Module ID is required");
371                T result = myRestClient
372                                .get()
373                                .uri("module-config/{nodeId}/{moduleId}", theNodeId, theModuleId)
374                                .retrieve()
375                                .body(theResponseType);
376                return Objects.requireNonNull(result);
377        }
378
379        /**
380         * @deprecated Use {@link #getModuleConfig(String, String, Class)} with Jackson 3's
381         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
382         */
383        @Deprecated(since = "2026.11.R01", forRemoval = true)
384        @Nonnull
385        public JsonNode getModuleConfig(String theNodeId, String theModuleId) {
386                return getModuleConfig(theNodeId, theModuleId, JsonNode.class);
387        }
388
389        /**
390         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
391         *    or a model class to bind it to
392         */
393        public <T> T getModuleInterceptors(String theNodeId, String theModuleId, @Nonnull Class<T> theResponseType) {
394                Validate.notEmpty(theNodeId, "Node ID is required");
395                Validate.notEmpty(theModuleId, "Module ID is required");
396                T result = myRestClient
397                                .get()
398                                .uri("module-config/{nodeId}/{moduleId}/interceptors", theNodeId, theModuleId)
399                                .retrieve()
400                                .body(theResponseType);
401                return Objects.requireNonNull(result);
402        }
403
404        /**
405         * @deprecated Use {@link #getModuleInterceptors(String, String, Class)} with Jackson 3's
406         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
407         */
408        @Deprecated(since = "2026.11.R01", forRemoval = true)
409        public JsonNode getModuleInterceptors(String theNodeId, String theModuleId) {
410                return getModuleInterceptors(theNodeId, theModuleId, JsonNode.class);
411        }
412
413        /**
414         * Update the configuration for a specific module. When either {@code theRestart} or {@code theReload} is set,
415         * the client blocks until the module reports {@value #TARGET_STATUS} (up to {@link #DEFAULT_TIMEOUT}).
416         * Use {@link #updateModuleConfig(String, String, tools.jackson.databind.JsonNode, boolean, boolean, boolean)} to
417         * opt out of the wait.
418         */
419        @Nonnull
420        public tools.jackson.databind.JsonNode updateModuleConfig(
421                        String theNodeId,
422                        String theModuleId,
423                        tools.jackson.databind.JsonNode theOptions,
424                        boolean theRestart,
425                        boolean theReload) {
426                return updateModuleConfig(theNodeId, theModuleId, theOptions, theRestart, theReload, true, DEFAULT_TIMEOUT);
427        }
428
429        /**
430         * Update the configuration for a specific module.
431         *
432         * @param theShouldWaitForRestart when {@code true} and either {@code theRestart} or {@code theReload} is set,
433         *                                the client polls the admin status endpoint until the module reports
434         *                                {@value #TARGET_STATUS}, up to {@link #DEFAULT_TIMEOUT}.
435         */
436        @Nonnull
437        public tools.jackson.databind.JsonNode updateModuleConfig(
438                        String theNodeId,
439                        String theModuleId,
440                        tools.jackson.databind.JsonNode theOptions,
441                        boolean theRestart,
442                        boolean theReload,
443                        boolean theShouldWaitForRestart) {
444                return updateModuleConfig(
445                                theNodeId, theModuleId, theOptions, theRestart, theReload, theShouldWaitForRestart, DEFAULT_TIMEOUT);
446        }
447
448        /**
449         * Update the configuration for a specific module with a caller-supplied wait timeout.
450         *
451         * @param theShouldWaitForRestart when {@code true} and either {@code theRestart} or {@code theReload} is set,
452         *                                the client polls the admin status endpoint until the module reports
453         *                                {@value #TARGET_STATUS}, up to {@code theWaitTimeout}.
454         * @param theWaitTimeout          the maximum duration to wait for the module to report {@value #TARGET_STATUS}
455         *                                when {@code theShouldWaitForRestart} is {@code true}. Ignored otherwise.
456         */
457        @Nonnull
458        public tools.jackson.databind.JsonNode updateModuleConfig(
459                        String theNodeId,
460                        String theModuleId,
461                        tools.jackson.databind.JsonNode theOptions,
462                        boolean theRestart,
463                        boolean theReload,
464                        boolean theShouldWaitForRestart,
465                        Duration theWaitTimeout) {
466                return putModuleConfig(
467                                theNodeId,
468                                theModuleId,
469                                theOptions,
470                                theRestart,
471                                theReload,
472                                theShouldWaitForRestart,
473                                theWaitTimeout,
474                                tools.jackson.databind.JsonNode.class);
475        }
476
477        /**
478         * @deprecated Use {@link #updateModuleConfig(String, String, tools.jackson.databind.JsonNode, boolean, boolean)}
479         *    with Jackson 3's {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
480         */
481        @Deprecated(since = "2026.11.R01", forRemoval = true)
482        @Nonnull
483        public JsonNode updateModuleConfig(
484                        String theNodeId, String theModuleId, JsonNode theOptions, boolean theRestart, boolean theReload) {
485                return updateModuleConfig(theNodeId, theModuleId, theOptions, theRestart, theReload, true, DEFAULT_TIMEOUT);
486        }
487
488        /**
489         * @deprecated Use
490         *    {@link #updateModuleConfig(String, String, tools.jackson.databind.JsonNode, boolean, boolean, boolean)}
491         *    with Jackson 3's {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
492         */
493        @Deprecated(since = "2026.11.R01", forRemoval = true)
494        @Nonnull
495        public JsonNode updateModuleConfig(
496                        String theNodeId,
497                        String theModuleId,
498                        JsonNode theOptions,
499                        boolean theRestart,
500                        boolean theReload,
501                        boolean theShouldWaitForRestart) {
502                return updateModuleConfig(
503                                theNodeId, theModuleId, theOptions, theRestart, theReload, theShouldWaitForRestart, DEFAULT_TIMEOUT);
504        }
505
506        /**
507         * @deprecated Use
508         *    {@link #updateModuleConfig(String, String, tools.jackson.databind.JsonNode, boolean, boolean, boolean, Duration)}
509         *    with Jackson 3's {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
510         */
511        @Deprecated(since = "2026.11.R01", forRemoval = true)
512        @Nonnull
513        public JsonNode updateModuleConfig(
514                        String theNodeId,
515                        String theModuleId,
516                        JsonNode theOptions,
517                        boolean theRestart,
518                        boolean theReload,
519                        boolean theShouldWaitForRestart,
520                        Duration theWaitTimeout) {
521                return putModuleConfig(
522                                theNodeId,
523                                theModuleId,
524                                theOptions,
525                                theRestart,
526                                theReload,
527                                theShouldWaitForRestart,
528                                theWaitTimeout,
529                                JsonNode.class);
530        }
531
532        @Nonnull
533        private <T> T putModuleConfig(
534                        String theNodeId,
535                        String theModuleId,
536                        Object theOptions,
537                        boolean theRestart,
538                        boolean theReload,
539                        boolean theShouldWaitForRestart,
540                        Duration theWaitTimeout,
541                        Class<T> theResponseType) {
542                Validate.notEmpty(theNodeId, "Node ID is required");
543                Validate.notEmpty(theModuleId, "Module ID is required");
544                Validate.notNull(theOptions, "Options is required");
545
546                T result = myRestClient
547                                .put()
548                                .uri(
549                                                "module-config/{nodeId}/{theModuleId}/set?restart={theRestart}&reload={theReload}",
550                                                theNodeId,
551                                                theModuleId,
552                                                theRestart,
553                                                theReload)
554                                .body(theOptions)
555                                .retrieve()
556                                .body(theResponseType);
557
558                if (theShouldWaitForRestart && (theRestart || theReload)) {
559                        Validate.notNull(theWaitTimeout, "Wait timeout is required");
560                        waitForModuleStarted(theNodeId, theModuleId, theWaitTimeout);
561                }
562
563                return Objects.requireNonNull(result);
564        }
565
566        /**
567         * Request to start a module on all processes
568         */
569        @Nonnull
570        private tools.jackson.databind.JsonNode startModule(String theNodeId, String theModuleId) {
571                Validate.notEmpty(theNodeId, "Node ID is required");
572                Validate.notEmpty(theModuleId, "Module ID is required");
573                tools.jackson.databind.JsonNode result = myRestClient
574                                .post()
575                                .uri("module-config/{nodeId}/{moduleId}/start", theNodeId, theModuleId)
576                                .retrieve()
577                                .body(tools.jackson.databind.JsonNode.class);
578                return Objects.requireNonNull(result);
579        }
580
581        /**
582         * Request to stop a module on all processes
583         * ModuleProcessesStatusChangeResponseJson
584         *
585         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
586         *    or a model class to bind it to
587         */
588        @Nonnull
589        public <T> T stopModule(String theNodeId, String theModuleId, @Nonnull Class<T> theResponseType) {
590                Validate.notEmpty(theNodeId, "Node ID is required");
591                Validate.notEmpty(theModuleId, "Module ID is required");
592                T result = myRestClient
593                                .post()
594                                .uri("module-config/{nodeId}/{moduleId}/stop", theNodeId, theModuleId)
595                                .retrieve()
596                                .body(theResponseType);
597                return Objects.requireNonNull(result);
598        }
599
600        /**
601         * @deprecated Use {@link #stopModule(String, String, Class)} with Jackson 3's
602         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
603         */
604        @Deprecated(since = "2026.11.R01", forRemoval = true)
605        @Nonnull
606        public JsonNode stopModule(String theNodeId, String theModuleId) {
607                return stopModule(theNodeId, theModuleId, JsonNode.class);
608        }
609
610        /**
611         * Request to restart a module on all processes. Blocks until the module reports {@value #TARGET_STATUS}
612         * (up to {@link #DEFAULT_TIMEOUT}). Use {@link #restartModule(String, String, boolean, Class)} to opt out of the wait.
613         *
614         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
615         *    or a model class to bind it to
616         */
617        @Nonnull
618        public <T> T restartModule(String theNodeId, String theModuleId, @Nonnull Class<T> theResponseType) {
619                return restartModule(theNodeId, theModuleId, true, DEFAULT_TIMEOUT, theResponseType);
620        }
621
622        /**
623         * @deprecated Use {@link #restartModule(String, String, Class)} with Jackson 3's
624         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
625         */
626        @Deprecated(since = "2026.11.R01", forRemoval = true)
627        @Nonnull
628        public JsonNode restartModule(String theNodeId, String theModuleId) {
629                return restartModule(theNodeId, theModuleId, JsonNode.class);
630        }
631
632        /**
633         * Request to restart a module on all processes.
634         *
635         * @param theShouldWaitForRestart when {@code true}, the client polls the admin status endpoint
636         *                                until the module reports {@value #TARGET_STATUS},
637         *                                up to {@link #DEFAULT_TIMEOUT}.
638         *
639         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
640         *    or a model class to bind it to
641         */
642        @Nonnull
643        public <T> T restartModule(
644                        String theNodeId, String theModuleId, boolean theShouldWaitForRestart, @Nonnull Class<T> theResponseType) {
645                return restartModule(theNodeId, theModuleId, theShouldWaitForRestart, DEFAULT_TIMEOUT, theResponseType);
646        }
647
648        /**
649         * @deprecated Use {@link #restartModule(String, String, boolean, Class)} with Jackson 3's
650         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
651         */
652        @Deprecated(since = "2026.11.R01", forRemoval = true)
653        @Nonnull
654        public JsonNode restartModule(String theNodeId, String theModuleId, boolean theShouldWaitForRestart) {
655                return restartModule(theNodeId, theModuleId, theShouldWaitForRestart, JsonNode.class);
656        }
657
658        /**
659         * Request to restart a module on all processes with a caller-supplied wait timeout.
660         *
661         * @param theShouldWaitForRestart when {@code true}, the client polls the admin status endpoint
662         *                                until the module reports {@value #TARGET_STATUS},
663         *                                up to {@code theWaitTimeout}.
664         * @param theWaitTimeout          the maximum duration to wait for the module to report {@value #TARGET_STATUS}
665         *                                when {@code theShouldWaitForRestart} is {@code true}. Ignored otherwise.
666         *
667         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
668         *    or a model class to bind it to
669         */
670        @Nonnull
671        public <T> T restartModule(
672                        String theNodeId,
673                        String theModuleId,
674                        boolean theShouldWaitForRestart,
675                        Duration theWaitTimeout,
676                        @Nonnull Class<T> theResponseType) {
677                Validate.notEmpty(theNodeId, "Node ID is required");
678                Validate.notEmpty(theModuleId, "Module ID is required");
679                T result = myRestClient
680                                .post()
681                                .uri("module-config/{nodeId}/{moduleId}/restart", theNodeId, theModuleId)
682                                .retrieve()
683                                .body(theResponseType);
684
685                if (theShouldWaitForRestart) {
686                        Validate.notNull(theWaitTimeout, "Wait timeout is required");
687                        waitForModuleStarted(theNodeId, theModuleId, theWaitTimeout);
688                }
689
690                return Objects.requireNonNull(result);
691        }
692
693        /**
694         * @deprecated Use {@link #restartModule(String, String, boolean, Duration, Class)} with Jackson 3's
695         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
696         */
697        @Deprecated(since = "2026.11.R01", forRemoval = true)
698        @Nonnull
699        public JsonNode restartModule(
700                        String theNodeId, String theModuleId, boolean theShouldWaitForRestart, Duration theWaitTimeout) {
701                return restartModule(theNodeId, theModuleId, theShouldWaitForRestart, theWaitTimeout, JsonNode.class);
702        }
703
704        /**
705         * Package-private overload that accepts a custom timeout. Primarily intended for tests that need to
706         * exercise the timeout branch without waiting 90 seconds.
707         *
708         * Polls {@link #getNodeStatuses(Class)} until the first process of the given module on the given node reports
709         * {@value #TARGET_STATUS}, up to {@code theTimeout}. Throws {@link IllegalStateException} on timeout
710         * or terminal failure ({@value #FAILED_TO_START} / {@value #FAILED_TO_STOP}).
711         */
712        void waitForModuleStarted(String theNodeId, String theModuleId, Duration theTimeout) {
713                Validate.notEmpty(theNodeId, "Node ID is required");
714                Validate.notEmpty(theModuleId, "Module ID is required");
715                Validate.notNull(theTimeout, "Timeout is required");
716
717                long deadlineNanos = System.nanoTime() + theTimeout.toNanos();
718                int completedProbes = 0;
719                String lastObservedStatus = NEVER_OBSERVED;
720                RuntimeException lastException = null;
721                int transientErrorCount = 0;
722
723                while (true) {
724                        ModuleStatusProbe probe = null;
725                        try {
726                                tools.jackson.databind.JsonNode statuses = getNodeStatuses(tools.jackson.databind.JsonNode.class);
727                                probe = extractModuleProcessStatus(statuses, theNodeId, theModuleId);
728                                completedProbes++;
729                        } catch (RestClientException e) {
730                                // Narrow catch: only Spring HTTP-layer transients (RestClientException covers ResourceAccessException,
731                                // HttpServerErrorException, HttpClientErrorException, etc.). Programmer errors like NPE, IAE, ISE
732                                // from extractModuleProcessStatus or elsewhere propagate up immediately so they aren't masked
733                                // by a 90s timeout.
734                                lastException = e;
735                                transientErrorCount++;
736                                ourLog.debug(
737                                                "Transient error while polling node statuses for module '{}' on node '{}' (transient #{}): {}",
738                                                theModuleId,
739                                                theNodeId,
740                                                transientErrorCount,
741                                                e.toString());
742                        }
743
744                        if (probe != null) {
745                                lastObservedStatus = probe.presence();
746                                if (probe.rawStatus() != null) {
747                                        if (TARGET_STATUS.equals(probe.rawStatus())) {
748                                                ourLog.debug(
749                                                                "Module '{}' on node '{}' reported {} after {} completed probe(s)",
750                                                                theModuleId,
751                                                                theNodeId,
752                                                                TARGET_STATUS,
753                                                                completedProbes);
754                                                return;
755                                        }
756                                        if (probe.terminalFailure()) {
757                                                // Throw terminal-failure OUTSIDE the try/catch above so it is never classified as transient.
758                                                throw new IllegalStateException(String.format(
759                                                                "Module '%s' on node '%s' reached terminal failure status '%s' after %d completed probe(s)",
760                                                                theModuleId, theNodeId, probe.rawStatus(), completedProbes));
761                                        }
762                                }
763                        }
764
765                        if (System.nanoTime() >= deadlineNanos) {
766                                String message = String.format(
767                                                "Timed out after %d ms waiting for module '%s' on node '%s' to reach status '%s' (last observed status: %s, poll attempts: %d, transient errors: %d)",
768                                                theTimeout.toMillis(),
769                                                theModuleId,
770                                                theNodeId,
771                                                TARGET_STATUS,
772                                                lastObservedStatus,
773                                                completedProbes,
774                                                transientErrorCount);
775                                if (lastException != null) {
776                                        // Use the FQN so subclasses (e.g. HttpServerErrorException$InternalServerError) still surface
777                                        // the parent class name in the timeout message.
778                                        String causeSummary = lastException.getClass().getName() + ": " + lastException.getMessage();
779                                        throw new IllegalStateException(message + "; last error: " + causeSummary, lastException);
780                                }
781                                throw new IllegalStateException(message);
782                        }
783
784                        try {
785                                mySleeper.sleep(POLL_INTERVAL.toMillis());
786                        } catch (InterruptedException e) {
787                                Thread.currentThread().interrupt();
788                                throw new IllegalStateException(
789                                                "Interrupted while waiting for module '" + theModuleId + "' on node '" + theNodeId
790                                                                + "' to start",
791                                                e);
792                        }
793                }
794        }
795
796        /**
797         * Result of probing the {@code node-statuses/complete} payload for a specific node/module.
798         *
799         * <p>The record stores only {@code rawStatus} and (when {@code rawStatus} is {@code null}) an
800         * {@code absenceLabel} that explains why no status was observed ({@value #NOT_PRESENT} or
801         * {@value #NO_PROCESSES}). The observability-friendly {@link #presence()} label and the
802         * {@link #terminalFailure()} flag are derived from {@code rawStatus} so there is a single source
803         * of truth and no two fields to keep in sync.
804         *
805         * @param rawStatus    the raw {@code processes[0].status} string, or {@code null} when the module row was
806         *                     absent, the processes array was empty, or the status field was missing.
807         * @param absenceLabel when {@code rawStatus} is {@code null}, one of {@value #NOT_PRESENT} or
808         *                     {@value #NO_PROCESSES}. Ignored (and may be {@code null}) when {@code rawStatus}
809         *                     is non-null.
810         */
811        private record ModuleStatusProbe(@Nullable String rawStatus, @Nullable String absenceLabel) {
812                boolean terminalFailure() {
813                        return FAILED_TO_START.equals(rawStatus) || FAILED_TO_STOP.equals(rawStatus);
814                }
815
816                String presence() {
817                        return rawStatus != null ? rawStatus : absenceLabel;
818                }
819        }
820
821        /**
822         * Walk the raw {@code node-statuses/complete} payload to extract the first process status for the given
823         * {@code nodeId} / {@code moduleId}.
824         *
825         * Expected shape: {@code { "nodes": [ { "nodeId": "...", "modules": [ { "moduleId": "...", "processes": [ { "status": "..." } ] } ] } ] } }.
826         */
827        @Nonnull
828        private static ModuleStatusProbe extractModuleProcessStatus(
829                        tools.jackson.databind.JsonNode theStatuses, String theNodeId, String theModuleId) {
830                if (theStatuses == null) {
831                        return new ModuleStatusProbe(null, NOT_PRESENT);
832                }
833                tools.jackson.databind.JsonNode nodes = theStatuses.get("nodes");
834                if (nodes == null || !nodes.isArray()) {
835                        return new ModuleStatusProbe(null, NOT_PRESENT);
836                }
837                for (tools.jackson.databind.JsonNode node : nodes) {
838                        tools.jackson.databind.JsonNode nodeId = node.get("nodeId");
839                        if (nodeId == null || !theNodeId.equals(nodeId.asString())) {
840                                continue;
841                        }
842                        tools.jackson.databind.JsonNode modules = node.get("modules");
843                        if (modules == null || !modules.isArray()) {
844                                continue;
845                        }
846                        for (tools.jackson.databind.JsonNode module : modules) {
847                                tools.jackson.databind.JsonNode moduleId = module.get("moduleId");
848                                if (moduleId == null || !theModuleId.equals(moduleId.asString())) {
849                                        continue;
850                                }
851                                tools.jackson.databind.JsonNode processes = module.get("processes");
852                                if (processes == null || !processes.isArray() || processes.isEmpty()) {
853                                        // Node+module matched, but no processes are reporting yet.
854                                        return new ModuleStatusProbe(null, NO_PROCESSES);
855                                }
856                                tools.jackson.databind.JsonNode status = processes.get(0).get("status");
857                                if (status == null) {
858                                        return new ModuleStatusProbe(null, NO_PROCESSES);
859                                }
860                                return new ModuleStatusProbe(status.asString(), null);
861                        }
862                }
863                return new ModuleStatusProbe(null, NOT_PRESENT);
864        }
865
866        /**
867         * Get a list of restore points for a node
868         *
869         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
870         *    or a model class to bind it to
871         */
872        @Nonnull
873        public <T> T getRestorePoints(
874                        String theNodeId,
875                        @Nullable String theVersion,
876                        @Nullable String theFromDate,
877                        @Nullable String theToDate,
878                        int theOffset,
879                        int theCount,
880                        @Nonnull Class<T> theResponseType) {
881                Validate.notEmpty(theNodeId, "Node ID is required");
882
883                T result = myRestClient
884                                .get()
885                                .uri("module-config/{theNodeId}/restorePoints", builder -> {
886                                        builder.queryParamIfPresent("version", Optional.ofNullable(theVersion));
887                                        builder.queryParamIfPresent("from", Optional.ofNullable(theFromDate));
888                                        builder.queryParamIfPresent("to", Optional.ofNullable(theToDate));
889                                        builder.queryParam("offset", theOffset);
890                                        builder.queryParam("count", theCount);
891                                        return builder.build(theNodeId);
892                                })
893                                .retrieve()
894                                .body(theResponseType);
895
896                return Objects.requireNonNull(result);
897        }
898
899        /**
900         * @deprecated Use {@link #getRestorePoints(String, String, String, String, int, int, Class)} with Jackson 3's
901         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
902         */
903        @Deprecated(since = "2026.11.R01", forRemoval = true)
904        @Nonnull
905        public JsonNode getRestorePoints(
906                        String theNodeId,
907                        @Nullable String theVersion,
908                        @Nullable String theFromDate,
909                        @Nullable String theToDate,
910                        int theOffset,
911                        int theCount) {
912                return getRestorePoints(theNodeId, theVersion, theFromDate, theToDate, theOffset, theCount, JsonNode.class);
913        }
914
915        /**
916         * Get a specific restore point
917         *
918         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
919         *    or a model class to bind it to
920         */
921        @Nonnull
922        public <T> T getRestorePoint(String theNodeId, Long theId, @Nonnull Class<T> theResponseType) {
923                Validate.notEmpty(theNodeId, "Node ID is required");
924                Validate.notNull(theId, "Restore point ID is required");
925                T result = myRestClient
926                                .get()
927                                .uri("module-config/{nodeId}/restorePoints/{id}", theNodeId, theId)
928                                .retrieve()
929                                .body(theResponseType);
930                return Objects.requireNonNull(result);
931        }
932
933        /**
934         * @deprecated Use {@link #getRestorePoint(String, Long, Class)} with Jackson 3's
935         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
936         */
937        @Deprecated(since = "2026.11.R01", forRemoval = true)
938        @Nonnull
939        public JsonNode getRestorePoint(String theNodeId, Long theId) {
940                return getRestorePoint(theNodeId, theId, JsonNode.class);
941        }
942
943        /**
944         * Restore the system to a specific restore point
945         */
946        public void restoreSystem(String theNodeId, Long theRestorePointId) {
947                Validate.notEmpty(theNodeId, "Node ID is required");
948                Validate.notNull(theRestorePointId, "Restore point ID is required");
949                myRestClient
950                                .post()
951                                .uri("module-config/{nodeId}/restorePoints/{id}/restore", theNodeId, theRestorePointId)
952                                .retrieve()
953                                .toBodilessEntity();
954        }
955
956        /**
957         * Get health checks for all modules
958         *
959         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
960         *    or a model class to bind it to
961         */
962        @Nonnull
963        public <T> T getHealthChecks(boolean theOnlyRunning, @Nonnull Class<T> theResponseType) {
964                T result = myRestClient
965                                .get()
966                                .uri("runtime-status/node-statuses/health-checks?onlyRunning={onlyRunning}", theOnlyRunning)
967                                .retrieve()
968                                .body(theResponseType);
969                return Objects.requireNonNull(result);
970        }
971
972        /**
973         * @deprecated Use {@link #getHealthChecks(boolean, Class)} with Jackson 3's
974         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
975         */
976        @Deprecated(since = "2026.11.R01", forRemoval = true)
977        @Nonnull
978        public JsonNode getHealthChecks(boolean theOnlyRunning) {
979                return getHealthChecks(theOnlyRunning, JsonNode.class);
980        }
981
982        /**
983         * Get node statuses
984         *
985         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
986         *    or a model class to bind it to
987         */
988        @Nonnull
989        public <T> T getNodeStatuses(@Nonnull Class<T> theResponseType) {
990                T result = myRestClient
991                                .get()
992                                .uri("runtime-status/node-statuses/complete")
993                                .retrieve()
994                                .body(theResponseType);
995                return Objects.requireNonNull(result);
996        }
997
998        /**
999         * @deprecated Use {@link #getNodeStatuses(Class)} with Jackson 3's
1000         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
1001         */
1002        @Deprecated(since = "2026.11.R01", forRemoval = true)
1003        @Nonnull
1004        public JsonNode getNodeStatuses() {
1005                return getNodeStatuses(JsonNode.class);
1006        }
1007
1008        /**
1009         * Cancel a batch job
1010         */
1011        public void cancelBatchJob(String theModuleId, String theJobId) {
1012                Validate.notEmpty(theModuleId, "Module ID is required");
1013                Validate.notEmpty(theJobId, "Job ID is required");
1014                myRestClient
1015                                .get()
1016                                .uri("batch2-jobs/modules/{moduleId}/jobs/{jobId}/cancel", theModuleId, theJobId)
1017                                .retrieve()
1018                                .toBodilessEntity();
1019        }
1020
1021        /**
1022         * Get all module IDs that support batch jobs
1023         */
1024        @Nonnull
1025        public String[] getAllBatchJobModuleIds() {
1026                String[] result =
1027                                myRestClient.get().uri("batch2-jobs/modules").retrieve().body(String[].class);
1028                return Objects.requireNonNull(result);
1029        }
1030
1031        /**
1032         * Get a specific batch job instance by ID
1033         */
1034        @Nonnull
1035        public Batch2JobInstanceJson getBatchJobInstance(String theModuleId, String theJobId) {
1036                Validate.notEmpty(theModuleId, "Module ID is required");
1037                Validate.notEmpty(theJobId, "Job ID is required");
1038                Batch2JobInstanceJson result = myRestClient
1039                                .get()
1040                                .uri("batch2-jobs/modules/{moduleId}/jobs/{jobId}", theModuleId, theJobId)
1041                                .retrieve()
1042                                .body(Batch2JobInstanceJson.class);
1043                return Objects.requireNonNull(result);
1044        }
1045
1046        @Nonnull
1047        public AllBatch2JobInstancesJson getBatchJobInstances(String theModuleId) {
1048                return getBatchJobInstances(theModuleId, new LinkedMultiValueMap<>());
1049        }
1050
1051        @Nonnull
1052        public AllBatch2JobInstancesJson getBatchJobInstances(
1053                        String theModuleId, @Nonnull MultiValueMap<String, String> theQueryParams) {
1054                Validate.notEmpty(theModuleId, "Module ID is required");
1055
1056                AllBatch2JobInstancesJson result = myRestClient
1057                                .get()
1058                                .uri("batch2-jobs/modules/{moduleId}", builder -> builder.queryParams(theQueryParams)
1059                                                .build(theModuleId))
1060                                .retrieve()
1061                                .body(AllBatch2JobInstancesJson.class);
1062                return Objects.requireNonNull(result);
1063        }
1064
1065        @Nonnull
1066        public Batch2JobInstancesJson getBatchJobInstancesByName(
1067                        String theModuleId, String theJobDefinitionId, @Nullable Boolean theEnded, int theStart, int theCount) {
1068                Validate.notEmpty(theModuleId, "Module ID is required");
1069                Validate.notEmpty(theJobDefinitionId, "Job definition ID is required");
1070
1071                Batch2JobInstancesJson result = myRestClient
1072                                .get()
1073                                .uri("batch2-jobs/modules/{moduleId}/names/{name}/jobs", builder -> {
1074                                        builder.queryParam("start", theStart);
1075                                        builder.queryParam("count", theCount);
1076                                        builder.queryParamIfPresent("ended", Optional.ofNullable(theEnded));
1077                                        return builder.build(theModuleId, theJobDefinitionId);
1078                                })
1079                                .retrieve()
1080                                .body(Batch2JobInstancesJson.class);
1081                return Objects.requireNonNull(result);
1082        }
1083
1084        /**
1085         * Process a bulk ETL import file
1086         * @param theModuleId the id of the etl module to target
1087         * @param theFilename the optional filename as a hint for the import process
1088         * @param theContent the body of the csv file to import
1089         */
1090        @Nonnull
1091        public EtlImportProcessFileResponseJson processBulkImport(
1092                        @Nonnull String theModuleId, @Nullable String theFilename, @Nonnull String theContent) {
1093                return processBulkImport(theModuleId, theFilename, null, theContent);
1094        }
1095
1096        /**
1097         * Process a bulk ETL import file
1098         * @param theModuleId the id of the etl module to target
1099         * @param theFilename the optional filename as a hint for the import process
1100         * @param theUserJobType the optional job type to use for the import process
1101         * @param theContent the body of the csv file to import
1102         */
1103        @Nonnull
1104        public EtlImportProcessFileResponseJson processBulkImport(
1105                        @Nonnull String theModuleId,
1106                        @Nullable String theFilename,
1107                        @Nullable String theUserJobType,
1108                        @Nonnull String theContent) {
1109                Validate.notEmpty(theModuleId, "Module ID is required");
1110                Validate.notNull(theContent, "Content is required");
1111
1112                EtlImportProcessFileResponseJson result = myRestClient
1113                                .post()
1114                                .uri("bulk-import/process-etl-file/{moduleId}", builder -> {
1115                                        builder.queryParamIfPresent("filename", Optional.ofNullable(theFilename));
1116                                        builder.queryParamIfPresent("userJobType", Optional.ofNullable(theUserJobType));
1117                                        return builder.build(Map.of("moduleId", theModuleId));
1118                                })
1119                                .accept(MediaType.APPLICATION_JSON)
1120                                .body(theContent)
1121                                .retrieve()
1122                                .body(EtlImportProcessFileResponseJson.class);
1123                return Objects.requireNonNull(result);
1124        }
1125
1126        /**
1127         * Get transaction logs
1128         */
1129        @Nonnull
1130        public TransactionLogEventsJson getTransactionLogs() {
1131                TransactionLogEventsJson result =
1132                                myRestClient.get().uri("transaction-log").retrieve().body(TransactionLogEventsJson.class);
1133                return Objects.requireNonNull(result);
1134        }
1135
1136        @Nonnull
1137        public TransactionLogEventsJson getTransactionLogs(@Nonnull MultiValueMap<String, String> theQueryParams) {
1138                TransactionLogEventsJson result = myRestClient
1139                                .get()
1140                                .uri("transaction-log", builder -> builder.queryParams(theQueryParams)
1141                                                .build())
1142                                .retrieve()
1143                                .body(TransactionLogEventsJson.class);
1144                return Objects.requireNonNull(result);
1145        }
1146
1147        @Nonnull
1148        public TransactionLogEventCodesJson getTransactionLogEventCodes() {
1149                TransactionLogEventCodesJson result = myRestClient
1150                                .get()
1151                                .uri("transaction-log/event-codes")
1152                                .retrieve()
1153                                .body(TransactionLogEventCodesJson.class);
1154                return Objects.requireNonNull(result);
1155        }
1156
1157        @Nonnull
1158        public AuditEventsJson getAuditEvents() {
1159                return getAuditEvents(new LinkedMultiValueMap<>());
1160        }
1161
1162        @Nonnull
1163        public AuditEventsJson getAuditEvents(@Nonnull MultiValueMap<String, String> theQueryParams) {
1164                AuditEventsJson result = myRestClient
1165                                .get()
1166                                .uri("audit-log", builder -> builder.queryParams(theQueryParams).build())
1167                                .retrieve()
1168                                .body(AuditEventsJson.class);
1169                return Objects.requireNonNull(result);
1170        }
1171
1172        @Nonnull
1173        public MdmAlgorithmsListJson getMdmAlgorithms(String theModuleId) {
1174                Validate.notEmpty(theModuleId, "Module ID is required");
1175
1176                MdmAlgorithmsListJson result = myRestClient
1177                                .get()
1178                                .uri("mdm/{moduleId}/mdm-algorithms", theModuleId)
1179                                .retrieve()
1180                                .body(MdmAlgorithmsListJson.class);
1181                return Objects.requireNonNull(result);
1182        }
1183
1184        @Nonnull
1185        public MdmMetricsJson getMdmMetrics(String theModuleId, String theResourceType) {
1186                Validate.notEmpty(theModuleId, "Module ID is required");
1187                Validate.notEmpty(theResourceType, "Resource type is required");
1188
1189                MdmMetricsJson result = myRestClient
1190                                .get()
1191                                .uri("mdm/{moduleId}/mdm-metrics?resourceType={resourceType}", theModuleId, theResourceType)
1192                                .retrieve()
1193                                .body(MdmMetricsJson.class);
1194                return Objects.requireNonNull(result);
1195        }
1196
1197        @Nonnull
1198        public Set<LoggerConfigJson> getTroubleshootingLoggers() {
1199                Set<LoggerConfigJson> result = myRestClient
1200                                .get()
1201                                .uri("troubleshooting-log/configuration")
1202                                .retrieve()
1203                                .body(new ParameterizedTypeReference<>() {});
1204                return Objects.requireNonNull(result);
1205        }
1206
1207        @Nonnull
1208        public Set<LoggerConfigJson> updateTroubleshootingLoggers(@Nonnull Set<LoggerConfigJson> theLoggers) {
1209                Set<LoggerConfigJson> result = myRestClient
1210                                .post()
1211                                .uri("troubleshooting-log/configuration")
1212                                .contentType(MediaType.APPLICATION_JSON)
1213                                .body(theLoggers)
1214                                .retrieve()
1215                                .body(new ParameterizedTypeReference<>() {});
1216                return Objects.requireNonNull(result);
1217        }
1218
1219        @Nonnull
1220        public LoggerConfigJson updateTroubleshootingLoggerLevel(String theLoggerName, String theLoggerLevel) {
1221                Validate.notEmpty(theLoggerName, "Logger name is required");
1222                Validate.notEmpty(theLoggerLevel, "Logger level is required");
1223
1224                LoggerConfigJson result = myRestClient
1225                                .put()
1226                                .uri(
1227                                                "troubleshooting-log/configuration/{loggerName}?loggerLevel={loggerLevel}",
1228                                                theLoggerName,
1229                                                theLoggerLevel)
1230                                .retrieve()
1231                                .body(LoggerConfigJson.class);
1232                return Objects.requireNonNull(result);
1233        }
1234
1235        /**
1236         * Get a specific transaction log event with its body
1237         */
1238        @Nonnull
1239        public TransactionLogEventsJson.TransactionLogEventJson getTransactionLogEvent(
1240                        Long theEventId, boolean theIncludeBody) {
1241                Validate.notNull(theEventId, "Event ID is required");
1242
1243                TransactionLogEventsJson.TransactionLogEventJson result = myRestClient
1244                                .get()
1245                                .uri("transaction-log/event/{theEventId}?includeBody={includeBody}", theEventId, theIncludeBody)
1246                                .retrieve()
1247                                .body(TransactionLogEventsJson.TransactionLogEventJson.class);
1248                return Objects.requireNonNull(result);
1249        }
1250
1251        /**
1252         * Create an OAuth client for a specific module
1253         */
1254        @Nonnull
1255        public OAuth2ClientDetailsJson createOAuthClient(
1256                        String theNodeId, String theModuleId, OAuth2WritableClientDetailsJson theClientDetails) {
1257                Validate.notEmpty(theNodeId, "Node ID is required");
1258                Validate.notEmpty(theModuleId, "Module ID is required");
1259                Validate.notEmpty(theClientDetails.getClientId(), "Client ID is required");
1260                Validate.notNull(theClientDetails, "Client details are required");
1261
1262                OAuth2ClientDetailsJson result;
1263                try {
1264                        result = myRestClient
1265                                        .post()
1266                                        .uri("openid-connect-clients/{nodeId}/{moduleId}", theNodeId, theModuleId)
1267                                        .body(theClientDetails)
1268                                        .retrieve()
1269                                        .body(OAuth2ClientDetailsJson.class);
1270                } catch (HttpClientErrorException e) {
1271                        ourLog.warn("Failed to create OIDC client, going to try update instead: " + e.toString());
1272                        result = myRestClient
1273                                        .post()
1274                                        .uri(
1275                                                        "openid-connect-clients/{nodeId}/{moduleId}/{clientId}",
1276                                                        theNodeId,
1277                                                        theModuleId,
1278                                                        theClientDetails.getClientId())
1279                                        .body(theClientDetails)
1280                                        .retrieve()
1281                                        .body(OAuth2ClientDetailsJson.class);
1282                }
1283                return Objects.requireNonNull(result);
1284        }
1285
1286        /**
1287         * Update an OAuth client for a specific module
1288         */
1289        @Nonnull
1290        public OAuth2ClientDetailsJson updateOAuthClient(
1291                        String theNodeId,
1292                        String theModuleId,
1293                        String theClientId,
1294                        OAuth2WritableClientDetailsJson theClientDetails) {
1295                Validate.notEmpty(theNodeId, "Node ID is required");
1296                Validate.notEmpty(theModuleId, "Module ID is required");
1297                Validate.notEmpty(theClientId, "Client ID is required");
1298                Validate.notNull(theClientDetails, "Client details are required");
1299
1300                OAuth2ClientDetailsJson result = myRestClient
1301                                .put()
1302                                .uri(
1303                                                "openid-connect-clients/{nodeId}/{moduleId}/{clientId}",
1304                                                Map.of(
1305                                                                "nodeId", theNodeId,
1306                                                                "moduleId", theModuleId,
1307                                                                "clientId", theClientId))
1308                                .body(theClientDetails)
1309                                .retrieve()
1310                                .body(OAuth2ClientDetailsJson.class);
1311                return Objects.requireNonNull(result);
1312        }
1313
1314        /**
1315         * Delete an OAuth client
1316         */
1317        public void deleteOAuthClient(String theNodeId, String theModuleId, String theClientId) {
1318                Validate.notEmpty(theNodeId, "Node ID is required");
1319                Validate.notEmpty(theModuleId, "Module ID is required");
1320                Validate.notEmpty(theClientId, "Client ID is required");
1321
1322                myRestClient
1323                                .delete()
1324                                .uri("openid-connect-clients/{nodeId}/{moduleId}/{clientId}", theNodeId, theModuleId, theClientId)
1325                                .retrieve()
1326                                .toBodilessEntity();
1327        }
1328
1329        @Nonnull
1330        public OAuth2ClientsJson getOAuthClients(
1331                        int thePageIndex, int thePageSize, @Nullable ClientStatusFilterEnum theClientStatus) {
1332                OAuth2ClientsJson result = myRestClient
1333                                .get()
1334                                .uri("openid-connect-clients", builder -> {
1335                                        builder.queryParam("pageIndex", thePageIndex);
1336                                        builder.queryParam("pageSize", thePageSize);
1337                                        builder.queryParamIfPresent("clientStatus", Optional.ofNullable(theClientStatus));
1338                                        return builder.build();
1339                                })
1340                                .retrieve()
1341                                .body(OAuth2ClientsJson.class);
1342                return Objects.requireNonNull(result);
1343        }
1344
1345        /**
1346         * Get an OAuth client
1347         */
1348        @Nonnull
1349        public OAuth2ClientDetailsJson getOAuthClient(String theNodeId, String theModuleId, String theClientId) {
1350                Validate.notEmpty(theNodeId, "Node ID is required");
1351                Validate.notEmpty(theModuleId, "Module ID is required");
1352                Validate.notEmpty(theClientId, "Client ID is required");
1353
1354                OAuth2ClientDetailsJson result = myRestClient
1355                                .get()
1356                                .uri("openid-connect-clients/{nodeId}/{moduleId}/{clientId}", theNodeId, theModuleId, theClientId)
1357                                .retrieve()
1358                                .body(OAuth2ClientDetailsJson.class);
1359                return Objects.requireNonNull(result);
1360        }
1361
1362        /**
1363         * Create an OIDC server for a specific module
1364         */
1365        @Nonnull
1366        public tools.jackson.databind.JsonNode createOidcServer(
1367                        String theNodeId, String theModuleId, tools.jackson.databind.JsonNode theServerDetails) {
1368                return postOidcServer(theNodeId, theModuleId, theServerDetails, tools.jackson.databind.JsonNode.class);
1369        }
1370
1371        /**
1372         * @deprecated Use {@link #createOidcServer(String, String, tools.jackson.databind.JsonNode)} with Jackson 3's
1373         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
1374         */
1375        @Deprecated(since = "2026.11.R01", forRemoval = true)
1376        @Nonnull
1377        public JsonNode createOidcServer(String theNodeId, String theModuleId, JsonNode theServerDetails) {
1378                return postOidcServer(theNodeId, theModuleId, theServerDetails, JsonNode.class);
1379        }
1380
1381        @Nonnull
1382        private <T> T postOidcServer(
1383                        String theNodeId, String theModuleId, Object theServerDetails, Class<T> theResponseType) {
1384                Validate.notEmpty(theNodeId, "Node ID is required");
1385                Validate.notEmpty(theModuleId, "Module ID is required");
1386                Validate.notNull(theServerDetails, "Server details are required");
1387
1388                T result = myRestClient
1389                                .post()
1390                                .uri("openid-connect-servers/{nodeId}/{moduleId}", theNodeId, theModuleId)
1391                                .body(theServerDetails)
1392                                .retrieve()
1393                                .body(theResponseType);
1394                return Objects.requireNonNull(result);
1395        }
1396
1397        @Nonnull
1398        public OAuth2ServerJson createOidcServer(
1399                        String theNodeId, String theModuleId, @Nonnull OAuth2ServerJson theServer) {
1400                Validate.notEmpty(theNodeId, "Node ID is required");
1401                Validate.notEmpty(theModuleId, "Module ID is required");
1402                Validate.notNull(theServer, "Server is required");
1403
1404                OAuth2ServerJson result = myRestClient
1405                                .post()
1406                                .uri("openid-connect-servers/{nodeId}/{moduleId}", theNodeId, theModuleId)
1407                                .contentType(MediaType.APPLICATION_JSON)
1408                                .body(theServer)
1409                                .retrieve()
1410                                .body(OAuth2ServerJson.class);
1411                return Objects.requireNonNull(result);
1412        }
1413
1414        @Nonnull
1415        public OAuth2ServerJson getOidcServer(String theNodeId, String theModuleId, String theIssuerUrl) {
1416                Validate.notEmpty(theNodeId, "Node ID is required");
1417                Validate.notEmpty(theModuleId, "Module ID is required");
1418                Validate.notEmpty(theIssuerUrl, "Issuer URL is required");
1419
1420                OAuth2ServerJson result = myRestClient
1421                                .get()
1422                                .uri(
1423                                                "openid-connect-servers/{nodeId}/{moduleId}?issuer_url={issuerUrl}",
1424                                                theNodeId,
1425                                                theModuleId,
1426                                                theIssuerUrl)
1427                                .retrieve()
1428                                .body(OAuth2ServerJson.class);
1429                return Objects.requireNonNull(result);
1430        }
1431
1432        @Nonnull
1433        public OAuth2ServersJson getOidcServers(
1434                        @Nullable String theNodeId, @Nullable String theModuleId, int thePageIndex, int thePageSize) {
1435                OAuth2ServersJson result = myRestClient
1436                                .get()
1437                                .uri("openid-connect-servers", builder -> {
1438                                        builder.queryParamIfPresent("node_id", Optional.ofNullable(theNodeId));
1439                                        builder.queryParamIfPresent("module_id", Optional.ofNullable(theModuleId));
1440                                        builder.queryParam("pageIndex", thePageIndex);
1441                                        builder.queryParam("pageSize", thePageSize);
1442                                        return builder.build();
1443                                })
1444                                .retrieve()
1445                                .body(OAuth2ServersJson.class);
1446                return Objects.requireNonNull(result);
1447        }
1448
1449        /**
1450         * Update an OIDC server
1451         */
1452        @Nonnull
1453        public tools.jackson.databind.JsonNode updateOidcServer(
1454                        String theNodeId,
1455                        String theModuleId,
1456                        String theServerId,
1457                        tools.jackson.databind.JsonNode theServerDetails) {
1458                return putOidcServer(
1459                                theNodeId, theModuleId, theServerId, theServerDetails, tools.jackson.databind.JsonNode.class);
1460        }
1461
1462        /**
1463         * @deprecated Use {@link #updateOidcServer(String, String, String, tools.jackson.databind.JsonNode)} with
1464         *    Jackson 3's {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
1465         */
1466        @Deprecated(since = "2026.11.R01", forRemoval = true)
1467        @Nonnull
1468        public JsonNode updateOidcServer(
1469                        String theNodeId, String theModuleId, String theServerId, JsonNode theServerDetails) {
1470                return putOidcServer(theNodeId, theModuleId, theServerId, theServerDetails, JsonNode.class);
1471        }
1472
1473        @Nonnull
1474        private <T> T putOidcServer(
1475                        String theNodeId,
1476                        String theModuleId,
1477                        String theServerId,
1478                        Object theServerDetails,
1479                        Class<T> theResponseType) {
1480                Validate.notEmpty(theNodeId, "Node ID is required");
1481                Validate.notEmpty(theModuleId, "Module ID is required");
1482                Validate.notEmpty(theServerId, "Server ID is required");
1483                Validate.notNull(theServerDetails, "Server details are required");
1484
1485                T result = myRestClient
1486                                .put()
1487                                .uri("openid-connect-servers/{nodeId}/{moduleId}/{serverId}", theNodeId, theModuleId, theServerId)
1488                                .body(theServerDetails)
1489                                .retrieve()
1490                                .body(theResponseType);
1491                return Objects.requireNonNull(result);
1492        }
1493
1494        @Nonnull
1495        public OAuth2ServerJson updateOidcServer(
1496                        String theNodeId, String theModuleId, @Nonnull OAuth2ServerJson theServer) {
1497                Validate.notEmpty(theNodeId, "Node ID is required");
1498                Validate.notEmpty(theModuleId, "Module ID is required");
1499                Validate.notNull(theServer, "Server is required");
1500                Validate.notNull(theServer.getPid(), "Server PID is required");
1501
1502                OAuth2ServerJson result = myRestClient
1503                                .put()
1504                                .uri("openid-connect-servers/{nodeId}/{moduleId}/{pid}", theNodeId, theModuleId, theServer.getPid())
1505                                .contentType(MediaType.APPLICATION_JSON)
1506                                .body(theServer)
1507                                .retrieve()
1508                                .body(OAuth2ServerJson.class);
1509                return Objects.requireNonNull(result);
1510        }
1511
1512        @Nonnull
1513        public CdaTemplateJson createCdaTemplate(
1514                        String theModuleId, String theTemplateId, @Nonnull CdaTemplateRequestJson theTemplate) {
1515                return writeCdaTemplate(myRestClient.post(), theModuleId, theTemplateId, theTemplate);
1516        }
1517
1518        @Nonnull
1519        public CdaTemplateJson updateCdaTemplate(
1520                        String theModuleId, String theTemplateId, @Nonnull CdaTemplateRequestJson theTemplate) {
1521                return writeCdaTemplate(myRestClient.put(), theModuleId, theTemplateId, theTemplate);
1522        }
1523
1524        private CdaTemplateJson writeCdaTemplate(
1525                        RestClient.RequestBodyUriSpec theMethod,
1526                        String theModuleId,
1527                        String theTemplateId,
1528                        CdaTemplateRequestJson theTemplate) {
1529                Validate.notEmpty(theModuleId, "Module ID is required");
1530                Validate.notEmpty(theTemplateId, "Template ID is required");
1531                Validate.notNull(theTemplate, "Template is required");
1532
1533                CdaTemplateJson result = theMethod
1534                                .uri("cda/{moduleId}/template/{templateId}", theModuleId, theTemplateId)
1535                                .contentType(MediaType.APPLICATION_JSON)
1536                                .body(theTemplate)
1537                                .retrieve()
1538                                .body(CdaTemplateJson.class);
1539                return Objects.requireNonNull(result);
1540        }
1541
1542        @Nonnull
1543        public CdaTemplateJson updateCdaTemplateScript(String theModuleId, String theTemplateId, String theScript) {
1544                Validate.notEmpty(theModuleId, "Module ID is required");
1545                Validate.notEmpty(theTemplateId, "Template ID is required");
1546                Validate.notNull(theScript, "Script is required");
1547
1548                CdaTemplateJson result = myRestClient
1549                                .put()
1550                                .uri("cda/{moduleId}/template/{templateId}/script", theModuleId, theTemplateId)
1551                                .contentType(MediaType.parseMediaType("application/javascript"))
1552                                .body(theScript)
1553                                .retrieve()
1554                                .body(CdaTemplateJson.class);
1555                return Objects.requireNonNull(result);
1556        }
1557
1558        @Nonnull
1559        public CdaTemplateViewAllResponseJson getCdaTemplates(String theModuleId) {
1560                Validate.notEmpty(theModuleId, "Module ID is required");
1561
1562                CdaTemplateViewAllResponseJson result = myRestClient
1563                                .get()
1564                                .uri("cda/{moduleId}/template", theModuleId)
1565                                .retrieve()
1566                                .body(CdaTemplateViewAllResponseJson.class);
1567                return Objects.requireNonNull(result);
1568        }
1569
1570        @Nonnull
1571        public CdaTemplateResponseJson getCdaTemplate(String theModuleId, String theTemplateId) {
1572                Validate.notEmpty(theModuleId, "Module ID is required");
1573                Validate.notEmpty(theTemplateId, "Template ID is required");
1574
1575                CdaTemplateResponseJson result = myRestClient
1576                                .get()
1577                                .uri("cda/{moduleId}/template/{templateId}", theModuleId, theTemplateId)
1578                                .retrieve()
1579                                .body(CdaTemplateResponseJson.class);
1580                return Objects.requireNonNull(result);
1581        }
1582
1583        public void deleteCdaTemplate(String theModuleId, String theTemplateId) {
1584                Validate.notEmpty(theModuleId, "Module ID is required");
1585                Validate.notEmpty(theTemplateId, "Template ID is required");
1586
1587                myRestClient
1588                                .delete()
1589                                .uri("cda/{moduleId}/template/{templateId}", theModuleId, theTemplateId)
1590                                .retrieve()
1591                                .toBodilessEntity();
1592        }
1593
1594        @Nonnull
1595        public PrivacyNoticeJson getPrivacyNotice() {
1596                PrivacyNoticeJson result =
1597                                myRestClient.get().uri("admin-json/privacy-notice").retrieve().body(PrivacyNoticeJson.class);
1598                return Objects.requireNonNull(result);
1599        }
1600
1601        @Nonnull
1602        public PrivacyNoticeStatusJson getPrivacyNoticeStatus() {
1603                PrivacyNoticeStatusJson result = myRestClient
1604                                .get()
1605                                .uri("admin-json/privacy-notice/status")
1606                                .retrieve()
1607                                .body(PrivacyNoticeStatusJson.class);
1608                return Objects.requireNonNull(result);
1609        }
1610
1611        @Nonnull
1612        public PrivacyNoticeAcceptanceJson acceptPrivacyNotice(String theVersion) {
1613                Validate.notEmpty(theVersion, "Version is required");
1614
1615                PrivacyNoticeAcceptanceJson result = myRestClient
1616                                .post()
1617                                .uri("admin-json/privacy-notice/accept")
1618                                .contentType(MediaType.APPLICATION_JSON)
1619                                .body(new PrivacyNoticeAcceptRequestJson(theVersion))
1620                                .retrieve()
1621                                .body(PrivacyNoticeAcceptanceJson.class);
1622                return Objects.requireNonNull(result);
1623        }
1624
1625        @Nonnull
1626        public OAuth2KeystoresJson getKeystores(int thePageIndex, int thePageSize) {
1627                OAuth2KeystoresJson result = myRestClient
1628                                .get()
1629                                .uri("keystores?pageIndex={pageIndex}&pageSize={pageSize}", thePageIndex, thePageSize)
1630                                .retrieve()
1631                                .body(OAuth2KeystoresJson.class);
1632                return Objects.requireNonNull(result);
1633        }
1634
1635        @Nonnull
1636        public OAuth2KeystoreJson getKeystore(String theKeystoreId) {
1637                Validate.notEmpty(theKeystoreId, "Keystore ID is required");
1638
1639                OAuth2KeystoreJson result = myRestClient
1640                                .get()
1641                                .uri("keystores/{keystoreId}", theKeystoreId)
1642                                .retrieve()
1643                                .body(OAuth2KeystoreJson.class);
1644                return Objects.requireNonNull(result);
1645        }
1646
1647        @Nonnull
1648        public OAuth2KeystoreJson createKeystore(@Nonnull OAuth2KeystoreJson theKeystore) {
1649                Validate.notNull(theKeystore, "Keystore is required");
1650
1651                OAuth2KeystoreJson result = myRestClient
1652                                .post()
1653                                .uri("keystores")
1654                                .contentType(MediaType.APPLICATION_JSON)
1655                                .body(theKeystore)
1656                                .retrieve()
1657                                .body(OAuth2KeystoreJson.class);
1658                return Objects.requireNonNull(result);
1659        }
1660
1661        @Nonnull
1662        public OAuth2KeystoreJson updateKeystore(String theKeystoreId, @Nonnull OAuth2KeystoreJson theKeystore) {
1663                Validate.notEmpty(theKeystoreId, "Keystore ID is required");
1664                Validate.notNull(theKeystore, "Keystore is required");
1665
1666                OAuth2KeystoreJson result = myRestClient
1667                                .put()
1668                                .uri("keystores/{keystoreId}", theKeystoreId)
1669                                .contentType(MediaType.APPLICATION_JSON)
1670                                .body(theKeystore)
1671                                .retrieve()
1672                                .body(OAuth2KeystoreJson.class);
1673                return Objects.requireNonNull(result);
1674        }
1675
1676        public void deleteKeystore(String theKeystoreId) {
1677                Validate.notEmpty(theKeystoreId, "Keystore ID is required");
1678
1679                myRestClient
1680                                .delete()
1681                                .uri("keystores/{keystoreId}", theKeystoreId)
1682                                .retrieve()
1683                                .toBodilessEntity();
1684        }
1685
1686        @Nonnull
1687        public OAuth2RevokeAllWithScopeResponseJson revokeAllTokens(
1688                        @Nullable String theNodeId, @Nullable String theModuleId, @Nullable String theScope) {
1689                OAuth2RevokeAllWithScopeResponseJson result = myRestClient
1690                                .delete()
1691                                .uri("openid-connect-sessions/revoke/all-tokens", builder -> {
1692                                        builder.queryParamIfPresent("node_id", Optional.ofNullable(theNodeId));
1693                                        builder.queryParamIfPresent("module_id", Optional.ofNullable(theModuleId));
1694                                        builder.queryParamIfPresent("scope", Optional.ofNullable(theScope));
1695                                        return builder.build();
1696                                })
1697                                .retrieve()
1698                                .body(OAuth2RevokeAllWithScopeResponseJson.class);
1699                return Objects.requireNonNull(result);
1700        }
1701
1702        /**
1703         * Get MDM links
1704         *
1705         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
1706         *    or a model class to bind it to
1707         */
1708        @Nonnull
1709        public <T> T getMdmLinks(String theModuleId, @Nonnull Class<T> theResponseType) {
1710                Validate.notEmpty(theModuleId, "Module ID is required");
1711
1712                T result = myRestClient
1713                                .get()
1714                                .uri("mdm/{moduleId}/query-links", theModuleId)
1715                                .retrieve()
1716                                .body(theResponseType);
1717                return Objects.requireNonNull(result);
1718        }
1719
1720        /**
1721         * @deprecated Use {@link #getMdmLinks(String, Class)} with Jackson 3's
1722         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
1723         */
1724        @Deprecated(since = "2026.11.R01", forRemoval = true)
1725        @Nonnull
1726        public JsonNode getMdmLinks(String theModuleId) {
1727                return getMdmLinks(theModuleId, JsonNode.class);
1728        }
1729
1730        /**
1731         * Merge MDM golden resources
1732         *
1733         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
1734         *    or a model class to bind it to
1735         */
1736        @Nonnull
1737        public <T> T mergeMdmGoldenResources(String theModuleId, Object theRequest, @Nonnull Class<T> theResponseType) {
1738                Validate.notEmpty(theModuleId, "Module ID is required");
1739                Validate.notNull(theRequest, "Request is required");
1740
1741                T result = myRestClient
1742                                .post()
1743                                .uri("mdm/{moduleId}/merge-golden-resources", theModuleId)
1744                                .body(theRequest)
1745                                .retrieve()
1746                                .body(theResponseType);
1747                return Objects.requireNonNull(result);
1748        }
1749
1750        /**
1751         * @deprecated Use {@link #mergeMdmGoldenResources(String, Object, Class)} with Jackson 3's
1752         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
1753         */
1754        @Deprecated(since = "2026.11.R01", forRemoval = true)
1755        @Nonnull
1756        public JsonNode mergeMdmGoldenResources(String theModuleId, Object theRequest) {
1757                return mergeMdmGoldenResources(theModuleId, theRequest, JsonNode.class);
1758        }
1759
1760        /**
1761         * Update MDM link
1762         *
1763         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
1764         *    or a model class to bind it to
1765         */
1766        @Nonnull
1767        public <T> T updateMdmLink(String theModuleId, Object theRequest, @Nonnull Class<T> theResponseType) {
1768                Validate.notEmpty(theModuleId, "Module ID is required");
1769                Validate.notNull(theRequest, "Request is required");
1770
1771                T result = myRestClient
1772                                .post()
1773                                .uri("mdm/{moduleId}/update-link", theModuleId)
1774                                .body(theRequest)
1775                                .retrieve()
1776                                .body(theResponseType);
1777                return Objects.requireNonNull(result);
1778        }
1779
1780        /**
1781         * @deprecated Use {@link #updateMdmLink(String, Object, Class)} with Jackson 3's
1782         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
1783         */
1784        @Deprecated(since = "2026.11.R01", forRemoval = true)
1785        @Nonnull
1786        public JsonNode updateMdmLink(String theModuleId, Object theRequest) {
1787                return updateMdmLink(theModuleId, theRequest, JsonNode.class);
1788        }
1789
1790        /**
1791         * Get MDM duplicate golden resources
1792         *
1793         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
1794         *    or a model class to bind it to
1795         */
1796        @Nonnull
1797        public <T> T getMdmDuplicateGoldenResources(String theModuleId, @Nonnull Class<T> theResponseType) {
1798                Validate.notEmpty(theModuleId, "Module ID is required");
1799
1800                T result = myRestClient
1801                                .get()
1802                                .uri("mdm/{moduleId}/duplicate-golden-resources", theModuleId)
1803                                .retrieve()
1804                                .body(theResponseType);
1805                return Objects.requireNonNull(result);
1806        }
1807
1808        /**
1809         * @deprecated Use {@link #getMdmDuplicateGoldenResources(String, Class)} with Jackson 3's
1810         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
1811         */
1812        @Deprecated(since = "2026.11.R01", forRemoval = true)
1813        @Nonnull
1814        public JsonNode getMdmDuplicateGoldenResources(String theModuleId) {
1815                return getMdmDuplicateGoldenResources(theModuleId, JsonNode.class);
1816        }
1817
1818        /**
1819         * Submit an MDM operation to perform batch matching on all resources
1820         *
1821         * @param theModuleId   The module ID
1822         * @param theParameters The parameters for the MDM operation
1823         * @return The response as a String
1824         */
1825        @Nonnull
1826        public String submitMdmOperation(String theModuleId, IBaseParameters theParameters) {
1827                Validate.notEmpty(theModuleId, "Module ID is required");
1828
1829                String body = toJsonString(theParameters);
1830
1831                String result = myRestClient
1832                                .post()
1833                                .uri("{moduleId}/mdm-submit", theModuleId)
1834                                .body(body)
1835                                .retrieve()
1836                                .body(String.class);
1837
1838                return result != null ? result : "";
1839        }
1840
1841        public static String toJsonString(IBaseResource theResource) {
1842                FhirVersionEnum version = FhirVersionEnum.determineVersionForType(theResource.getClass());
1843                FhirContext ctx = FhirContext.forCached(version);
1844                return ctx.newJsonParser().encodeResourceToString(theResource);
1845        }
1846
1847        /**
1848         * Exception thrown when a forbidden operation is attempted
1849         */
1850        public static class ForbiddenOperationException extends RuntimeException {
1851                public ForbiddenOperationException(String message, Throwable cause) {
1852                        super(message, cause);
1853                }
1854        }
1855
1856        /**
1857         * Get the node configurations from the admin API.
1858         *
1859         * @return The node configurations
1860         */
1861        @Nonnull
1862        public NodeConfigurations getNodeConfigurations() {
1863                NodeConfigurations result =
1864                                myRestClient.get().uri("/module-config/").retrieve().body(NodeConfigurations.class);
1865                return Objects.requireNonNull(result);
1866        }
1867
1868        /**
1869         * Get the port number for a specific module from the node configurations.
1870         *
1871         * @param theModuleId The ID of the module to get the port for
1872         * @return The port number, or the default FHIR port (8000) if not found
1873         */
1874        public int getPortFromModule(String theModuleId) {
1875                Validate.notEmpty(theModuleId, "Module ID is required");
1876                NodeConfigurations config = getNodeConfigurations();
1877
1878                // Find the first node (assuming there's only one node in the container)
1879                if (config.getNodes().isEmpty()) {
1880                        throw new IllegalStateException("No nodes found in node configuration");
1881                } else {
1882                        NodeConfigurations.NodeConfiguration node = config.getNodes().get(0);
1883
1884                        // Find the module with the given ID
1885                        return node.getModule(theModuleId)
1886                                        .map(module -> {
1887                                                // Look for the port property in the module's configuration
1888                                                for (NodeConfigurations.ModuleConfigProperty property : module.getConfigProperties()) {
1889                                                        if (property.getKey().equals("port")) {
1890                                                                try {
1891                                                                        return Integer.parseInt(property.getValue());
1892                                                                } catch (NumberFormatException e) {
1893                                                                        // If the port is not a valid integer, fail.
1894                                                                        throw new IllegalArgumentException(
1895                                                                                        "Invalid port number: " + property.getValue(), e);
1896                                                                }
1897                                                        }
1898                                                }
1899                                                // If no port property is found, return the default FHIR port
1900                                                return null;
1901                                        })
1902                                        .orElseThrow(() -> new IllegalArgumentException(
1903                                                        "Module with ID " + theModuleId + " not found in node configuration"));
1904                }
1905        }
1906
1907        /**
1908         * Find the module ID of the FHIR endpoint (FHIR REST, hybrid providers, or FHIR gateway) running
1909         * on the given port.
1910         *
1911         * @param thePort The port to look up
1912         * @return The module ID of the FHIR endpoint module running on the given port
1913         * @throws IllegalArgumentException if no FHIR endpoint module is found running on the given port
1914         * @throws IllegalStateException if no nodes are found in the node configuration
1915         */
1916        @Nonnull
1917        public String getFhirEndpointModuleIdFromPort(int thePort) {
1918                final NodeConfigurations config = getNodeConfigurations();
1919                // Find the first node (assuming there's only one node in the container)
1920                if (config.getNodes().isEmpty()) {
1921                        throw new IllegalStateException("No nodes found in node configuration");
1922                } else {
1923                        final NodeConfigurations.NodeConfiguration node = config.getNodes().get(0);
1924                        // Find the module with the given ID
1925                        return node.getModules().stream()
1926                                        .filter(theModuleConfiguration -> theModuleConfiguration.isFhirEndpointModuleType()
1927                                                        && thePort == Integer.parseInt(theModuleConfiguration.getConfigProperty("port")))
1928                                        .findFirst()
1929                                        .map(NodeConfigurations.ModuleConfiguration::getModuleId)
1930                                        .orElseThrow(() -> new IllegalArgumentException(
1931                                                        "Unable to find FHIR Endpoint module running on Port " + thePort));
1932                }
1933        }
1934
1935        /**
1936         * Binds a JSON tree to a model class. Methods that take a response type can bind to the model directly instead.
1937         *
1938         * @param theJsonNode the tree to bind
1939         * @param theModelClass the class to bind it to
1940         * @return the model
1941         * @throws tools.jackson.core.JacksonException if the tree does not match the model
1942         */
1943        public <T> T convertJsonNodeToModel(tools.jackson.databind.JsonNode theJsonNode, Class<T> theModelClass) {
1944                return ourJsonMapper.treeToValue(theJsonNode, theModelClass);
1945        }
1946
1947        /**
1948         * Writes a model as a JSON tree.
1949         *
1950         * @param theModel the model to write
1951         * @param theNodeType the Jackson 3 node type to return, normally {@link tools.jackson.databind.JsonNode}
1952         * @return the tree
1953         */
1954        public <N extends tools.jackson.databind.JsonNode> N convertModelToJsonNode(Object theModel, Class<N> theNodeType) {
1955                return theNodeType.cast(ourJsonMapper.valueToTree(theModel));
1956        }
1957
1958        /**
1959         * Since many  methods currently return JsonNode, if you have a known model you would like to bind to, you can convert a json object to it using this method
1960         *
1961         * @deprecated Use {@link #convertJsonNodeToModel(tools.jackson.databind.JsonNode, Class)} with Jackson 3's
1962         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
1963         */
1964        @Deprecated(since = "2026.11.R01", forRemoval = true)
1965        public <T> T convertJsonNodeToModel(JsonNode jsonNode, Class<T> modelClass) throws JsonProcessingException {
1966                // This is a hack to work around many of our return types being hidden in cdr-api instead of cdr-api-public.
1967                // From Gary: We can't extract them cleanly yet to the fact that they often are relying on enums in clustermgr
1968                // or enums in api that we do not currently want to make public,
1969                // usually via 3 separate levels of nesting (e.g. node configurations -> module config -> ModuleTypeEnum
1970                // TODO: Fix these, and move them to public, updating the method types to our model classes.
1971
1972                try {
1973                        // The models carry Jackson 3 annotations only, so bind with Jackson 3 by way of the JSON text
1974                        return ourJsonMapper.readValue(jsonNode.toString(), modelClass);
1975                } catch (JacksonException e) {
1976                        // Log the error with the actual JSON content for debugging
1977                        ourLog.error(
1978                                        "Failed to convert JsonNode to " + modelClass.getSimpleName() + ". JSON content: "
1979                                                        + jsonNode.toString(),
1980                                        e);
1981                        throw new JsonProcessingException(e.getMessage(), e) {};
1982                }
1983        }
1984
1985        /**
1986         * @deprecated Use {@link #convertModelToJsonNode(Object, Class)} with Jackson 3's
1987         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
1988         */
1989        @Deprecated(since = "2026.11.R01", forRemoval = true)
1990        public <T> JsonNode convertModelToJsonNode(T model) throws JsonProcessingException {
1991                try {
1992                        // The models carry Jackson 3 annotations only, so write with Jackson 3
1993                        // and read the text as a Jackson 2 tree
1994                        return new ObjectMapper().readTree(ourJsonMapper.writeValueAsString(model));
1995                } catch (Exception e) {
1996                        throw new JsonProcessingException("Error converting model to JsonNode") {};
1997                }
1998        }
1999
2000        @Nullable
2001        public TransactionLogEventsJson.TransactionLogEventJson getMostRecentTransactionLogEntry() {
2002                TransactionLogEventsJson events = myRestClient
2003                                .get()
2004                                .uri("/transaction-log/?pageSize=1")
2005                                .retrieve()
2006                                .body(TransactionLogEventsJson.class);
2007                if (events == null || events.getEvents() == null || events.getEvents().isEmpty()) {
2008                        return null;
2009                } else {
2010                        return events.getEvents().get(0);
2011                }
2012        }
2013
2014        @Nullable
2015        public Long getMostRecentTransactionLogEntryId() {
2016                TransactionLogEventsJson.TransactionLogEventJson entry = getMostRecentTransactionLogEntry();
2017                if (entry != null) {
2018                        return entry.getId();
2019                } else {
2020                        return null;
2021                }
2022        }
2023
2024        public void awaitNewTransactionLogEntry(Long theMostRecentTxLogEntryId) {
2025                await().until(this::getMostRecentTransactionLogEntryId, t -> !Objects.equals(theMostRecentTxLogEntryId, t));
2026        }
2027
2028        /**
2029         * Fetch a transaction log entry by ID and return all details (includes the body)
2030         */
2031        public TransactionLogEventsJson.TransactionLogEventJson getTransactionLogEntryById(Long theId) {
2032                return myRestClient
2033                                .get()
2034                                .uri("/transaction-log/clustermgr/event/" + theId + "?includeBody=true")
2035                                .retrieve()
2036                                .body(TransactionLogEventsJson.TransactionLogEventJson.class);
2037        }
2038
2039        /**
2040         * Perform a generic GET request to the specified path and return the response as JsonNode
2041         *
2042         * @param thePath The path to perform the GET request on
2043         * @param theResponseType the type to read the response as: Jackson 3's {@link tools.jackson.databind.JsonNode},
2044         *    or a model class to bind it to
2045         * @return The response, read as {@code theResponseType}
2046         */
2047        @Nonnull
2048        public <T> T get(String thePath, @Nonnull Class<T> theResponseType) {
2049                Validate.notEmpty(thePath, "Path is required");
2050                T result = myRestClient.get().uri(thePath).retrieve().body(theResponseType);
2051                return Objects.requireNonNull(result);
2052        }
2053
2054        /**
2055         * @deprecated Use {@link #get(String, Class)} with Jackson 3's
2056         *    {@link tools.jackson.databind.JsonNode}. Jackson 2 support will be removed in a later release.
2057         */
2058        @Deprecated(since = "2026.11.R01", forRemoval = true)
2059        @Nonnull
2060        public JsonNode get(String thePath) {
2061                return get(thePath, JsonNode.class);
2062        }
2063
2064        /**
2065         * Releases the connection pool this client built for itself. A no-op when the client was built
2066         * over one supplied by a caller, which owns its own pool.
2067         */
2068        @Override
2069        public void close() {
2070                if (myOwnership != null) {
2071                        myOwnership.closeIfOwned();
2072                }
2073        }
2074}