From c1004a2dfebb4ab80c56a308e91216985f4e0898 Mon Sep 17 00:00:00 2001 From: Craig Perkins Date: Wed, 3 Dec 2025 14:39:24 -0500 Subject: [PATCH 1/6] Upgrade com.pinterest from ktlint to ktlint-cli and fix ktlintFormat Signed-off-by: Craig Perkins --- build.gradle | 2 +- .../alerting/AlertingPluginInterface.kt | 84 ++- .../action/AcknowledgeAlertRequest.kt | 8 +- .../action/AcknowledgeAlertResponse.kt | 42 +- .../action/AcknowledgeChainedAlertRequest.kt | 8 +- .../alerting/action/DeleteCommentRequest.kt | 2 +- .../alerting/action/DeleteCommentResponse.kt | 13 +- .../alerting/action/DeleteMonitorRequest.kt | 7 +- .../alerting/action/DeleteMonitorResponse.kt | 13 +- .../alerting/action/DeleteWorkflowRequest.kt | 7 +- .../alerting/action/DeleteWorkflowResponse.kt | 13 +- .../action/DocLevelMonitorFanOutRequest.kt | 25 +- .../action/DocLevelMonitorFanOutResponse.kt | 23 +- .../alerting/action/GetAlertsRequest.kt | 8 +- .../alerting/action/GetAlertsResponse.kt | 12 +- .../alerting/action/GetFindingsRequest.kt | 8 +- .../alerting/action/GetFindingsResponse.kt | 14 +- .../alerting/action/GetMonitorRequest.kt | 8 +- .../alerting/action/GetMonitorResponse.kt | 37 +- .../action/GetWorkflowAlertsRequest.kt | 8 +- .../action/GetWorkflowAlertsResponse.kt | 12 +- .../alerting/action/GetWorkflowRequest.kt | 8 +- .../alerting/action/GetWorkflowResponse.kt | 16 +- .../alerting/action/IndexCommentRequest.kt | 8 +- .../alerting/action/IndexCommentResponse.kt | 13 +- .../alerting/action/IndexMonitorRequest.kt | 13 +- .../alerting/action/IndexMonitorResponse.kt | 13 +- .../alerting/action/IndexWorkflowRequest.kt | 118 ++-- .../alerting/action/IndexWorkflowResponse.kt | 13 +- .../alerting/action/PublishFindingsRequest.kt | 9 +- .../alerting/action/SearchCommentRequest.kt | 9 +- .../alerting/action/SearchMonitorRequest.kt | 9 +- .../action/SubscribeFindingsResponse.kt | 13 +- .../BucketSelectorExtAggregationBuilder.kt | 81 +-- .../BucketSelectorExtAggregator.kt | 20 +- .../BucketSelectorExtFilter.kt | 41 +- .../BucketSelectorIndices.kt | 34 +- .../commons/alerting/alerts/AlertError.kt | 23 +- .../alerting/model/ActionExecutionResult.kt | 35 +- .../alerting/model/AggregationResultBucket.kt | 28 +- .../commons/alerting/model/Alert.kt | 205 ++++--- .../commons/alerting/model/BaseAlert.kt | 111 ++-- .../alerting/model/BucketLevelTrigger.kt | 82 +-- .../model/BucketLevelTriggerRunResult.kt | 21 +- .../alerting/model/ChainedAlertTrigger.kt | 59 +- .../model/ChainedAlertTriggerRunResult.kt | 14 +- .../alerting/model/ChainedMonitorFindings.kt | 29 +- .../alerting/model/ClusterMetricsInput.kt | 99 ++-- .../model/ClusterMetricsTriggerRunResult.kt | 41 +- .../commons/alerting/model/Comment.kt | 89 +-- .../commons/alerting/model/CompositeInput.kt | 42 +- .../alerting/model/CorrelationAlert.kt | 47 +- .../commons/alerting/model/DataSources.kt | 52 +- .../commons/alerting/model/Delegate.kt | 35 +- .../alerting/model/DocLevelMonitorInput.kt | 68 ++- .../commons/alerting/model/DocLevelQuery.kt | 49 +- .../alerting/model/DocumentLevelTrigger.kt | 74 ++- .../model/DocumentLevelTriggerRunResult.kt | 14 +- .../commons/alerting/model/Finding.kt | 61 +- .../commons/alerting/model/FindingDocument.kt | 29 +- .../commons/alerting/model/FindingWithDocs.kt | 27 +- .../alerting/model/IndexExecutionContext.kt | 16 +- .../commons/alerting/model/Input.kt | 46 +- .../commons/alerting/model/Monitor.kt | 236 +++++--- .../commons/alerting/model/MonitorMetadata.kt | 91 +-- .../alerting/model/MonitorRunResult.kt | 94 +-- .../commons/alerting/model/NoOpTrigger.kt | 34 +- .../alerting/model/QueryLevelTrigger.kt | 71 ++- .../model/QueryLevelTriggerRunResult.kt | 14 +- .../commons/alerting/model/Schedule.kt | 131 +++-- .../commons/alerting/model/ScheduledJob.kt | 19 +- .../commons/alerting/model/SearchInput.kt | 39 +- .../commons/alerting/model/Sequence.kt | 27 +- .../commons/alerting/model/Table.kt | 9 +- .../commons/alerting/model/Trigger.kt | 22 +- .../alerting/model/TriggerRunResult.kt | 27 +- .../commons/alerting/model/Workflow.kt | 128 +++-- .../commons/alerting/model/WorkflowInput.kt | 30 +- .../alerting/model/WorkflowMetadata.kt | 37 +- .../alerting/model/WorkflowRunContext.kt | 19 +- .../alerting/model/WorkflowRunResult.kt | 24 +- .../commons/alerting/model/action/Action.kt | 83 +-- .../model/action/ActionExecutionPolicy.kt | 33 +- .../model/action/ActionExecutionScope.kt | 52 +- .../commons/alerting/model/action/Throttle.kt | 20 +- .../monitors/RemoteDocLevelMonitorInput.kt | 32 +- .../remote/monitors/RemoteMonitorInput.kt | 21 +- .../remote/monitors/RemoteMonitorTrigger.kt | 56 +- .../alerting/util/AlertingException.kt | 17 +- .../alerting/util/IndexPatternUtils.kt | 38 +- .../commons/alerting/util/IndexUtils.kt | 42 +- .../NotificationsPluginInterface.kt | 40 +- .../notifications/action/BaseResponse.kt | 9 +- .../action/CreateNotificationConfigRequest.kt | 33 +- .../CreateNotificationConfigResponse.kt | 15 +- .../action/DeleteNotificationConfigRequest.kt | 19 +- .../DeleteNotificationConfigResponse.kt | 20 +- .../action/GetChannelListRequest.kt | 24 +- .../action/GetChannelListResponse.kt | 12 +- .../action/GetNotificationConfigRequest.kt | 47 +- .../action/GetNotificationConfigResponse.kt | 13 +- .../action/GetPluginFeaturesRequest.kt | 24 +- .../action/GetPluginFeaturesResponse.kt | 23 +- .../LegacyPublishNotificationRequest.kt | 17 +- .../LegacyPublishNotificationResponse.kt | 6 +- .../action/SendNotificationRequest.kt | 36 +- .../action/SendNotificationResponse.kt | 12 +- .../action/UpdateNotificationConfigRequest.kt | 29 +- .../UpdateNotificationConfigResponse.kt | 15 +- .../commons/notifications/model/Attachment.kt | 35 +- .../commons/notifications/model/BaseModel.kt | 4 +- .../commons/notifications/model/Channel.kt | 42 +- .../notifications/model/ChannelList.kt | 11 +- .../notifications/model/ChannelMessage.kt | 32 +- .../commons/notifications/model/Chime.kt | 20 +- .../commons/notifications/model/ConfigType.kt | 50 +- .../notifications/model/DeliveryStatus.kt | 27 +- .../commons/notifications/model/Email.kt | 30 +- .../commons/notifications/model/EmailGroup.kt | 20 +- .../notifications/model/EmailRecipient.kt | 20 +- .../model/EmailRecipientStatus.kt | 25 +- .../notifications/model/EventSource.kt | 37 +- .../notifications/model/EventStatus.kt | 77 ++- .../notifications/model/HttpMethodType.kt | 22 +- .../commons/notifications/model/MethodType.kt | 22 +- .../notifications/model/MicrosoftTeams.kt | 20 +- .../notifications/model/NotificationConfig.kt | 37 +- .../model/NotificationConfigInfo.kt | 37 +- .../model/NotificationConfigSearchResult.kt | 11 +- .../notifications/model/NotificationEvent.kt | 32 +- .../notifications/model/SearchResults.kt | 47 +- .../commons/notifications/model/SesAccount.kt | 33 +- .../notifications/model/SeverityType.kt | 26 +- .../commons/notifications/model/Slack.kt | 20 +- .../notifications/model/SmtpAccount.kt | 38 +- .../commons/notifications/model/Sns.kt | 27 +- .../commons/notifications/model/Webhook.kt | 30 +- .../model/config/ConfigDataProperties.kt | 45 +- .../replication/ReplicationPluginInterface.kt | 134 +++-- .../replication/action/ReplicationActions.kt | 59 +- .../action/StopIndexReplicationRequest.kt | 143 ++--- .../opensearch/commons/utils/EnumHelpers.kt | 10 +- .../org/opensearch/commons/utils/Helpers.kt | 4 +- .../commons/utils/SecureClientWrapper.kt | 275 +++++++-- .../commons/utils/TransportHelpers.kt | 25 +- .../commons/utils/ValidationHelpers.kt | 27 +- .../commons/utils/XContentHelpers.kt | 16 +- .../opensearch/commons/alerting/AlertTests.kt | 19 +- .../alerting/AlertingPluginInterfaceTests.kt | 203 ++++--- .../commons/alerting/CorrelationAlertTests.kt | 15 +- .../commons/alerting/TestHelpers.kt | 481 +++++++++------- .../action/AcknowledgeAlertRequestTests.kt | 1 - .../action/AcknowledgeAlertResponseTests.kt | 115 ++-- .../AcknowledgeChainedAlertRequestTests.kt | 1 - .../action/DeleteMonitorRequestTests.kt | 1 - .../action/DeleteWorkflowRequestTests.kt | 1 - .../action/DeleteWorkflowResponseTests.kt | 1 - .../DocLevelMonitorFanOutRequestTests.kt | 185 +++--- .../DocLevelMonitorFanOutResponseTests.kt | 35 +- .../alerting/action/GetAlertsRequestTests.kt | 22 +- .../alerting/action/GetAlertsResponseTests.kt | 110 ++-- .../action/GetFindingsRequestTests.kt | 1 - .../action/GetFindingsResponseTests.kt | 43 +- .../alerting/action/GetMonitorRequestTests.kt | 5 +- .../action/GetMonitorResponseTests.kt | 35 +- .../action/GetWorkflowAlertsRequestTests.kt | 68 +-- .../action/GetWorkflowAlertsResponseTests.kt | 48 +- .../action/GetWorkflowRequestTests.kt | 1 - .../action/GetWorkflowResponseTests.kt | 72 +-- .../action/IndexCommentResponseTests.kt | 19 +- .../action/IndexMonitorRequestTests.kt | 238 ++++---- .../action/IndexMonitorResponseTests.kt | 32 +- .../action/IndexWorkflowRequestTests.kt | 313 +++++----- .../action/IndexWorkflowResponseTests.kt | 61 +- .../action/PublishFindingsRequestTests.kt | 1 - .../action/SearchCommentRequestTests.kt | 2 + .../action/SearchMonitorRequestTests.kt | 3 +- .../alerting/alerts/AlertErrorTests.kt | 17 +- .../BucketSelectorExtAggregatorTests.kt | 226 ++++---- .../alerting/model/BucketLevelTriggerTests.kt | 9 +- .../model/ClusterMetricsInputTests.kt | 84 +-- .../alerting/model/CompositeInputTests.kt | 17 +- .../alerting/model/DataSourcesTests.kt | 21 +- .../model/DocLevelMonitorInputTests.kt | 22 +- .../model/DocumentLevelTriggerTests.kt | 7 +- .../commons/alerting/model/FindingTests.kt | 8 +- .../alerting/model/MockScheduledJob.kt | 12 +- .../commons/alerting/model/MonitorsTests.kt | 11 +- .../alerting/model/QueryLevelTriggerTests.kt | 7 +- .../commons/alerting/model/ScheduleTest.kt | 20 +- .../alerting/model/SearchInputTests.kt | 5 +- .../commons/alerting/model/WriteableTests.kt | 99 ++-- .../alerting/model/XContentTestBase.kt | 11 +- .../commons/alerting/model/XContentTests.kt | 147 ++--- .../alerting/model/action/ActionTests.kt | 9 +- .../NotificationsPluginInterfaceTests.kt | 103 ++-- .../CreateNotificationConfigRequestTests.kt | 536 ++++++++++-------- .../CreateNotificationConfigResponseTests.kt | 18 +- .../DeleteNotificationConfigRequestTests.kt | 40 +- .../DeleteNotificationConfigResponseTests.kt | 35 +- .../action/GetChannelListRequestTests.kt | 18 +- .../action/GetChannelListResponseTests.kt | 312 +++++----- .../GetNotificationConfigRequestTests.kt | 251 ++++---- .../GetNotificationConfigResponseTests.kt | 404 ++++++------- .../action/GetPluginFeaturesRequestTests.kt | 18 +- .../action/GetPluginFeaturesResponseTests.kt | 103 ++-- .../LegacyPublishNotificationRequestTests.kt | 10 +- .../LegacyPublishNotificationResponseTests.kt | 8 +- .../action/SendNotificationRequestTests.kt | 315 +++++----- .../action/SendNotificationResponseTests.kt | 42 +- .../UpdateNotificationConfigRequestTests.kt | 371 ++++++------ .../UpdateNotificationConfigResponseTests.kt | 18 +- .../notifications/model/AttachmentTests.kt | 136 ++--- .../notifications/model/ChannelListTests.kt | 319 ++++++----- .../model/ChannelMessageTests.kt | 239 ++++---- .../notifications/model/ChannelTests.kt | 258 +++++---- .../commons/notifications/model/ChimeTests.kt | 1 - .../notifications/model/ConfigTypeTests.kt | 1 - .../model/DeliveryStatusTests.kt | 42 +- .../notifications/model/EmailGroupTests.kt | 60 +- .../model/EmailRecipientStatusTests.kt | 48 +- .../model/EmailRecipientTests.kt | 16 +- .../commons/notifications/model/EmailTests.kt | 89 +-- .../notifications/model/EventSourceTests.kt | 95 ++-- .../notifications/model/EventStatusTests.kt | 110 ++-- .../model/FilterConfigListTests.kt | 312 +++++----- .../notifications/model/FilterConfigTests.kt | 129 +++-- .../notifications/model/MethodTypeTests.kt | 1 - .../model/MicrosoftTeamsTests.kt | 1 - .../model/NotificationConfigInfoTests.kt | 229 ++++---- .../NotificationConfigSearchResultsTests.kt | 421 +++++++------- .../model/NotificationConfigTests.kt | 263 +++++---- .../model/NotificationEventTests.kt | 238 ++++---- .../notifications/model/SesAccountTests.kt | 136 ++--- .../notifications/model/SeverityTypeTests.kt | 1 - .../commons/notifications/model/SlackTests.kt | 1 - .../notifications/model/SmtpAccountTests.kt | 69 +-- .../commons/notifications/model/SnsTests.kt | 3 +- .../notifications/model/WebhookTests.kt | 28 +- .../ReplicationPluginInterfaceTests.kt | 129 +++-- .../opensearch/commons/utils/TestHelpers.kt | 8 +- 241 files changed, 8060 insertions(+), 6367 deletions(-) diff --git a/build.gradle b/build.gradle index 65ed6109..74e49a92 100644 --- a/build.gradle +++ b/build.gradle @@ -99,7 +99,7 @@ dependencies { testImplementation "commons-validator:commons-validator:1.7" testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.11.4' - ktlint "com.pinterest:ktlint:0.47.1" + ktlint "com.pinterest.ktlint:ktlint-cli:1.8.0" } test { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/AlertingPluginInterface.kt b/src/main/kotlin/org/opensearch/commons/alerting/AlertingPluginInterface.kt index 3ed49ff1..a4484438 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/AlertingPluginInterface.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/AlertingPluginInterface.kt @@ -42,7 +42,6 @@ import org.opensearch.transport.client.node.NodeClient * All the transport action plugin interfaces for the Alerting plugin */ object AlertingPluginInterface { - /** * Index monitor interface. * @param client Node client for making transport action @@ -54,7 +53,7 @@ object AlertingPluginInterface { client: NodeClient, request: IndexMonitorRequest, namedWriteableRegistry: NamedWriteableRegistry, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.INDEX_MONITOR_ACTION_TYPE, @@ -62,17 +61,17 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response, namedWriteableRegistry) { IndexMonitorResponse( - it + it, ) } - } + }, ) } fun deleteMonitor( client: NodeClient, request: DeleteMonitorRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.DELETE_MONITOR_ACTION_TYPE, @@ -80,10 +79,10 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { DeleteMonitorResponse( - it + it, ) } - } + }, ) } @@ -97,7 +96,7 @@ object AlertingPluginInterface { fun indexWorkflow( client: NodeClient, request: IndexWorkflowRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.INDEX_WORKFLOW_ACTION_TYPE, @@ -105,17 +104,17 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { IndexWorkflowResponse( - it + it, ) } - } + }, ) } fun deleteWorkflow( client: NodeClient, request: DeleteWorkflowRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.DELETE_WORKFLOW_ACTION_TYPE, @@ -123,10 +122,10 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { DeleteWorkflowResponse( - it + it, ) } - } + }, ) } @@ -139,7 +138,7 @@ object AlertingPluginInterface { fun getAlerts( client: NodeClient, request: GetAlertsRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.GET_ALERTS_ACTION_TYPE, @@ -147,10 +146,10 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { GetAlertsResponse( - it + it, ) } - } + }, ) } @@ -163,7 +162,7 @@ object AlertingPluginInterface { fun getWorkflowAlerts( client: NodeClient, request: GetWorkflowAlertsRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.GET_WORKFLOW_ALERTS_ACTION_TYPE, @@ -171,10 +170,10 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { GetWorkflowAlertsResponse( - it + it, ) } - } + }, ) } @@ -187,7 +186,7 @@ object AlertingPluginInterface { fun getWorkflow( client: NodeClient, request: GetWorkflowRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.GET_WORKFLOW_ACTION_TYPE, @@ -195,10 +194,10 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { GetWorkflowResponse( - it + it, ) } - } + }, ) } @@ -211,7 +210,7 @@ object AlertingPluginInterface { fun getFindings( client: NodeClient, request: GetFindingsRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.GET_FINDINGS_ACTION_TYPE, @@ -219,10 +218,10 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { GetFindingsResponse( - it + it, ) } - } + }, ) } @@ -235,7 +234,7 @@ object AlertingPluginInterface { fun acknowledgeAlerts( client: NodeClient, request: AcknowledgeAlertRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.ACKNOWLEDGE_ALERTS_ACTION_TYPE, @@ -243,17 +242,17 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { AcknowledgeAlertResponse( - it + it, ) } - } + }, ) } fun publishFinding( client: NodeClient, request: PublishFindingsRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.SUBSCRIBE_FINDINGS_ACTION_TYPE, @@ -261,10 +260,10 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { SubscribeFindingsResponse( - it + it, ) } - } + }, ) } @@ -277,7 +276,7 @@ object AlertingPluginInterface { fun acknowledgeChainedAlerts( client: NodeClient, request: AcknowledgeChainedAlertRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.ACKNOWLEDGE_CHAINED_ALERTS_ACTION_TYPE, @@ -285,10 +284,10 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { AcknowledgeAlertResponse( - it + it, ) } - } + }, ) } @@ -301,7 +300,7 @@ object AlertingPluginInterface { fun getMonitor( client: NodeClient, request: GetMonitorRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.GET_MONITOR_ACTION_TYPE, @@ -309,10 +308,10 @@ object AlertingPluginInterface { wrapActionListener(listener) { response -> recreateObject(response) { GetMonitorResponse( - it + it, ) } - } + }, ) } @@ -325,7 +324,7 @@ object AlertingPluginInterface { fun searchMonitors( client: NodeClient, request: SearchMonitorRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( AlertingActions.SEARCH_MONITORS_ACTION_TYPE, @@ -333,16 +332,16 @@ object AlertingPluginInterface { // we do not use the wrapActionListener in this case since there is no need // to recreate any object or specially handle onResponse / onFailure. It is // simply returning a SearchResponse. - listener + listener, ) } @Suppress("UNCHECKED_CAST") private fun wrapActionListener( listener: ActionListener, - recreate: (Writeable) -> Response - ): ActionListener { - return object : ActionListener { + recreate: (Writeable) -> Response, + ): ActionListener = + object : ActionListener { override fun onResponse(response: ActionResponse) { val recreated = response as? Response ?: recreate(response) listener.onResponse(recreated) @@ -352,5 +351,4 @@ object AlertingPluginInterface { listener.onFailure(exception) } } as ActionListener - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertRequest.kt index 01f3fdd2..6952b79e 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertRequest.kt @@ -21,7 +21,7 @@ class AcknowledgeAlertRequest : ActionRequest { constructor( monitorId: String, alertIds: List, - refreshPolicy: WriteRequest.RefreshPolicy + refreshPolicy: WriteRequest.RefreshPolicy, ) : super() { this.monitorId = monitorId this.alertIds = alertIds @@ -32,12 +32,10 @@ class AcknowledgeAlertRequest : ActionRequest { constructor(sin: StreamInput) : this( sin.readString(), // monitorId Collections.unmodifiableList(sin.readStringList()), // alertIds - WriteRequest.RefreshPolicy.readFrom(sin) // refreshPolicy + WriteRequest.RefreshPolicy.readFrom(sin), // refreshPolicy ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponse.kt index 38d81778..996428a4 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponse.kt @@ -14,7 +14,6 @@ import java.io.IOException import java.util.Collections class AcknowledgeAlertResponse : BaseResponse { - val acknowledged: List val failed: List val missing: List @@ -22,7 +21,7 @@ class AcknowledgeAlertResponse : BaseResponse { constructor( acknowledged: List, failed: List, - missing: List + missing: List, ) : super() { this.acknowledged = acknowledged this.failed = failed @@ -33,7 +32,7 @@ class AcknowledgeAlertResponse : BaseResponse { constructor(sin: StreamInput) : this( Collections.unmodifiableList(sin.readList(::Alert)), // acknowledged Collections.unmodifiableList(sin.readList(::Alert)), // failed - Collections.unmodifiableList(sin.readStringList()) // missing + Collections.unmodifiableList(sin.readStringList()), // missing ) @Throws(IOException::class) @@ -44,7 +43,10 @@ class AcknowledgeAlertResponse : BaseResponse { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { builder.startObject().startArray("success") acknowledged.forEach { builder.value(it.id) } builder.endArray().startArray("failed") @@ -53,22 +55,32 @@ class AcknowledgeAlertResponse : BaseResponse { return builder.endArray().endObject() } - private fun buildFailedAlertAcknowledgeObject(builder: XContentBuilder, failedAlert: Alert) { - builder.startObject() + private fun buildFailedAlertAcknowledgeObject( + builder: XContentBuilder, + failedAlert: Alert, + ) { + builder + .startObject() .startObject(failedAlert.id) - val reason = when (failedAlert.state) { - Alert.State.ERROR -> "Alert is in an error state and can not be acknowledged." - Alert.State.COMPLETED -> "Alert has already completed and can not be acknowledged." - Alert.State.ACKNOWLEDGED -> "Alert has already been acknowledged." - else -> "Alert state unknown and can not be acknowledged" - } - builder.field("failed_reason", reason) + val reason = + when (failedAlert.state) { + Alert.State.ERROR -> "Alert is in an error state and can not be acknowledged." + Alert.State.COMPLETED -> "Alert has already completed and can not be acknowledged." + Alert.State.ACKNOWLEDGED -> "Alert has already been acknowledged." + else -> "Alert state unknown and can not be acknowledged" + } + builder + .field("failed_reason", reason) .endObject() .endObject() } - private fun buildMissingAlertAcknowledgeObject(builder: XContentBuilder, alertID: String) { - builder.startObject() + private fun buildMissingAlertAcknowledgeObject( + builder: XContentBuilder, + alertID: String, + ) { + builder + .startObject() .startObject(alertID) .field("failed_reason", "Alert: $alertID does not exist (it may have already completed).") .endObject() diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeChainedAlertRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeChainedAlertRequest.kt index 81d1fef6..6643a761 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeChainedAlertRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeChainedAlertRequest.kt @@ -19,7 +19,7 @@ class AcknowledgeChainedAlertRequest : ActionRequest { constructor( workflowId: String, - alertIds: List + alertIds: List, ) : super() { this.workflowId = workflowId this.alertIds = alertIds @@ -28,12 +28,10 @@ class AcknowledgeChainedAlertRequest : ActionRequest { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // workflowId - Collections.unmodifiableList(sin.readStringList()) // alertIds + Collections.unmodifiableList(sin.readStringList()), // alertIds ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteCommentRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteCommentRequest.kt index 811dcd9e..2855c750 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteCommentRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteCommentRequest.kt @@ -15,7 +15,7 @@ class DeleteCommentRequest : ActionRequest { @Throws(IOException::class) constructor(sin: StreamInput) : this( - commentId = sin.readString() + commentId = sin.readString(), ) override fun validate(): ActionRequestValidationException? { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteCommentResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteCommentResponse.kt index f00fe266..5681d0f1 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteCommentResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteCommentResponse.kt @@ -11,22 +11,25 @@ class DeleteCommentResponse : BaseResponse { var commentId: String constructor( - id: String + id: String, ) : super() { this.commentId = id } constructor(sin: StreamInput) : this( - sin.readString() // commentId + sin.readString(), // commentId ) override fun writeTo(out: StreamOutput) { out.writeString(commentId) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(IndexUtils._ID, commentId) .endObject() - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorRequest.kt index b0bd9992..910f0483 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorRequest.kt @@ -8,7 +8,6 @@ import org.opensearch.core.common.io.stream.StreamOutput import java.io.IOException class DeleteMonitorRequest : ActionRequest { - val monitorId: String val refreshPolicy: WriteRequest.RefreshPolicy @@ -20,12 +19,10 @@ class DeleteMonitorRequest : ActionRequest { @Throws(IOException::class) constructor(sin: StreamInput) : this( monitorId = sin.readString(), - refreshPolicy = WriteRequest.RefreshPolicy.readFrom(sin) + refreshPolicy = WriteRequest.RefreshPolicy.readFrom(sin), ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorResponse.kt index 90ac17ba..8f83f272 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorResponse.kt @@ -13,7 +13,7 @@ class DeleteMonitorResponse : BaseResponse { constructor( id: String, - version: Long + version: Long, ) : super() { this.id = id this.version = version @@ -21,7 +21,7 @@ class DeleteMonitorResponse : BaseResponse { constructor(sin: StreamInput) : this( sin.readString(), // id - sin.readLong() // version + sin.readLong(), // version ) override fun writeTo(out: StreamOutput) { @@ -29,10 +29,13 @@ class DeleteMonitorResponse : BaseResponse { out.writeLong(version) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(IndexUtils._ID, id) .field(IndexUtils._VERSION, version) .endObject() - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequest.kt index a3907e83..a904ed25 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequest.kt @@ -7,7 +7,6 @@ import org.opensearch.core.common.io.stream.StreamOutput import java.io.IOException class DeleteWorkflowRequest : ActionRequest { - val workflowId: String /** @@ -24,12 +23,10 @@ class DeleteWorkflowRequest : ActionRequest { @Throws(IOException::class) constructor(sin: StreamInput) : this( workflowId = sin.readString(), - deleteDelegateMonitors = sin.readOptionalBoolean() + deleteDelegateMonitors = sin.readOptionalBoolean(), ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowResponse.kt index 3ccb9f41..1a1278c9 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowResponse.kt @@ -15,7 +15,7 @@ class DeleteWorkflowResponse : BaseResponse { constructor( id: String, version: Long, - nonDeletedMonitors: List? = null + nonDeletedMonitors: List? = null, ) : super() { this.id = id this.version = version @@ -25,7 +25,7 @@ class DeleteWorkflowResponse : BaseResponse { constructor(sin: StreamInput) : this( sin.readString(), // id sin.readLong(), // version - sin.readOptionalStringList() + sin.readOptionalStringList(), ) override fun writeTo(out: StreamOutput) { @@ -34,13 +34,16 @@ class DeleteWorkflowResponse : BaseResponse { out.writeOptionalStringCollection(nonDeletedMonitors) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(IndexUtils._ID, id) .field(IndexUtils._VERSION, version) .field(NON_DELETED_MONITORS, nonDeletedMonitors) .endObject() - } companion object { const val NON_DELETED_MONITORS = "NON_DELETED_MONITORS" diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutRequest.kt index fe5cfe29..7ee5ba5f 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutRequest.kt @@ -19,7 +19,9 @@ import org.opensearch.core.xcontent.ToXContentObject import org.opensearch.core.xcontent.XContentBuilder import java.io.IOException -class DocLevelMonitorFanOutRequest : ActionRequest, ToXContentObject { +class DocLevelMonitorFanOutRequest : + ActionRequest, + ToXContentObject { val monitor: Monitor val dryRun: Boolean val monitorMetadata: MonitorMetadata @@ -37,7 +39,7 @@ class DocLevelMonitorFanOutRequest : ActionRequest, ToXContentObject { indexExecutionContext: IndexExecutionContext?, shardIds: List, concreteIndicesSeenSoFar: List, - workflowRunContext: WorkflowRunContext? + workflowRunContext: WorkflowRunContext?, ) : super() { this.monitor = monitor this.dryRun = dryRun @@ -58,10 +60,13 @@ class DocLevelMonitorFanOutRequest : ActionRequest, ToXContentObject { executionId = sin.readString(), shardIds = sin.readList(::ShardId), concreteIndicesSeenSoFar = sin.readStringList(), - workflowRunContext = if (sin.readBoolean()) { - WorkflowRunContext(sin) - } else { null }, - indexExecutionContext = IndexExecutionContext(sin) + workflowRunContext = + if (sin.readBoolean()) { + WorkflowRunContext(sin) + } else { + null + }, + indexExecutionContext = IndexExecutionContext(sin), ) @Throws(IOException::class) @@ -87,8 +92,12 @@ class DocLevelMonitorFanOutRequest : ActionRequest, ToXContentObject { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field("monitor", monitor) .field("dry_run", dryRun) .field("execution_id", executionId) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutResponse.kt index 6e5cde55..0b51069a 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutResponse.kt @@ -16,7 +16,9 @@ import org.opensearch.core.xcontent.ToXContentObject import org.opensearch.core.xcontent.XContentBuilder import java.io.IOException -class DocLevelMonitorFanOutResponse : ActionResponse, ToXContentObject { +class DocLevelMonitorFanOutResponse : + ActionResponse, + ToXContentObject { val nodeId: String val executionId: String val monitorId: String @@ -33,7 +35,7 @@ class DocLevelMonitorFanOutResponse : ActionResponse, ToXContentObject { lastRunContexts = sin.readMap()!! as MutableMap, inputResults = InputRunResults.readFrom(sin), triggerResults = suppressWarning(sin.readMap(StreamInput::readString, DocumentLevelTriggerRunResult::readFrom)), - exception = sin.readException() + exception = sin.readException(), ) constructor( @@ -43,7 +45,7 @@ class DocLevelMonitorFanOutResponse : ActionResponse, ToXContentObject { lastRunContexts: MutableMap, inputResults: InputRunResults = InputRunResults(), // partial, triggerResults: Map = mapOf(), - exception: AlertingException? = null + exception: AlertingException? = null, ) : super() { this.nodeId = nodeId this.executionId = executionId @@ -64,14 +66,18 @@ class DocLevelMonitorFanOutResponse : ActionResponse, ToXContentObject { out.writeMap( triggerResults, StreamOutput::writeString, - { stream, stats -> stats.writeTo(stream) } + { stream, stats -> stats.writeTo(stream) }, ) out.writeException(exception) } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field("node_id", nodeId) .field("execution_id", executionId) .field("monitor_id", monitorId) @@ -85,8 +91,7 @@ class DocLevelMonitorFanOutResponse : ActionResponse, ToXContentObject { companion object { @Suppress("UNCHECKED_CAST") - fun suppressWarning(map: MutableMap?): Map { - return map as Map - } + fun suppressWarning(map: MutableMap?): Map = + map as Map } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequest.kt index 4592a9be..0c171c6c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequest.kt @@ -28,7 +28,7 @@ class GetAlertsRequest : ActionRequest { monitorIds: List? = null, workflowIds: List? = null, alertIds: List? = null, - boolQueryBuilder: BoolQueryBuilder? = null + boolQueryBuilder: BoolQueryBuilder? = null, ) : super() { this.table = table this.severityLevel = severityLevel @@ -51,12 +51,10 @@ class GetAlertsRequest : ActionRequest { monitorIds = sin.readOptionalStringList(), workflowIds = sin.readOptionalStringList(), alertIds = sin.readOptionalStringList(), - boolQueryBuilder = if (sin.readOptionalBoolean() == true) BoolQueryBuilder(sin) else null + boolQueryBuilder = if (sin.readOptionalBoolean() == true) BoolQueryBuilder(sin) else null, ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetAlertsResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetAlertsResponse.kt index 50a4ec53..b9cec3f6 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetAlertsResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetAlertsResponse.kt @@ -18,7 +18,7 @@ class GetAlertsResponse : BaseResponse { constructor( alerts: List, - totalAlerts: Int? + totalAlerts: Int?, ) : super() { this.alerts = alerts this.totalAlerts = totalAlerts @@ -27,7 +27,7 @@ class GetAlertsResponse : BaseResponse { @Throws(IOException::class) constructor(sin: StreamInput) : this( alerts = Collections.unmodifiableList(sin.readList(::Alert)), - totalAlerts = sin.readOptionalInt() + totalAlerts = sin.readOptionalInt(), ) @Throws(IOException::class) @@ -37,8 +37,12 @@ class GetAlertsResponse : BaseResponse { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field("alerts", alerts) .field("totalAlerts", totalAlerts) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequest.kt index 59dd3c39..a184460e 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequest.kt @@ -21,7 +21,7 @@ class GetFindingsRequest : ActionRequest { monitorId: String? = null, findingIndexName: String? = null, monitorIds: List? = null, - boolQueryBuilder: BoolQueryBuilder? = null + boolQueryBuilder: BoolQueryBuilder? = null, ) : super() { this.findingId = findingId this.table = table @@ -38,12 +38,10 @@ class GetFindingsRequest : ActionRequest { monitorId = sin.readOptionalString(), findingIndexName = sin.readOptionalString(), monitorIds = sin.readOptionalStringList(), - boolQueryBuilder = BoolQueryBuilder(sin) + boolQueryBuilder = BoolQueryBuilder(sin), ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponse.kt index 9caeebde..595cf905 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponse.kt @@ -17,7 +17,7 @@ class GetFindingsResponse : BaseResponse { constructor( status: RestStatus, totalFindings: Int?, - findings: List + findings: List, ) : super() { this.status = status this.totalFindings = totalFindings @@ -47,15 +47,17 @@ class GetFindingsResponse : BaseResponse { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field("total_findings", totalFindings) .field("findings", findings) return builder.endObject() } - override fun getStatus(): RestStatus { - return this.status - } + override fun getStatus(): RestStatus = this.status } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequest.kt index 80676a04..a45a840d 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequest.kt @@ -23,7 +23,7 @@ class GetMonitorRequest : ActionRequest { monitorId: String, version: Long, method: RestRequest.Method, - srcContext: FetchSourceContext? + srcContext: FetchSourceContext?, ) : super() { this.monitorId = monitorId this.version = version @@ -40,12 +40,10 @@ class GetMonitorRequest : ActionRequest { FetchSourceContext(sin) // srcContext } else { null - } + }, ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponse.kt index 7984ed07..44b7743b 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponse.kt @@ -32,7 +32,7 @@ class GetMonitorResponse : BaseResponse { seqNo: Long, primaryTerm: Long, monitor: Monitor?, - associatedCompositeMonitors: List? + associatedCompositeMonitors: List?, ) : super() { this.id = id this.version = version @@ -48,12 +48,13 @@ class GetMonitorResponse : BaseResponse { version = sin.readLong(), // version seqNo = sin.readLong(), // seqNo primaryTerm = sin.readLong(), // primaryTerm - monitor = if (sin.readBoolean()) { - Monitor.readFrom(sin) // monitor - } else { - null - }, - associatedCompositeMonitors = sin.readList((AssociatedWorkflow)::readFrom) + monitor = + if (sin.readBoolean()) { + Monitor.readFrom(sin) // monitor + } else { + null + }, + associatedCompositeMonitors = sin.readList((AssociatedWorkflow)::readFrom), ) @Throws(IOException::class) @@ -74,8 +75,12 @@ class GetMonitorResponse : BaseResponse { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field(_ID, id) .field(_VERSION, version) .field(_SEQ_NO, seqNo) @@ -98,8 +103,12 @@ class GetMonitorResponse : BaseResponse { this.name = name } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params?): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params?, + ): XContentBuilder { + builder + .startObject() .field("id", id) .field("name", name) .endObject() @@ -114,15 +123,13 @@ class GetMonitorResponse : BaseResponse { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), - sin.readString() + sin.readString(), ) companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): AssociatedWorkflow { - return AssociatedWorkflow(sin) - } + fun readFrom(sin: StreamInput): AssociatedWorkflow = AssociatedWorkflow(sin) } } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequest.kt index 9d08fa96..492ad16f 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequest.kt @@ -27,7 +27,7 @@ class GetWorkflowAlertsRequest : ActionRequest { monitorIds: List? = null, workflowIds: List? = null, alertIds: List? = null, - getAssociatedAlerts: Boolean + getAssociatedAlerts: Boolean, ) : super() { this.table = table this.severityLevel = severityLevel @@ -50,12 +50,10 @@ class GetWorkflowAlertsRequest : ActionRequest { monitorIds = sin.readOptionalStringList(), workflowIds = sin.readOptionalStringList(), alertIds = sin.readOptionalStringList(), - getAssociatedAlerts = sin.readBoolean() + getAssociatedAlerts = sin.readBoolean(), ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponse.kt index 5104f344..56bb0a2f 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponse.kt @@ -20,7 +20,7 @@ class GetWorkflowAlertsResponse : BaseResponse { constructor( alerts: List, associatedAlerts: List, - totalAlerts: Int? + totalAlerts: Int?, ) : super() { this.alerts = alerts this.associatedAlerts = associatedAlerts @@ -31,7 +31,7 @@ class GetWorkflowAlertsResponse : BaseResponse { constructor(sin: StreamInput) : this( alerts = Collections.unmodifiableList(sin.readList(::Alert)), associatedAlerts = Collections.unmodifiableList(sin.readList(::Alert)), - totalAlerts = sin.readOptionalInt() + totalAlerts = sin.readOptionalInt(), ) @Throws(IOException::class) @@ -42,8 +42,12 @@ class GetWorkflowAlertsResponse : BaseResponse { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field("alerts", alerts) .field("associatedAlerts", associatedAlerts) .field("totalAlerts", totalAlerts) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowRequest.kt index cff81206..30b10f39 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowRequest.kt @@ -18,7 +18,7 @@ class GetWorkflowRequest : ActionRequest { constructor( workflowId: String, - method: RestRequest.Method + method: RestRequest.Method, ) : super() { this.workflowId = workflowId this.method = method @@ -27,12 +27,10 @@ class GetWorkflowRequest : ActionRequest { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // workflowId - sin.readEnum(RestRequest.Method::class.java) // method + sin.readEnum(RestRequest.Method::class.java), // method ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponse.kt index ca6db115..ccf71770 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponse.kt @@ -32,7 +32,7 @@ class GetWorkflowResponse : BaseResponse { seqNo: Long, primaryTerm: Long, status: RestStatus, - workflow: Workflow? + workflow: Workflow?, ) : super() { this.id = id this.version = version @@ -53,7 +53,7 @@ class GetWorkflowResponse : BaseResponse { Workflow.readFrom(sin) // monitor } else { null - } + }, ) @Throws(IOException::class) @@ -72,8 +72,12 @@ class GetWorkflowResponse : BaseResponse { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field(_ID, id) .field(_VERSION, version) .field(_SEQ_NO, seqNo) @@ -85,7 +89,5 @@ class GetWorkflowResponse : BaseResponse { return builder.endObject() } - override fun getStatus(): RestStatus { - return this.status - } + override fun getStatus(): RestStatus = this.status } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexCommentRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexCommentRequest.kt index 3eb05f13..1acb4eb2 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexCommentRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexCommentRequest.kt @@ -32,7 +32,7 @@ class IndexCommentRequest : ActionRequest { seqNo: Long, primaryTerm: Long, method: RestRequest.Method, - content: String + content: String, ) : super() { this.entityId = entityId this.entityType = entityType @@ -51,12 +51,12 @@ class IndexCommentRequest : ActionRequest { seqNo = sin.readLong(), primaryTerm = sin.readLong(), method = sin.readEnum(RestRequest.Method::class.java), - content = sin.readString() + content = sin.readString(), ) override fun validate(): ActionRequestValidationException? { - if (method == RestRequest.Method.POST && entityId.isBlank() || - method == RestRequest.Method.PUT && commentId.isBlank() + if ((method == RestRequest.Method.POST && entityId.isBlank()) || + (method == RestRequest.Method.PUT && commentId.isBlank()) ) { val exception = ActionRequestValidationException() exception.addValidationError("id must not be blank") diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexCommentResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexCommentResponse.kt index 7c9bb9b7..8f12fb52 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexCommentResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexCommentResponse.kt @@ -21,7 +21,7 @@ class IndexCommentResponse : BaseResponse { id: String, seqNo: Long, primaryTerm: Long, - comment: Comment + comment: Comment, ) : super() { this.id = id this.seqNo = seqNo @@ -34,7 +34,7 @@ class IndexCommentResponse : BaseResponse { sin.readString(), // id sin.readLong(), // seqNo sin.readLong(), // primaryTerm - Comment.readFrom(sin) // comment + Comment.readFrom(sin), // comment ) @Throws(IOException::class) @@ -46,12 +46,15 @@ class IndexCommentResponse : BaseResponse { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(_ID, id) .field(_SEQ_NO, seqNo) .field(_PRIMARY_TERM, primaryTerm) .field("comment", comment) .endObject() - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequest.kt index cd5e6230..81ca10a6 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequest.kt @@ -28,7 +28,7 @@ class IndexMonitorRequest : ActionRequest { refreshPolicy: WriteRequest.RefreshPolicy, method: RestRequest.Method, monitor: Monitor, - rbacRoles: List? = null + rbacRoles: List? = null, ) : super() { this.monitorId = monitorId this.seqNo = seqNo @@ -47,7 +47,7 @@ class IndexMonitorRequest : ActionRequest { refreshPolicy = WriteRequest.RefreshPolicy.readFrom(sin), method = sin.readEnum(RestRequest.Method::class.java), monitor = Monitor.readFrom(sin) as Monitor, - rbacRoles = sin.readOptionalStringList() + rbacRoles = sin.readOptionalStringList(), ) override fun validate(): ActionRequestValidationException? { @@ -65,10 +65,15 @@ class IndexMonitorRequest : ActionRequest { private fun hasDocLeveMonitorInput() = monitor.inputs.isNotEmpty() && monitor.inputs[0] is DocLevelMonitorInput private fun isDocLevelMonitor() = - monitor.monitorType.isNotBlank() && isMonitorOfStandardType(monitor.monitorType) && Monitor.MonitorType.valueOf(this.monitor.monitorType.uppercase(Locale.ROOT)) == Monitor.MonitorType.DOC_LEVEL_MONITOR + monitor.monitorType.isNotBlank() && isMonitorOfStandardType(monitor.monitorType) && + Monitor.MonitorType.valueOf(this.monitor.monitorType.uppercase(Locale.ROOT)) == Monitor.MonitorType.DOC_LEVEL_MONITOR private fun isMonitorOfStandardType(monitorType: String): Boolean { - val standardMonitorTypes = Monitor.MonitorType.values().map { it.value.uppercase(Locale.ROOT) }.toSet() + val standardMonitorTypes = + Monitor.MonitorType + .values() + .map { it.value.uppercase(Locale.ROOT) } + .toSet() return standardMonitorTypes.contains(monitorType.uppercase(Locale.ROOT)) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexMonitorResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexMonitorResponse.kt index 0464bff8..f35b865c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexMonitorResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexMonitorResponse.kt @@ -24,7 +24,7 @@ class IndexMonitorResponse : BaseResponse { version: Long, seqNo: Long, primaryTerm: Long, - monitor: Monitor + monitor: Monitor, ) : super() { this.id = id this.version = version @@ -39,7 +39,7 @@ class IndexMonitorResponse : BaseResponse { sin.readLong(), // version sin.readLong(), // seqNo sin.readLong(), // primaryTerm - Monitor.readFrom(sin) as Monitor // monitor + Monitor.readFrom(sin) as Monitor, // monitor ) @Throws(IOException::class) @@ -52,13 +52,16 @@ class IndexMonitorResponse : BaseResponse { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(_ID, id) .field(_VERSION, version) .field(_SEQ_NO, seqNo) .field(_PRIMARY_TERM, primaryTerm) .field("monitor", monitor) .endObject() - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequest.kt index 1033e651..8febd134 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequest.kt @@ -21,7 +21,9 @@ class IndexWorkflowRequest : ActionRequest { var workflow: Workflow val rbacRoles: List? - private val MAX_DELEGATE_SIZE = 25 + companion object { + private const val MAX_DELEGATE_SIZE = 25 + } constructor( workflowId: String, @@ -30,7 +32,7 @@ class IndexWorkflowRequest : ActionRequest { refreshPolicy: WriteRequest.RefreshPolicy, method: RestRequest.Method, workflow: Workflow, - rbacRoles: List? = null + rbacRoles: List? = null, ) : super() { this.workflowId = workflowId this.seqNo = seqNo @@ -49,64 +51,80 @@ class IndexWorkflowRequest : ActionRequest { refreshPolicy = WriteRequest.RefreshPolicy.readFrom(sin), method = sin.readEnum(RestRequest.Method::class.java), workflow = Workflow.readFrom(sin) as Workflow, - rbacRoles = sin.readOptionalStringList() + rbacRoles = sin.readOptionalStringList(), ) override fun validate(): ActionRequestValidationException? { var validationException: ActionRequestValidationException? = null if (workflow.inputs.isEmpty()) { - validationException = ValidateActions.addValidationError( - "Input list can not be empty.", - validationException - ) + validationException = + ValidateActions.addValidationError( + "Input list can not be empty.", + validationException, + ) return validationException } if (workflow.inputs.size > 1) { - validationException = ValidateActions.addValidationError( - "Input list can contain only one element.", - validationException - ) + validationException = + ValidateActions.addValidationError( + "Input list can contain only one element.", + validationException, + ) return validationException } if (workflow.inputs[0] !is CompositeInput) { - validationException = ValidateActions.addValidationError( - "When creating a workflow input must be CompositeInput", - validationException - ) + validationException = + ValidateActions.addValidationError( + "When creating a workflow input must be CompositeInput", + validationException, + ) } val compositeInput = workflow.inputs[0] as CompositeInput - val monitorIds = compositeInput.sequence.delegates.stream().map { it.monitorId }.collect(Collectors.toList()) + val monitorIds = + compositeInput.sequence.delegates + .stream() + .map { it.monitorId } + .collect(Collectors.toList()) if (monitorIds.isNullOrEmpty()) { - validationException = ValidateActions.addValidationError( - "Delegates list can not be empty.", - validationException - ) + validationException = + ValidateActions.addValidationError( + "Delegates list can not be empty.", + validationException, + ) // Break the flow because next checks are dependant on non-null monitorIds return validationException } if (monitorIds.size > MAX_DELEGATE_SIZE) { - validationException = ValidateActions.addValidationError( - "Delegates list can not be larger then $MAX_DELEGATE_SIZE.", - validationException - ) + validationException = + ValidateActions.addValidationError( + "Delegates list can not be larger then $MAX_DELEGATE_SIZE.", + validationException, + ) } if (monitorIds.toSet().size != monitorIds.size) { - validationException = ValidateActions.addValidationError( - "Duplicate delegates not allowed", - validationException - ) + validationException = + ValidateActions.addValidationError( + "Duplicate delegates not allowed", + validationException, + ) } val delegates = compositeInput.sequence.delegates - val orderSet = delegates.stream().filter { it.order > 0 }.map { it.order }.collect(Collectors.toSet()) + val orderSet = + delegates + .stream() + .filter { it.order > 0 } + .map { it.order } + .collect(Collectors.toSet()) if (orderSet.size != delegates.size) { - validationException = ValidateActions.addValidationError( - "Sequence ordering of delegate monitor shouldn't contain duplicate order values", - validationException - ) + validationException = + ValidateActions.addValidationError( + "Sequence ordering of delegate monitor shouldn't contain duplicate order values", + validationException, + ) } val monitorIdOrderMap: Map = delegates.associate { it.monitorId to it.order } @@ -114,34 +132,38 @@ class IndexWorkflowRequest : ActionRequest { if (it.chainedMonitorFindings != null) { if (it.chainedMonitorFindings.monitorId != null) { if (monitorIdOrderMap.containsKey(it.chainedMonitorFindings.monitorId) == false) { - validationException = ValidateActions.addValidationError( - "Chained Findings Monitor ${it.chainedMonitorFindings.monitorId} doesn't exist in sequence", - validationException - ) + validationException = + ValidateActions.addValidationError( + "Chained Findings Monitor ${it.chainedMonitorFindings.monitorId} doesn't exist in sequence", + validationException, + ) // Break the flow because next check will generate the NPE return validationException } if (it.order <= monitorIdOrderMap[it.chainedMonitorFindings.monitorId]!!) { - validationException = ValidateActions.addValidationError( - "Chained Findings Monitor ${it.chainedMonitorFindings.monitorId} should be executed before monitor ${it.monitorId}", - validationException - ) + validationException = + ValidateActions.addValidationError( + "Chained Findings Monitor ${it.chainedMonitorFindings.monitorId} should be executed before monitor ${it.monitorId}", + validationException, + ) } } else { for (monitorId in it.chainedMonitorFindings.monitorIds) { if (!monitorIdOrderMap.containsKey(monitorId)) { - validationException = ValidateActions.addValidationError( - "Chained Findings Monitor $monitorId doesn't exist in sequence", - validationException - ) + validationException = + ValidateActions.addValidationError( + "Chained Findings Monitor $monitorId doesn't exist in sequence", + validationException, + ) return validationException } else { val order = monitorIdOrderMap.get(monitorId)!! if (order >= it.order) { return ValidateActions.addValidationError( - "Chained Findings Monitor ${it.chainedMonitorFindings.monitorId} should be executed before monitor ${it.monitorId}. " + - "Order of monitor being chained [$order] should be smaller than order of monitor using findings as source data [${it.order}] in sequence", - validationException + "Chained Findings Monitor ${it.chainedMonitorFindings.monitorId} should be executed before " + + "monitor ${it.monitorId}. Order of monitor being chained [$order] should be smaller than " + + "order of monitor using findings as source data [${it.order}] in sequence", + validationException, ) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowResponse.kt index b54d0d85..dd4d088b 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowResponse.kt @@ -21,7 +21,7 @@ class IndexWorkflowResponse : BaseResponse { version: Long, seqNo: Long, primaryTerm: Long, - workflow: Workflow + workflow: Workflow, ) : super() { this.id = id this.version = version @@ -36,7 +36,7 @@ class IndexWorkflowResponse : BaseResponse { sin.readLong(), // version sin.readLong(), // seqNo sin.readLong(), // primaryTerm - Workflow.readFrom(sin) as Workflow // workflow + Workflow.readFrom(sin) as Workflow, // workflow ) @Throws(IOException::class) @@ -49,13 +49,16 @@ class IndexWorkflowResponse : BaseResponse { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(IndexUtils._ID, id) .field(IndexUtils._VERSION, version) .field(IndexUtils._SEQ_NO, seqNo) .field(IndexUtils._PRIMARY_TERM, primaryTerm) .field("workflow", workflow) .endObject() - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequest.kt index 6e8f78f1..7d11239c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequest.kt @@ -8,14 +8,13 @@ import org.opensearch.core.common.io.stream.StreamOutput import java.io.IOException class PublishFindingsRequest : ActionRequest { - val monitorId: String val finding: Finding constructor( monitorId: String, - finding: Finding + finding: Finding, ) : super() { this.monitorId = monitorId this.finding = finding @@ -24,12 +23,10 @@ class PublishFindingsRequest : ActionRequest { @Throws(IOException::class) constructor(sin: StreamInput) : this( monitorId = sin.readString(), - finding = Finding.readFrom(sin) + finding = Finding.readFrom(sin), ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null override fun writeTo(out: StreamOutput) { out.writeString(monitorId) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequest.kt index e0d150d0..f4e561b5 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequest.kt @@ -8,23 +8,20 @@ import org.opensearch.core.common.io.stream.StreamOutput import java.io.IOException class SearchCommentRequest : ActionRequest { - val searchRequest: SearchRequest constructor( - searchRequest: SearchRequest + searchRequest: SearchRequest, ) : super() { this.searchRequest = searchRequest } @Throws(IOException::class) constructor(sin: StreamInput) : this( - searchRequest = SearchRequest(sin) + searchRequest = SearchRequest(sin), ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequest.kt index 003d3316..cea72da9 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequest.kt @@ -13,23 +13,20 @@ import org.opensearch.core.common.io.stream.StreamOutput import java.io.IOException class SearchMonitorRequest : ActionRequest { - val searchRequest: SearchRequest constructor( - searchRequest: SearchRequest + searchRequest: SearchRequest, ) : super() { this.searchRequest = searchRequest } @Throws(IOException::class) constructor(sin: StreamInput) : this( - searchRequest = SearchRequest(sin) + searchRequest = SearchRequest(sin), ) - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null @Throws(IOException::class) override fun writeTo(out: StreamOutput) { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/SubscribeFindingsResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/SubscribeFindingsResponse.kt index 58419d7c..2b2d77fe 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/SubscribeFindingsResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/SubscribeFindingsResponse.kt @@ -9,7 +9,6 @@ import org.opensearch.core.xcontent.XContentBuilder import java.io.IOException class SubscribeFindingsResponse : BaseResponse { - private var status: RestStatus constructor(status: RestStatus) : super() { @@ -26,13 +25,15 @@ class SubscribeFindingsResponse : BaseResponse { out.writeEnum(status) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field("status", status.status) return builder.endObject() } - override fun getStatus(): RestStatus { - return this.status - } + override fun getStatus(): RestStatus = this.status } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregationBuilder.kt b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregationBuilder.kt index 75d1f3ae..183588ab 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregationBuilder.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregationBuilder.kt @@ -18,8 +18,7 @@ import java.util.Objects import kotlin.collections.ArrayList import kotlin.collections.HashMap -class BucketSelectorExtAggregationBuilder : - AbstractPipelineAggregationBuilder { +class BucketSelectorExtAggregationBuilder : AbstractPipelineAggregationBuilder { private val bucketsPathsMap: Map val parentBucketPath: String val script: Script @@ -31,7 +30,7 @@ class BucketSelectorExtAggregationBuilder : bucketsPathsMap: Map, script: Script, parentBucketPath: String, - filter: BucketSelectorExtFilter? + filter: BucketSelectorExtFilter?, ) : super(name, NAME.preferredName, listOf(parentBucketPath).toTypedArray()) { this.bucketsPathsMap = bucketsPathsMap this.script = script @@ -46,11 +45,12 @@ class BucketSelectorExtAggregationBuilder : script = Script(sin) gapPolicy = BucketHelpers.GapPolicy.readFrom(sin) parentBucketPath = sin.readString() - filter = if (sin.readBoolean()) { - BucketSelectorExtFilter(sin) - } else { - null - } + filter = + if (sin.readBoolean()) { + BucketSelectorExtFilter(sin) + } else { + null + } } @Throws(IOException::class) @@ -76,23 +76,28 @@ class BucketSelectorExtAggregationBuilder : return this } - override fun createInternal(metaData: Map?): PipelineAggregator { - return BucketSelectorExtAggregator(name, bucketsPathsMap, parentBucketPath, script, gapPolicy, filter, metaData) - } + override fun createInternal(metaData: Map?): PipelineAggregator = + BucketSelectorExtAggregator(name, bucketsPathsMap, parentBucketPath, script, gapPolicy, filter, metaData) @Throws(IOException::class) - public override fun internalXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.field(PipelineAggregator.Parser.BUCKETS_PATH.preferredName, bucketsPathsMap as Map?) + public override fun internalXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .field(PipelineAggregator.Parser.BUCKETS_PATH.preferredName, bucketsPathsMap as Map?) .field(PARENT_BUCKET_PATH.preferredName, parentBucketPath) .field(Script.SCRIPT_PARSE_FIELD.preferredName, script) .field(PipelineAggregator.Parser.GAP_POLICY.preferredName, gapPolicy.getName()) if (filter != null) { if (filter.isCompositeAggregation) { - builder.startObject(BUCKET_SELECTOR_COMPOSITE_AGG_FILTER.preferredName) + builder + .startObject(BUCKET_SELECTOR_COMPOSITE_AGG_FILTER.preferredName) .value(filter) .endObject() } else { - builder.startObject(BUCKET_SELECTOR_FILTER.preferredName) + builder + .startObject(BUCKET_SELECTOR_FILTER.preferredName) .value(filter) .endObject() } @@ -100,17 +105,13 @@ class BucketSelectorExtAggregationBuilder : return builder } - override fun overrideBucketsPath(): Boolean { - return true - } + override fun overrideBucketsPath(): Boolean = true override fun validate(context: ValidationContext) { // Nothing to check } - override fun hashCode(): Int { - return Objects.hash(super.hashCode(), bucketsPathsMap, script, gapPolicy) - } + override fun hashCode(): Int = Objects.hash(super.hashCode(), bucketsPathsMap, script, gapPolicy) override fun equals(other: Any?): Boolean { if (this === other) return true @@ -121,19 +122,20 @@ class BucketSelectorExtAggregationBuilder : bucketsPathsMap == otherCast.bucketsPathsMap && script == otherCast.script && gapPolicy == otherCast.gapPolicy - ) + ) } - override fun getWriteableName(): String { - return NAME.preferredName - } + override fun getWriteableName(): String = NAME.preferredName companion object { val NAME = ParseField("bucket_selector_ext") val PARENT_BUCKET_PATH = ParseField("parent_bucket_path") @Throws(IOException::class) - fun parse(reducerName: String, parser: XContentParser): BucketSelectorExtAggregationBuilder { + fun parse( + reducerName: String, + parser: XContentParser, + ): BucketSelectorExtAggregationBuilder { var token: XContentParser.Token var script: Script? = null var currentFieldName: String? = null @@ -150,19 +152,23 @@ class BucketSelectorExtAggregationBuilder : bucketsPathsMap = HashMap() bucketsPathsMap["_value"] = parser.text() } + PipelineAggregator.Parser.GAP_POLICY.match(currentFieldName, parser.deprecationHandler) -> { gapPolicy = BucketHelpers.GapPolicy.parse(parser.text(), parser.tokenLocation) } + Script.SCRIPT_PARSE_FIELD.match(currentFieldName, parser.deprecationHandler) -> { script = Script.parse(parser) } + PARENT_BUCKET_PATH.match(currentFieldName, parser.deprecationHandler) -> { parentBucketPath = parser.text() } + else -> { throw ParsingException( parser.tokenLocation, - "Unknown key for a $token in [$reducerName]: [$currentFieldName]." + "Unknown key for a $token in [$reducerName]: [$currentFieldName].", ) } } @@ -180,7 +186,7 @@ class BucketSelectorExtAggregationBuilder : } else { throw ParsingException( parser.tokenLocation, - "Unknown key for a $token in [$reducerName]: [$currentFieldName]." + "Unknown key for a $token in [$reducerName]: [$currentFieldName].", ) } } else if (token === XContentParser.Token.START_OBJECT) { @@ -188,6 +194,7 @@ class BucketSelectorExtAggregationBuilder : Script.SCRIPT_PARSE_FIELD.match(currentFieldName, parser.deprecationHandler) -> { script = Script.parse(parser) } + PipelineAggregator.Parser.BUCKETS_PATH.match(currentFieldName, parser.deprecationHandler) -> { val map = parser.map() bucketsPathsMap = HashMap() @@ -195,19 +202,22 @@ class BucketSelectorExtAggregationBuilder : bucketsPathsMap[key] = value.toString() } } + BUCKET_SELECTOR_FILTER.match(currentFieldName, parser.deprecationHandler) -> { filter = BucketSelectorExtFilter.parse(reducerName, false, parser) } + BUCKET_SELECTOR_COMPOSITE_AGG_FILTER.match( currentFieldName, - parser.deprecationHandler + parser.deprecationHandler, ) -> { filter = BucketSelectorExtFilter.parse(reducerName, true, parser) } + else -> { throw ParsingException( parser.tokenLocation, - "Unknown key for a $token in [$reducerName]: [$currentFieldName]." + "Unknown key for a $token in [$reducerName]: [$currentFieldName].", ) } } @@ -218,20 +228,25 @@ class BucketSelectorExtAggregationBuilder : if (bucketsPathsMap == null) { throw ParsingException( parser.tokenLocation, - "Missing required field [" + PipelineAggregator.Parser.BUCKETS_PATH.preferredName + "] for bucket_selector aggregation [" + reducerName + "]" + "Missing required field [" + PipelineAggregator.Parser.BUCKETS_PATH.preferredName + + "] for bucket_selector aggregation [" + + reducerName + + "]", ) } if (script == null) { throw ParsingException( parser.tokenLocation, - "Missing required field [" + Script.SCRIPT_PARSE_FIELD.preferredName + "] for bucket_selector aggregation [" + reducerName + "]" + "Missing required field [" + Script.SCRIPT_PARSE_FIELD.preferredName + "] for bucket_selector aggregation [" + + reducerName + + "]", ) } if (parentBucketPath == null) { throw ParsingException( parser.tokenLocation, - "Missing required field [" + PARENT_BUCKET_PATH + "] for bucket_selector aggregation [" + reducerName + "]" + "Missing required field [" + PARENT_BUCKET_PATH + "] for bucket_selector aggregation [" + reducerName + "]", ) } val factory = BucketSelectorExtAggregationBuilder(reducerName, bucketsPathsMap, script, parentBucketPath, filter) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregator.kt b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregator.kt index ef305239..580dda98 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregator.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregator.kt @@ -31,7 +31,7 @@ class BucketSelectorExtAggregator : SiblingPipelineAggregator { script: Script, gapPolicy: BucketHelpers.GapPolicy, filter: BucketSelectorExtFilter?, - metadata: Map? + metadata: Map?, ) : super(name, bucketsPathsMap.values.toTypedArray(), metadata) { this.bucketsPathsMap = bucketsPathsMap this.parentBucketPath = parentBucketPath @@ -57,7 +57,10 @@ class BucketSelectorExtAggregator : SiblingPipelineAggregator { } } - override fun doReduce(aggregations: Aggregations, reduceContext: InternalAggregation.ReduceContext): InternalAggregation { + override fun doReduce( + aggregations: Aggregations, + reduceContext: InternalAggregation.ReduceContext, + ): InternalAggregation { val parentBucketPathList = AggregationPath.parse(parentBucketPath).pathElementsAsStringList var subAggregations: Aggregations = aggregations for (i in 0 until parentBucketPathList.size - 1) { @@ -111,27 +114,32 @@ class BucketSelectorExtAggregator : SiblingPipelineAggregator { name(), parentBucketPath, selectedBucketsIndex, - originalAgg.metadata + originalAgg.metadata, ) } - private fun isAccepted(obj: Any, filter: IncludeExclude?): Boolean { - return when (obj.javaClass) { + private fun isAccepted( + obj: Any, + filter: IncludeExclude?, + ): Boolean = + when (obj.javaClass) { String::class.java -> { val stringFilter = filter!!.convertToStringFilter(DocValueFormat.RAW) stringFilter.accept(BytesRef(obj as String)) } + java.lang.Long::class.java, Long::class.java -> { val longFilter = filter!!.convertToLongFilter(DocValueFormat.RAW) longFilter.accept(obj as Long) } + java.lang.Double::class.java, Double::class.java -> { val doubleFilter = filter!!.convertToDoubleFilter() doubleFilter.accept(obj as Long) } + else -> { throw IllegalStateException("Object is not comparable. Please use one of String, Long or Double type.") } } - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtFilter.kt b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtFilter.kt index 3d9466eb..1ed454c8 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtFilter.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtFilter.kt @@ -61,7 +61,10 @@ class BucketSelectorExtFilter : BaseModel { } @Throws(IOException::class) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { if (isCompositeAggregation) { for ((key, filter) in filtersMap!!) { builder.startObject(key) @@ -75,21 +78,30 @@ class BucketSelectorExtFilter : BaseModel { } val isCompositeAggregation: Boolean - get() = if (filtersMap != null && filters == null) { - true - } else if (filtersMap == null && filters != null) { - false - } else { - throw IllegalStateException("Type of selector cannot be determined") - } + get() = + if (filtersMap != null && filters == null) { + true + } else if (filtersMap == null && filters != null) { + false + } else { + throw IllegalStateException("Type of selector cannot be determined") + } companion object { const val NAME = "filter" + + @Suppress("ktlint:standard:property-naming") var BUCKET_SELECTOR_FILTER = ParseField("filter") + + @Suppress("ktlint:standard:property-naming") var BUCKET_SELECTOR_COMPOSITE_AGG_FILTER = ParseField("composite_agg_filter") @Throws(IOException::class) - fun parse(reducerName: String, isCompositeAggregation: Boolean, parser: XContentParser): BucketSelectorExtFilter { + fun parse( + reducerName: String, + isCompositeAggregation: Boolean, + parser: XContentParser, + ): BucketSelectorExtFilter { var token: XContentParser.Token return if (isCompositeAggregation) { val filtersMap = HashMap() @@ -101,7 +113,7 @@ class BucketSelectorExtFilter : BaseModel { } else { throw ParsingException( parser.tokenLocation, - "Unknown key for a " + token + " in [" + reducerName + "]: [" + parser.currentName() + "]." + "Unknown key for a " + token + " in [" + reducerName + "]: [" + parser.currentName() + "].", ) } } @@ -112,7 +124,10 @@ class BucketSelectorExtFilter : BaseModel { } @Throws(IOException::class) - private fun parseIncludeExclude(reducerName: String, parser: XContentParser): IncludeExclude { + private fun parseIncludeExclude( + reducerName: String, + parser: XContentParser, + ): IncludeExclude { var token: XContentParser.Token var include: IncludeExclude? = null var exclude: IncludeExclude? = null @@ -123,14 +138,16 @@ class BucketSelectorExtFilter : BaseModel { parser.nextToken() include = IncludeExclude.parseInclude(parser) } + IncludeExclude.EXCLUDE_FIELD.match(fieldName, parser.deprecationHandler) -> { parser.nextToken() exclude = IncludeExclude.parseExclude(parser) } + else -> { throw ParsingException( parser.tokenLocation, - "Unknown key for a $token in [$reducerName]: [$fieldName]." + "Unknown key for a $token in [$reducerName]: [$fieldName].", ) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorIndices.kt b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorIndices.kt index a2989fc8..7ac87b39 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorIndices.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorIndices.kt @@ -16,7 +16,7 @@ open class BucketSelectorIndices : InternalAggregation { name: String?, parentBucketPath: String, bucketIndices: List, - metaData: Map? + metaData: Map?, ) : super(name, metaData) { this.parentBucketPath = parentBucketPath this.bucketIndices = bucketIndices @@ -37,21 +37,16 @@ open class BucketSelectorIndices : InternalAggregation { out.writeIntArray(bucketIndices.stream().mapToInt { i: Int? -> i!! }.toArray()) } - override fun getWriteableName(): String { - return BucketSelectorExtAggregationBuilder.NAME.preferredName - } + override fun getWriteableName(): String = BucketSelectorExtAggregationBuilder.NAME.preferredName - override fun reduce(aggregations: List, reduceContext: ReduceContext): BucketSelectorIndices { - throw UnsupportedOperationException("Not supported") - } + override fun reduce( + aggregations: List, + reduceContext: ReduceContext, + ): BucketSelectorIndices = throw UnsupportedOperationException("Not supported") - override fun mustReduceOnSingleInternalAgg(): Boolean { - return false - } + override fun mustReduceOnSingleInternalAgg(): Boolean = false - override fun getProperty(path: MutableList?): Any { - throw UnsupportedOperationException("Not supported") - } + override fun getProperty(path: MutableList?): Any = throw UnsupportedOperationException("Not supported") object Fields { const val PARENT_BUCKET_PATH = "parent_bucket_path" @@ -59,7 +54,10 @@ open class BucketSelectorIndices : InternalAggregation { } @Throws(IOException::class) - override fun doXContentBody(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun doXContentBody( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { builder.field(Fields.PARENT_BUCKET_PATH, parentBucketPath) builder.field(Fields.BUCKET_INDICES, bucketIndices) otherStatsToXContent(builder) @@ -67,13 +65,9 @@ open class BucketSelectorIndices : InternalAggregation { } @Throws(IOException::class) - protected fun otherStatsToXContent(builder: XContentBuilder): XContentBuilder { - return builder - } + protected fun otherStatsToXContent(builder: XContentBuilder): XContentBuilder = builder - override fun hashCode(): Int { - return Objects.hash(super.hashCode(), parentBucketPath) - } + override fun hashCode(): Int = Objects.hash(super.hashCode(), parentBucketPath) override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/src/main/kotlin/org/opensearch/commons/alerting/alerts/AlertError.kt b/src/main/kotlin/org/opensearch/commons/alerting/alerts/AlertError.kt index 28ef4a55..14e969fa 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/alerts/AlertError.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/alerts/AlertError.kt @@ -12,7 +12,11 @@ import org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken import java.io.IOException import java.time.Instant -data class AlertError(val timestamp: Instant, var message: String) : Writeable, ToXContent { +data class AlertError( + val timestamp: Instant, + var message: String, +) : Writeable, + ToXContent { init { this.message = obfuscateIPAddresses(message) } @@ -20,7 +24,7 @@ data class AlertError(val timestamp: Instant, var message: String) : Writeable, @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readInstant(), // timestamp - sin.readString() // message + sin.readString(), // message ) @Throws(IOException::class) @@ -28,8 +32,8 @@ data class AlertError(val timestamp: Instant, var message: String) : Writeable, out.writeInstant(timestamp) out.writeString(message) } - companion object { + companion object { const val TIMESTAMP_FIELD = "timestamp" const val MESSAGE_FIELD = "message" @@ -54,9 +58,7 @@ data class AlertError(val timestamp: Instant, var message: String) : Writeable, @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): AlertError { - return AlertError(sin) - } + fun readFrom(sin: StreamInput): AlertError = AlertError(sin) fun obfuscateIPAddresses(exceptionMessage: String): String { val ipAddressPattern = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" @@ -65,10 +67,13 @@ data class AlertError(val timestamp: Instant, var message: String) : Writeable, } } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .optionalTimeField(TIMESTAMP_FIELD, timestamp) .field(MESSAGE_FIELD, message) .endObject() - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/ActionExecutionResult.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/ActionExecutionResult.kt index 6d4614e8..c5f09b05 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/ActionExecutionResult.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/ActionExecutionResult.kt @@ -20,23 +20,26 @@ import java.time.Instant data class ActionExecutionResult( val actionId: String, val lastExecutionTime: Instant?, - val throttledCount: Int = 0 -) : Writeable, ToXContentObject { - + val throttledCount: Int = 0, +) : Writeable, + ToXContentObject { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // actionId sin.readOptionalInstant(), // lastExecutionTime - sin.readInt() // throttledCount + sin.readInt(), // throttledCount ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(ACTION_ID_FIELD, actionId) .optionalTimeField(LAST_EXECUTION_TIME_FIELD, lastExecutionTime) .field(THROTTLED_COUNT_FIELD, throttledCount) .endObject() - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -62,9 +65,17 @@ data class ActionExecutionResult( val fieldName = xcp.currentName() xcp.nextToken() when (fieldName) { - ACTION_ID_FIELD -> actionId = xcp.text() - THROTTLED_COUNT_FIELD -> throttledCount = xcp.intValue() - LAST_EXECUTION_TIME_FIELD -> lastExecutionTime = xcp.instant() + ACTION_ID_FIELD -> { + actionId = xcp.text() + } + + THROTTLED_COUNT_FIELD -> { + throttledCount = xcp.intValue() + } + + LAST_EXECUTION_TIME_FIELD -> { + lastExecutionTime = xcp.instant() + } else -> { throw IllegalStateException("Unexpected field: $fieldName, while parsing action") @@ -78,8 +89,6 @@ data class ActionExecutionResult( @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): ActionExecutionResult { - return ActionExecutionResult(sin) - } + fun readFrom(sin: StreamInput): ActionExecutionResult = ActionExecutionResult(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/AggregationResultBucket.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/AggregationResultBucket.kt index 2d36a51c..4f188ee3 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/AggregationResultBucket.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/AggregationResultBucket.kt @@ -16,9 +16,9 @@ import java.util.Locale data class AggregationResultBucket( val parentBucketPath: String?, val bucketKeys: List, - val bucket: Map? // TODO: Should reduce contents to only top-level to not include sub-aggs here -) : Writeable, ToXContentObject { - + val bucket: Map?, // TODO: Should reduce contents to only top-level to not include sub-aggs here +) : Writeable, + ToXContentObject { @Throws(IOException::class) constructor(sin: StreamInput) : this(sin.readString(), sin.readStringList(), sin.readMap()) @@ -28,14 +28,18 @@ data class AggregationResultBucket( out.writeMap(bucket) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { builder.startObject() innerXContent(builder) return builder.endObject() } fun innerXContent(builder: XContentBuilder): XContentBuilder { - builder.startObject(CONFIG_NAME) + builder + .startObject(CONFIG_NAME) .field(PARENTS_BUCKET_PATH, parentBucketPath) .field(BUCKET_KEYS, bucketKeys.toTypedArray()) .field(BUCKET, bucket) @@ -62,22 +66,28 @@ data class AggregationResultBucket( Locale.ROOT, "Failed to parse object: expecting token with name [%s] but found [%s]", CONFIG_NAME, - xcp.currentName() - ) + xcp.currentName(), + ), ) } while (xcp.nextToken() != Token.END_OBJECT) { val fieldName = xcp.currentName() xcp.nextToken() when (fieldName) { - PARENTS_BUCKET_PATH -> parentBucketPath = xcp.text() + PARENTS_BUCKET_PATH -> { + parentBucketPath = xcp.text() + } + BUCKET_KEYS -> { ensureExpectedToken(Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != Token.END_ARRAY) { bucketKeys.add(xcp.text()) } } - BUCKET -> bucket = xcp.map() + + BUCKET -> { + bucket = xcp.map() + } } } return AggregationResultBucket(parentBucketPath, bucketKeys, bucket) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Alert.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Alert.kt index e435c866..9498d05e 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Alert.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Alert.kt @@ -43,9 +43,9 @@ data class Alert( val aggregationResultBucket: AggregationResultBucket? = null, val executionId: String? = null, val associatedAlertIds: List, - val clusters: List? = null -) : Writeable, ToXContent { - + val clusters: List? = null, +) : Writeable, + ToXContent { init { if (errorMessage != null) { require(state == State.DELETED || state == State.ERROR || state == State.AUDIT) { @@ -64,7 +64,7 @@ data class Alert( chainedAlertTrigger: ChainedAlertTrigger, workflow: Workflow, associatedAlertIds: List, - clusters: List? = null + clusters: List? = null, ) : this( monitorId = NO_ID, monitorName = "", @@ -87,7 +87,7 @@ data class Alert( workflowId = workflow.id, workflowName = workflow.name, associatedAlertIds = associatedAlertIds, - clusters = clusters + clusters = clusters, ) constructor( @@ -102,7 +102,7 @@ data class Alert( schemaVersion: Int = NO_SCHEMA_VERSION, executionId: String? = null, workflowId: String? = null, - clusters: List? = null + clusters: List? = null, ) : this( monitorId = monitor.id, monitorName = monitor.name, @@ -125,7 +125,7 @@ data class Alert( workflowId = workflowId ?: "", workflowName = "", associatedAlertIds = emptyList(), - clusters = clusters + clusters = clusters, ) constructor( @@ -141,7 +141,7 @@ data class Alert( findingIds: List = emptyList(), executionId: String? = null, workflowId: String? = null, - clusters: List? = null + clusters: List? = null, ) : this( monitorId = monitor.id, monitorName = monitor.name, @@ -164,7 +164,7 @@ data class Alert( workflowId = workflowId ?: "", workflowName = "", associatedAlertIds = emptyList(), - clusters = clusters + clusters = clusters, ) constructor( @@ -181,7 +181,7 @@ data class Alert( findingIds: List = emptyList(), executionId: String? = null, workflowId: String? = null, - clusters: List? = null + clusters: List? = null, ) : this( monitorId = monitor.id, monitorName = monitor.name, @@ -204,7 +204,7 @@ data class Alert( workflowId = workflowId ?: "", workflowName = "", associatedAlertIds = emptyList(), - clusters = clusters + clusters = clusters, ) constructor( @@ -222,7 +222,7 @@ data class Alert( schemaVersion: Int = NO_SCHEMA_VERSION, executionId: String? = null, workflowId: String? = null, - clusters: List? = null + clusters: List? = null, ) : this( id = id, monitorId = monitor.id, @@ -246,7 +246,7 @@ data class Alert( workflowId = workflowId ?: "", workflowName = "", associatedAlertIds = emptyList(), - clusters = clusters + clusters = clusters, ) constructor( @@ -261,7 +261,7 @@ data class Alert( schemaVersion: Int = NO_SCHEMA_VERSION, workflowId: String? = null, executionId: String?, - clusters: List? = null + clusters: List? = null, ) : this( id = id, monitorId = monitor.id, @@ -285,17 +285,21 @@ data class Alert( workflowId = workflowId ?: "", executionId = executionId, associatedAlertIds = emptyList(), - clusters = clusters + clusters = clusters, ) enum class State { - ACTIVE, ACKNOWLEDGED, COMPLETED, ERROR, DELETED, + ACTIVE, + ACKNOWLEDGED, + COMPLETED, + ERROR, + DELETED, // Alerts are created in audit state when they are generated by delegate monitors of a workflow. // since chained alerts can be configured and acknowledged, the underlying monitors' alerts are simply // for evaluating chained alert triggers and auditing purpose. // Audit state alerts will be created in the history index and do not need to be acknowledged by users. - AUDIT + AUDIT, } @Throws(IOException::class) @@ -308,11 +312,12 @@ data class Alert( workflowName = sin.readString(), monitorName = sin.readString(), monitorVersion = sin.readLong(), - monitorUser = if (sin.readBoolean()) { - User(sin) - } else { - null - }, + monitorUser = + if (sin.readBoolean()) { + User(sin) + } else { + null + }, triggerId = sin.readString(), triggerName = sin.readString(), findingIds = sin.readStringList(), @@ -329,7 +334,7 @@ data class Alert( aggregationResultBucket = if (sin.readBoolean()) AggregationResultBucket(sin) else null, executionId = sin.readOptionalString(), associatedAlertIds = sin.readStringList(), - clusters = sin.readOptionalStringList() + clusters = sin.readOptionalStringList(), ) fun isAcknowledged(): Boolean = (state == State.ACKNOWLEDGED) @@ -371,7 +376,6 @@ data class Alert( } companion object { - const val ALERT_ID_FIELD = "id" const val SCHEMA_VERSION_FIELD = "schema_version" const val ALERT_VERSION_FIELD = "version" @@ -405,7 +409,11 @@ data class Alert( @JvmStatic @JvmOverloads @Throws(IOException::class) - fun parse(xcp: XContentParser, id: String = NO_ID, version: Long = NO_VERSION): Alert { + fun parse( + xcp: XContentParser, + id: String = NO_ID, + version: Long = NO_VERSION, + ): Alert { lateinit var monitorId: String var workflowId = "" var workflowName = "" @@ -436,69 +444,127 @@ data class Alert( xcp.nextToken() when (fieldName) { - MONITOR_ID_FIELD -> monitorId = xcp.text() - WORKFLOW_ID_FIELD -> workflowId = xcp.text() - WORKFLOW_NAME_FIELD -> workflowName = xcp.text() - SCHEMA_VERSION_FIELD -> schemaVersion = xcp.intValue() - MONITOR_NAME_FIELD -> monitorName = xcp.text() - MONITOR_VERSION_FIELD -> monitorVersion = xcp.longValue() - MONITOR_USER_FIELD -> - monitorUser = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { - null - } else { - User.parse(xcp) - } - TRIGGER_ID_FIELD -> triggerId = xcp.text() + MONITOR_ID_FIELD -> { + monitorId = xcp.text() + } + + WORKFLOW_ID_FIELD -> { + workflowId = xcp.text() + } + + WORKFLOW_NAME_FIELD -> { + workflowName = xcp.text() + } + + SCHEMA_VERSION_FIELD -> { + schemaVersion = xcp.intValue() + } + + MONITOR_NAME_FIELD -> { + monitorName = xcp.text() + } + + MONITOR_VERSION_FIELD -> { + monitorVersion = xcp.longValue() + } + + MONITOR_USER_FIELD -> { + monitorUser = + if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + null + } else { + User.parse(xcp) + } + } + + TRIGGER_ID_FIELD -> { + triggerId = xcp.text() + } + FINDING_IDS -> { ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { findingIds.add(xcp.text()) } } + RELATED_DOC_IDS -> { ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { relatedDocIds.add(xcp.text()) } } - STATE_FIELD -> state = State.valueOf(xcp.text()) - TRIGGER_NAME_FIELD -> triggerName = xcp.text() - START_TIME_FIELD -> startTime = requireNotNull(xcp.instant()) - END_TIME_FIELD -> endTime = xcp.instant() - LAST_NOTIFICATION_TIME_FIELD -> lastNotificationTime = xcp.instant() - ACKNOWLEDGED_TIME_FIELD -> acknowledgedTime = xcp.instant() - ERROR_MESSAGE_FIELD -> errorMessage = xcp.textOrNull() - EXECUTION_ID_FIELD -> executionId = xcp.textOrNull() + + STATE_FIELD -> { + state = State.valueOf(xcp.text()) + } + + TRIGGER_NAME_FIELD -> { + triggerName = xcp.text() + } + + START_TIME_FIELD -> { + startTime = requireNotNull(xcp.instant()) + } + + END_TIME_FIELD -> { + endTime = xcp.instant() + } + + LAST_NOTIFICATION_TIME_FIELD -> { + lastNotificationTime = xcp.instant() + } + + ACKNOWLEDGED_TIME_FIELD -> { + acknowledgedTime = xcp.instant() + } + + ERROR_MESSAGE_FIELD -> { + errorMessage = xcp.textOrNull() + } + + EXECUTION_ID_FIELD -> { + executionId = xcp.textOrNull() + } + ASSOCIATED_ALERT_IDS_FIELD -> { ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { associatedAlertIds.add(xcp.text()) } } + ALERT_HISTORY_FIELD -> { ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { errorHistory.add(AlertError.parse(xcp)) } } - SEVERITY_FIELD -> severity = xcp.text() + + SEVERITY_FIELD -> { + severity = xcp.text() + } + ACTION_EXECUTION_RESULTS_FIELD -> { ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { actionExecutionResults.add(ActionExecutionResult.parse(xcp)) } } + AggregationResultBucket.CONFIG_NAME -> { // If an Alert with aggAlertBucket contents is indexed into the alerts index first, then // that field will be added to the mappings. // In this case, that field will default to null when it isn't present for Alerts created by Query-Level Monitors // (even though the toXContent doesn't output the field) so null is being accounted for here. - aggAlertBucket = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { - null - } else { - AggregationResultBucket.parse(xcp) - } + aggAlertBucket = + if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + null + } else { + AggregationResultBucket.parse(xcp) + } } + CLUSTERS_FIELD -> { ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { @@ -534,27 +600,28 @@ data class Alert( workflowId = workflowId, workflowName = workflowName, associatedAlertIds = associatedAlertIds, - clusters = if (clusters.size > 0) clusters else null + clusters = if (clusters.size > 0) clusters else null, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Alert { - return Alert(sin) - } + fun readFrom(sin: StreamInput): Alert = Alert(sin) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return createXContentBuilder(builder, true) - } + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = createXContentBuilder(builder, true) - fun toXContentWithUser(builder: XContentBuilder): XContentBuilder { - return createXContentBuilder(builder, false) - } + fun toXContentWithUser(builder: XContentBuilder): XContentBuilder = createXContentBuilder(builder, false) - private fun createXContentBuilder(builder: XContentBuilder, secure: Boolean): XContentBuilder { - builder.startObject() + private fun createXContentBuilder( + builder: XContentBuilder, + secure: Boolean, + ): XContentBuilder { + builder + .startObject() .field(ALERT_ID_FIELD, id) .field(ALERT_VERSION_FIELD, version) .field(MONITOR_ID_FIELD, monitorId) @@ -570,7 +637,8 @@ data class Alert( builder.optionalUserField(MONITOR_USER_FIELD, monitorUser) } - builder.field(TRIGGER_ID_FIELD, triggerId) + builder + .field(TRIGGER_ID_FIELD, triggerId) .field(TRIGGER_NAME_FIELD, triggerName) .field(FINDING_IDS, findingIds.toTypedArray()) .field(RELATED_DOC_IDS, relatedDocIds.toTypedArray()) @@ -591,8 +659,8 @@ data class Alert( return builder } - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( ACKNOWLEDGED_TIME_FIELD to acknowledgedTime?.toEpochMilli(), ALERT_ID_FIELD to id, ALERT_VERSION_FIELD to version, @@ -611,7 +679,6 @@ data class Alert( PARENTS_BUCKET_PATH to aggregationResultBucket?.parentBucketPath, FINDING_IDS to findingIds.joinToString(","), RELATED_DOC_IDS to relatedDocIds.joinToString(","), - CLUSTERS_FIELD to clusters?.joinToString(",") + CLUSTERS_FIELD to clusters?.joinToString(","), ) - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/BaseAlert.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/BaseAlert.kt index dd9bd4dd..d59dfacd 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/BaseAlert.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/BaseAlert.kt @@ -24,7 +24,6 @@ open class BaseAlert( open val schemaVersion: Int = NO_SCHEMA_VERSION, open val user: User?, open val triggerName: String, - // State will be later moved to this Class (after `monitorBasedAlerts` extend this Class) open val state: Alert.State, open val startTime: Instant, @@ -32,9 +31,9 @@ open class BaseAlert( open val acknowledgedTime: Instant? = null, open val errorMessage: String? = null, open val severity: String, - open val actionExecutionResults: List -) : Writeable, ToXContent { - + open val actionExecutionResults: List, +) : Writeable, + ToXContent { init { if (errorMessage != null) { require((state == Alert.State.DELETED) || (state == Alert.State.ERROR) || (state == Alert.State.AUDIT)) { @@ -48,11 +47,12 @@ open class BaseAlert( id = sin.readString(), version = sin.readLong(), schemaVersion = sin.readInt(), - user = if (sin.readBoolean()) { - User(sin) - } else { - null - }, + user = + if (sin.readBoolean()) { + User(sin) + } else { + null + }, triggerName = sin.readString(), state = sin.readEnum(Alert.State::class.java), startTime = sin.readInstant(), @@ -60,7 +60,7 @@ open class BaseAlert( acknowledgedTime = sin.readOptionalInstant(), errorMessage = sin.readOptionalString(), severity = sin.readString(), - actionExecutionResults = sin.readList(::ActionExecutionResult) + actionExecutionResults = sin.readList(::ActionExecutionResult), ) fun isAcknowledged(): Boolean = (state == Alert.State.ACKNOWLEDGED) @@ -101,7 +101,10 @@ open class BaseAlert( @JvmStatic @JvmOverloads @Throws(IOException::class) - fun parse(xcp: XContentParser, version: Long = NO_VERSION): BaseAlert { + fun parse( + xcp: XContentParser, + version: Long = NO_VERSION, + ): BaseAlert { lateinit var id: String var schemaVersion = NO_SCHEMA_VERSION var version: Long = Versions.NOT_FOUND @@ -118,27 +121,60 @@ open class BaseAlert( val fieldName = xcp.currentName() xcp.nextToken() when (fieldName) { - USER_FIELD -> user = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) null else User.parse(xcp) - ALERT_ID_FIELD -> id = xcp.text() - ALERT_VERSION_FIELD -> version = xcp.longValue() - SCHEMA_VERSION_FIELD -> schemaVersion = xcp.intValue() - TRIGGER_NAME_FIELD -> triggerName = xcp.text() - STATE_FIELD -> state = Alert.State.valueOf(xcp.text()) - ERROR_MESSAGE_FIELD -> errorMessage = xcp.textOrNull() - SEVERITY_FIELD -> severity = xcp.text() + USER_FIELD -> { + user = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) null else User.parse(xcp) + } + + ALERT_ID_FIELD -> { + id = xcp.text() + } + + ALERT_VERSION_FIELD -> { + version = xcp.longValue() + } + + SCHEMA_VERSION_FIELD -> { + schemaVersion = xcp.intValue() + } + + TRIGGER_NAME_FIELD -> { + triggerName = xcp.text() + } + + STATE_FIELD -> { + state = Alert.State.valueOf(xcp.text()) + } + + ERROR_MESSAGE_FIELD -> { + errorMessage = xcp.textOrNull() + } + + SEVERITY_FIELD -> { + severity = xcp.text() + } + ACTION_EXECUTION_RESULTS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { actionExecutionResults.add(ActionExecutionResult.parse(xcp)) } } - START_TIME_FIELD -> startTime = requireNotNull(xcp.instant()) - END_TIME_FIELD -> endTime = requireNotNull(xcp.instant()) - ACKNOWLEDGED_TIME_FIELD -> acknowledgedTime = xcp.instant() + + START_TIME_FIELD -> { + startTime = requireNotNull(xcp.instant()) + } + + END_TIME_FIELD -> { + endTime = requireNotNull(xcp.instant()) + } + + ACKNOWLEDGED_TIME_FIELD -> { + acknowledgedTime = xcp.instant() + } } } @@ -154,26 +190,26 @@ open class BaseAlert( user = user, triggerName = requireNotNull(triggerName), severity = severity, - acknowledgedTime = acknowledgedTime + acknowledgedTime = acknowledgedTime, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Alert { - return Alert(sin) - } + fun readFrom(sin: StreamInput): Alert = Alert(sin) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return createXContentBuilder(builder, true) - } + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = createXContentBuilder(builder, true) - fun toXContentWithUser(builder: XContentBuilder): XContentBuilder { - return createXContentBuilder(builder, false) - } + fun toXContentWithUser(builder: XContentBuilder): XContentBuilder = createXContentBuilder(builder, false) - fun createXContentBuilder(builder: XContentBuilder, secure: Boolean): XContentBuilder { + fun createXContentBuilder( + builder: XContentBuilder, + secure: Boolean, + ): XContentBuilder { if (!secure) { builder.optionalUserField(USER_FIELD, user) } @@ -192,8 +228,8 @@ open class BaseAlert( return builder } - open fun asTemplateArg(): Map { - return mapOf( + open fun asTemplateArg(): Map = + mapOf( ACKNOWLEDGED_TIME_FIELD to acknowledgedTime?.toEpochMilli(), ALERT_ID_FIELD to id, ALERT_VERSION_FIELD to version, @@ -202,7 +238,6 @@ open class BaseAlert( SEVERITY_FIELD to severity, START_TIME_FIELD to startTime.toEpochMilli(), STATE_FIELD to state.toString(), - TRIGGER_NAME_FIELD to triggerName + TRIGGER_NAME_FIELD to triggerName, ) - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTrigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTrigger.kt index bac059f8..d77c850b 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTrigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTrigger.kt @@ -23,36 +23,38 @@ data class BucketLevelTrigger( override val name: String, override val severity: String, val bucketSelector: BucketSelectorExtAggregationBuilder, - override val actions: List + override val actions: List, ) : Trigger { - @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // id sin.readString(), // name sin.readString(), // severity BucketSelectorExtAggregationBuilder(sin), // condition - sin.readList(::Action) // actions + sin.readList(::Action), // actions ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(BUCKET_LEVEL_TRIGGER_FIELD) .field(ID_FIELD, id) .field(NAME_FIELD, name) .field(SEVERITY_FIELD, severity) .startObject(CONDITION_FIELD) bucketSelector.internalXContent(builder, params) - builder.endObject() + builder + .endObject() .field(ACTIONS_FIELD, actions.toTypedArray()) .endObject() .endObject() return builder } - override fun name(): String { - return BUCKET_LEVEL_TRIGGER_FIELD - } + override fun name(): String = BUCKET_LEVEL_TRIGGER_FIELD @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -63,29 +65,26 @@ data class BucketLevelTrigger( out.writeCollection(actions) } - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( ID_FIELD to id, NAME_FIELD to name, SEVERITY_FIELD to severity, ACTIONS_FIELD to actions.map { it.asTemplateArg() }, PARENT_BUCKET_PATH to getParentBucketPath(), - CONDITION_FIELD to mapOf( - SCRIPT_FIELD to mapOf( - SOURCE_FIELD to bucketSelector.script.idOrCode, - LANG_FIELD to bucketSelector.script.lang - ) - ) + CONDITION_FIELD to + mapOf( + SCRIPT_FIELD to + mapOf( + SOURCE_FIELD to bucketSelector.script.idOrCode, + LANG_FIELD to bucketSelector.script.lang, + ), + ), ) - } - fun getParentBucketPath(): String { - return bucketSelector.parentBucketPath - } + fun getParentBucketPath(): String = bucketSelector.parentBucketPath - fun getCondition(): String { - return bucketSelector.script.idOrCode - } + fun getCondition(): String = bucketSelector.script.idOrCode companion object { const val BUCKET_LEVEL_TRIGGER_FIELD = "bucket_level_trigger" @@ -95,11 +94,12 @@ data class BucketLevelTrigger( const val SOURCE_FIELD = "source" const val LANG_FIELD = "lang" - val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Trigger::class.java, - ParseField(BUCKET_LEVEL_TRIGGER_FIELD), - CheckedFunction { parseInner(it) } - ) + val XCONTENT_REGISTRY = + NamedXContentRegistry.Entry( + Trigger::class.java, + ParseField(BUCKET_LEVEL_TRIGGER_FIELD), + CheckedFunction { parseInner(it) }, + ) @JvmStatic @Throws(IOException::class) @@ -116,9 +116,18 @@ data class BucketLevelTrigger( xcp.nextToken() when (fieldName) { - ID_FIELD -> id = xcp.text() - NAME_FIELD -> name = xcp.text() - SEVERITY_FIELD -> severity = xcp.text() + ID_FIELD -> { + id = xcp.text() + } + + NAME_FIELD -> { + name = xcp.text() + } + + SEVERITY_FIELD -> { + severity = xcp.text() + } + CONDITION_FIELD -> { // Using the trigger id as the name in the bucket selector since it is validated for uniqueness within Monitors. // The contents of the trigger definition are round-tripped through parse and toXContent during Monitor creation @@ -126,11 +135,12 @@ data class BucketLevelTrigger( // user submitted a custom trigger id after the condition definition. bucketSelector = BucketSelectorExtAggregationBuilder.parse(id, xcp) } + ACTIONS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { actions.add(Action.parse(xcp)) @@ -144,14 +154,12 @@ data class BucketLevelTrigger( name = requireNotNull(name) { "Trigger name is null" }, severity = requireNotNull(severity) { "Trigger severity is null" }, bucketSelector = requireNotNull(bucketSelector) { "Trigger condition is null" }, - actions = requireNotNull(actions) { "Trigger actions are null" } + actions = requireNotNull(actions) { "Trigger actions are null" }, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): BucketLevelTrigger { - return BucketLevelTrigger(sin) - } + fun readFrom(sin: StreamInput): BucketLevelTrigger = BucketLevelTrigger(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTriggerRunResult.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTriggerRunResult.kt index 34328ca2..b3c1e197 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTriggerRunResult.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTriggerRunResult.kt @@ -15,30 +15,33 @@ data class BucketLevelTriggerRunResult( override var triggerName: String, override var error: Exception? = null, var aggregationResultBuckets: Map, - var actionResultsMap: MutableMap> = mutableMapOf() + var actionResultsMap: MutableMap> = mutableMapOf(), ) : TriggerRunResult(triggerName, error) { - @Throws(IOException::class) @Suppress("UNCHECKED_CAST") constructor(sin: StreamInput) : this( sin.readString(), sin.readException() as Exception?, // error sin.readMap(StreamInput::readString, ::AggregationResultBucket), - sin.readMap() as MutableMap> + sin.readMap() as MutableMap>, ) - override fun internalXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder + override fun internalXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder .field(AGG_RESULT_BUCKETS, aggregationResultBuckets) .field(ACTIONS_RESULTS, actionResultsMap as Map) - } @Throws(IOException::class) @Suppress("UNCHECKED_CAST") override fun writeTo(out: StreamOutput) { super.writeTo(out) out.writeMap(aggregationResultBuckets, StreamOutput::writeString) { - valueOut: StreamOutput, aggResultBucket: AggregationResultBucket -> + valueOut: StreamOutput, + aggResultBucket: AggregationResultBucket, + -> aggResultBucket.writeTo(valueOut) } out.writeMap(actionResultsMap as Map) @@ -50,8 +53,6 @@ data class BucketLevelTriggerRunResult( @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): TriggerRunResult { - return BucketLevelTriggerRunResult(sin) - } + fun readFrom(sin: StreamInput): TriggerRunResult = BucketLevelTriggerRunResult(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedAlertTrigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedAlertTrigger.kt index c56ce856..a6327f36 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedAlertTrigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedAlertTrigger.kt @@ -23,20 +23,23 @@ data class ChainedAlertTrigger( override val name: String, override val severity: String, override val actions: List, - val condition: Script + val condition: Script, ) : Trigger { - @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // id sin.readString(), // name sin.readString(), // severity sin.readList(::Action), // actions - Script(sin) + Script(sin), ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(CHAINED_ALERT_TRIGGER_FIELD) .field(ID_FIELD, id) .field(NAME_FIELD, name) @@ -50,19 +53,16 @@ data class ChainedAlertTrigger( return builder } - override fun name(): String { - return CHAINED_ALERT_TRIGGER_FIELD - } + override fun name(): String = CHAINED_ALERT_TRIGGER_FIELD /** Returns a representation of the trigger suitable for passing into painless and mustache scripts. */ - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( ID_FIELD to id, NAME_FIELD to name, SEVERITY_FIELD to severity, - ACTIONS_FIELD to actions.map { it.asTemplateArg() } + ACTIONS_FIELD to actions.map { it.asTemplateArg() }, ) - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -79,11 +79,12 @@ data class ChainedAlertTrigger( const val SCRIPT_FIELD = "script" const val QUERY_IDS_FIELD = "query_ids" - val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Trigger::class.java, - ParseField(CHAINED_ALERT_TRIGGER_FIELD), - CheckedFunction { parseInner(it) } - ) + val XCONTENT_REGISTRY = + NamedXContentRegistry.Entry( + Trigger::class.java, + ParseField(CHAINED_ALERT_TRIGGER_FIELD), + CheckedFunction { parseInner(it) }, + ) @JvmStatic @Throws(IOException::class) @@ -107,9 +108,18 @@ data class ChainedAlertTrigger( xcp.nextToken() when (fieldName) { - ID_FIELD -> id = xcp.text() - NAME_FIELD -> name = xcp.text() - SEVERITY_FIELD -> severity = xcp.text() + ID_FIELD -> { + id = xcp.text() + } + + NAME_FIELD -> { + name = xcp.text() + } + + SEVERITY_FIELD -> { + severity = xcp.text() + } + CONDITION_FIELD -> { xcp.nextToken() condition = Script.parse(xcp) @@ -118,11 +128,12 @@ data class ChainedAlertTrigger( } xcp.nextToken() } + ACTIONS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { actions.add(Action.parse(xcp)) @@ -137,14 +148,12 @@ data class ChainedAlertTrigger( severity = requireNotNull(severity) { "Trigger severity is null" }, condition = requireNotNull(condition) { "Trigger condition is null" }, actions = requireNotNull(actions) { "Trigger actions are null" }, - id = requireNotNull(id) { "Trigger id is null." } + id = requireNotNull(id) { "Trigger id is null." }, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): ChainedAlertTrigger { - return ChainedAlertTrigger(sin) - } + fun readFrom(sin: StreamInput): ChainedAlertTrigger = ChainedAlertTrigger(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedAlertTriggerRunResult.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedAlertTriggerRunResult.kt index 015762cf..1dfeb14c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedAlertTriggerRunResult.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedAlertTriggerRunResult.kt @@ -19,9 +19,8 @@ data class ChainedAlertTriggerRunResult( var triggered: Boolean, override var error: Exception?, var actionResults: MutableMap = mutableMapOf(), - val associatedAlertIds: Set + val associatedAlertIds: Set, ) : TriggerRunResult(triggerName, error) { - @Throws(IOException::class) @Suppress("UNCHECKED_CAST") constructor(sin: StreamInput) : this( @@ -29,7 +28,7 @@ data class ChainedAlertTriggerRunResult( error = sin.readException(), triggered = sin.readBoolean(), actionResults = sin.readMap() as MutableMap, - associatedAlertIds = sin.readStringList().toSet() + associatedAlertIds = sin.readStringList().toSet(), ) override fun alertError(): AlertError? { @@ -44,7 +43,10 @@ data class ChainedAlertTriggerRunResult( return null } - override fun internalXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun internalXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { if (error is ScriptException) error = Exception((error as ScriptException).toJsonString(), error) return builder .field("triggered", triggered) @@ -62,8 +64,6 @@ data class ChainedAlertTriggerRunResult( companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): TriggerRunResult { - return ChainedAlertTriggerRunResult(sin) - } + fun readFrom(sin: StreamInput): TriggerRunResult = ChainedAlertTriggerRunResult(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedMonitorFindings.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedMonitorFindings.kt index a1b6435a..49bf4a74 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedMonitorFindings.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedMonitorFindings.kt @@ -11,15 +11,15 @@ import org.opensearch.core.xcontent.XContentParserUtils import java.io.IOException import java.util.Collections +// TODO - Remove the class and move the monitorId to Delegate (as a chainedMonitorId property) if this class won't be updated by adding new properties + /** * Context passed in delegate monitor to filter data matched by a list of monitors based on the findings of the given monitor ids. */ -// TODO - Remove the class and move the monitorId to Delegate (as a chainedMonitorId property) if this class won't be updated by adding new properties data class ChainedMonitorFindings( val monitorId: String? = null, - val monitorIds: List = emptyList() // if monitorId field is non-null it would be given precendence for BWC + val monitorIds: List = emptyList(), // if monitorId field is non-null it would be given precendence for BWC ) : BaseModel { - init { require(!(monitorId.isNullOrBlank() && monitorIds.isEmpty())) { "at least one of fields, 'monitorIds' and 'monitorId' should be provided" @@ -34,16 +34,15 @@ data class ChainedMonitorFindings( @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readOptionalString(), // monitorId - Collections.unmodifiableList(sin.readStringList()) + Collections.unmodifiableList(sin.readStringList()), ) @Suppress("UNCHECKED_CAST") - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( MONITOR_ID_FIELD to monitorId, - MONITOR_IDS_FIELD to monitorIds + MONITOR_IDS_FIELD to monitorIds, ) as Map - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -51,8 +50,12 @@ data class ChainedMonitorFindings( out.writeStringCollection(monitorIds) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field(MONITOR_ID_FIELD, monitorId) .field(MONITOR_IDS_FIELD, monitorIds) .endObject() @@ -84,7 +87,7 @@ data class ChainedMonitorFindings( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { monitorIds.add(xcp.text()) @@ -97,8 +100,6 @@ data class ChainedMonitorFindings( @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): ChainedMonitorFindings { - return ChainedMonitorFindings(sin) - } + fun readFrom(sin: StreamInput): ChainedMonitorFindings = ChainedMonitorFindings(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInput.kt index d4b39657..2e1fe6d9 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInput.kt @@ -25,7 +25,7 @@ data class ClusterMetricsInput( var path: String, var pathParams: String = "", var url: String, - var clusters: List = listOf() + var clusters: List = listOf(), ) : Input { val clusterMetricType: ClusterMetricType val constructedUri: URI @@ -73,11 +73,15 @@ data class ClusterMetricsInput( constructor(sin: StreamInput) : this( sin.readString(), // path sin.readString(), // path params - sin.readString() // url + sin.readString(), // url ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .startObject(URI_FIELD) .field(API_TYPE_FIELD, clusterMetricType) .field(PATH_FIELD, path) @@ -86,11 +90,8 @@ data class ClusterMetricsInput( .field(CLUSTERS_FIELD, clusters) .endObject() .endObject() - } - override fun name(): String { - return URI_FIELD - } + override fun name(): String = URI_FIELD override fun writeTo(out: StreamOutput) { out.writeString(clusterMetricType.toString()) @@ -131,14 +132,23 @@ data class ClusterMetricsInput( val fieldName = xcp.currentName() xcp.nextToken() when (fieldName) { - PATH_FIELD -> path = xcp.text() - PATH_PARAMS_FIELD -> pathParams = xcp.text() - URL_FIELD -> url = xcp.text() + PATH_FIELD -> { + path = xcp.text() + } + + PATH_PARAMS_FIELD -> { + pathParams = xcp.text() + } + + URL_FIELD -> { + url = xcp.text() + } + CLUSTERS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) clusters.add(xcp.text()) } @@ -154,8 +164,8 @@ data class ClusterMetricsInput( * @return The [URI] constructed from [url] if it's defined; * otherwise a [URI] constructed from the provided [URI] fields. */ - private fun toConstructedUri(): URI { - return if (url.isEmpty()) { + private fun toConstructedUri(): URI = + if (url.isEmpty()) { constructUrlFromInputs() } else { try { @@ -164,7 +174,6 @@ data class ClusterMetricsInput( throw IllegalArgumentException("Invalid URL syntax.") } } - } /** * Isolates just the path parameters from the [ClusterMetricsInput] URI. @@ -190,7 +199,8 @@ data class ClusterMetricsInput( ILLEGAL_PATH_PARAMETER_CHARACTERS.forEach { character -> if (pathParams.contains(character)) { throw IllegalArgumentException( - "The provided path parameters contain invalid characters or spaces. Please omit: " + ILLEGAL_PATH_PARAMETER_CHARACTERS.joinToString(" ") + "The provided path parameters contain invalid characters or spaces. Please omit: " + + ILLEGAL_PATH_PARAMETER_CHARACTERS.joinToString(" "), ) } } @@ -214,7 +224,8 @@ data class ClusterMetricsInput( */ private fun findApiType(uriPath: String): ClusterMetricType { var apiType = ClusterMetricType.BLANK - ClusterMetricType.values() + ClusterMetricType + .values() .filter { option -> option != ClusterMetricType.BLANK } .forEach { option -> if (uriPath.startsWith(option.prependPath) || uriPath.startsWith(option.defaultPath)) { @@ -232,21 +243,20 @@ data class ClusterMetricsInput( * @return The constructed [URI]. */ private fun constructUrlFromInputs(): URI { - /** - * this try-catch block is required due to a httpcomponents 5.1.x library issue - * it auto encodes path params in the url. - */ + // This try-catch block is required due to a httpcomponents 5.1.x library issue + // it auto encodes path params in the url. return try { val formattedPath = if (path.startsWith("/") || path.isBlank()) path else "/$path" val formattedPathParams = if (pathParams.startsWith("/") || pathParams.isBlank()) pathParams else "/$pathParams" val uriBuilder = URIBuilder("$SUPPORTED_SCHEME://$SUPPORTED_HOST:$SUPPORTED_PORT$formattedPath$formattedPathParams") uriBuilder.build() } catch (ex: URISyntaxException) { - val uriBuilder = URIBuilder() - .setScheme(SUPPORTED_SCHEME) - .setHost(SUPPORTED_HOST) - .setPort(SUPPORTED_PORT) - .setPath(path + pathParams) + val uriBuilder = + URIBuilder() + .setScheme(SUPPORTED_SCHEME) + .setHost(SUPPORTED_HOST) + .setPort(SUPPORTED_PORT) + .setPath(path + pathParams) try { uriBuilder.build() } catch (e: URISyntaxException) { @@ -275,18 +285,14 @@ data class ClusterMetricsInput( * Helper function to confirm at least [url], or required URI component fields are defined. * @return TRUE if at least either [url] or the other components are provided; otherwise FALSE. */ - private fun validateFields(): Boolean { - return url.isNotEmpty() || validateFieldsNotEmpty() - } + private fun validateFields(): Boolean = url.isNotEmpty() || validateFieldsNotEmpty() /** * Confirms that required URI component fields are defined. * Only validating path for now, as that's the only required field. * @return TRUE if all those fields are defined; otherwise FALSE. */ - private fun validateFieldsNotEmpty(): Boolean { - return path.isNotEmpty() - } + private fun validateFieldsNotEmpty(): Boolean = path.isNotEmpty() /** * An enum class to quickly reference various supported API. @@ -296,7 +302,7 @@ data class ClusterMetricsInput( val prependPath: String, val appendPath: String, val supportsPathParams: Boolean, - val requiresPathParams: Boolean + val requiresPathParams: Boolean, ) { BLANK("", "", "", false, false), CAT_INDICES( @@ -304,77 +310,76 @@ data class ClusterMetricsInput( "/_cat/indices", "", true, - false + false, ), CAT_PENDING_TASKS( "/_cat/pending_tasks", "/_cat/pending_tasks", "", false, - false + false, ), CAT_RECOVERY( "/_cat/recovery", "/_cat/recovery", "", true, - false + false, ), CAT_SHARDS( "/_cat/shards", "/_cat/shards", "", true, - false + false, ), CAT_SNAPSHOTS( "/_cat/snapshots", "/_cat/snapshots", "", true, - true + true, ), CAT_TASKS( "/_cat/tasks", "/_cat/tasks", "", false, - false + false, ), CLUSTER_HEALTH( "/_cluster/health", "/_cluster/health", "", true, - false + false, ), CLUSTER_SETTINGS( "/_cluster/settings", "/_cluster/settings", "", false, - false + false, ), CLUSTER_STATS( "/_cluster/stats", "/_cluster/stats", "", true, - false + false, ), NODES_STATS( "/_nodes/stats", "/_nodes", "", false, - false - ); + false, + ), + ; /** * @return TRUE if the [ClusterMetricType] is [BLANK]; otherwise FALSE. */ - fun isBlank(): Boolean { - return this === BLANK - } + fun isBlank(): Boolean = this === BLANK } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsTriggerRunResult.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsTriggerRunResult.kt index d3af9be3..be3b6478 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsTriggerRunResult.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsTriggerRunResult.kt @@ -21,14 +21,13 @@ data class ClusterMetricsTriggerRunResult( override var triggered: Boolean, override var error: Exception?, override var actionResults: MutableMap = mutableMapOf(), - var clusterTriggerResults: List = listOf() + var clusterTriggerResults: List = listOf(), ) : QueryLevelTriggerRunResult( - triggerName = triggerName, - error = error, - triggered = triggered, - actionResults = actionResults -) { - + triggerName = triggerName, + error = error, + triggered = triggered, + actionResults = actionResults, + ) { @Throws(IOException::class) @Suppress("UNCHECKED_CAST") constructor(sin: StreamInput) : this( @@ -36,7 +35,7 @@ data class ClusterMetricsTriggerRunResult( error = sin.readException(), triggered = sin.readBoolean(), actionResults = sin.readMap() as MutableMap, - clusterTriggerResults = sin.readList((ClusterTriggerResult)::readFrom) + clusterTriggerResults = sin.readList((ClusterTriggerResult)::readFrom), ) override fun alertError(): AlertError? { @@ -51,7 +50,10 @@ data class ClusterMetricsTriggerRunResult( return null } - override fun internalXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun internalXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { if (error is ScriptException) error = Exception((error as ScriptException).toJsonString(), error) builder .field(TRIGGERED_FIELD, triggered) @@ -77,22 +79,25 @@ data class ClusterMetricsTriggerRunResult( data class ClusterTriggerResult( val cluster: String, - val triggered: Boolean - ) : ToXContentObject, Writeable { - + val triggered: Boolean, + ) : ToXContentObject, + Writeable { @Throws(IOException::class) constructor(sin: StreamInput) : this( cluster = sin.readString(), - triggered = sin.readBoolean() + triggered = sin.readBoolean(), ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .startObject(cluster) .field(TRIGGERED_FIELD, triggered) .endObject() .endObject() - } override fun writeTo(out: StreamOutput) { out.writeString(cluster) @@ -102,9 +107,7 @@ data class ClusterMetricsTriggerRunResult( companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): ClusterTriggerResult { - return ClusterTriggerResult(sin) - } + fun readFrom(sin: StreamInput): ClusterTriggerResult = ClusterTriggerResult(sin) } } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Comment.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Comment.kt index 45c007e3..664122fd 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Comment.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Comment.kt @@ -23,8 +23,9 @@ data class Comment( val content: String, val createdTime: Instant, val lastUpdatedTime: Instant?, - val user: User? -) : Writeable, ToXContent { + val user: User?, +) : Writeable, + ToXContent { @Throws(IOException::class) constructor(sin: StreamInput) : this( id = sin.readString(), @@ -33,7 +34,7 @@ data class Comment( content = sin.readString(), createdTime = sin.readInstant(), lastUpdatedTime = sin.readOptionalInstant(), - user = if (sin.readBoolean()) User(sin) else null + user = if (sin.readBoolean()) User(sin) else null, ) constructor( @@ -41,14 +42,14 @@ data class Comment( entityType: String, content: String, createdTime: Instant, - user: User? + user: User?, ) : this ( entityId = entityId, entityType = entityType, content = content, createdTime = createdTime, lastUpdatedTime = null, - user = user + user = user, ) @Throws(IOException::class) @@ -63,30 +64,32 @@ data class Comment( user?.writeTo(out) } - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( _ID to id, ENTITY_ID_FIELD to entityId, ENTITY_TYPE_FIELD to entityType, COMMENT_CONTENT_FIELD to content, COMMENT_CREATED_TIME_FIELD to createdTime, COMMENT_LAST_UPDATED_TIME_FIELD to lastUpdatedTime, - COMMENT_USER_FIELD to user?.name + COMMENT_USER_FIELD to user?.name, ) - } // used to create the Comment JSON object for an API response (displayed to user) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return createXContentBuilder(builder, false) - } + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = createXContentBuilder(builder, false) // used to create the Comment JSON object for indexing a doc into an index (not displayed to user) - fun toXContentWithUser(builder: XContentBuilder): XContentBuilder { - return createXContentBuilder(builder, true) - } - - private fun createXContentBuilder(builder: XContentBuilder, includeFullUser: Boolean): XContentBuilder { - builder.startObject() + fun toXContentWithUser(builder: XContentBuilder): XContentBuilder = createXContentBuilder(builder, true) + + private fun createXContentBuilder( + builder: XContentBuilder, + includeFullUser: Boolean, + ): XContentBuilder { + builder + .startObject() .field(ENTITY_ID_FIELD, entityId) .field(ENTITY_TYPE_FIELD, entityType) .field(COMMENT_CONTENT_FIELD, content) @@ -117,7 +120,10 @@ data class Comment( @JvmStatic @JvmOverloads @Throws(IOException::class) - fun parse(xcp: XContentParser, id: String = NO_ID): Comment { + fun parse( + xcp: XContentParser, + id: String = NO_ID, + ): Comment { lateinit var entityId: String lateinit var entityType: String var content = "" @@ -131,17 +137,34 @@ data class Comment( xcp.nextToken() when (fieldName) { - ENTITY_ID_FIELD -> entityId = xcp.text() - ENTITY_TYPE_FIELD -> entityType = xcp.text() - COMMENT_CONTENT_FIELD -> content = xcp.text() - COMMENT_CREATED_TIME_FIELD -> createdTime = requireNotNull(xcp.instant()) - COMMENT_LAST_UPDATED_TIME_FIELD -> lastUpdatedTime = xcp.instant() - COMMENT_USER_FIELD -> - user = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { - null - } else { - User.parse(xcp) - } + ENTITY_ID_FIELD -> { + entityId = xcp.text() + } + + ENTITY_TYPE_FIELD -> { + entityType = xcp.text() + } + + COMMENT_CONTENT_FIELD -> { + content = xcp.text() + } + + COMMENT_CREATED_TIME_FIELD -> { + createdTime = requireNotNull(xcp.instant()) + } + + COMMENT_LAST_UPDATED_TIME_FIELD -> { + lastUpdatedTime = xcp.instant() + } + + COMMENT_USER_FIELD -> { + user = + if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + null + } else { + User.parse(xcp) + } + } } } @@ -152,14 +175,12 @@ data class Comment( content = content, createdTime = createdTime, lastUpdatedTime = lastUpdatedTime, - user = user + user = user, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Comment { - return Comment(sin) - } + fun readFrom(sin: StreamInput): Comment = Comment(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/CompositeInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/CompositeInput.kt index 0f1e3e12..5100cfc9 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/CompositeInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/CompositeInput.kt @@ -12,26 +12,29 @@ import org.opensearch.core.xcontent.XContentParserUtils import java.io.IOException data class CompositeInput( - val sequence: Sequence + val sequence: Sequence, ) : WorkflowInput { @Throws(IOException::class) constructor(sin: StreamInput) : this( - Sequence(sin) + Sequence(sin), ) - fun asTemplateArg(): Map { - return mapOf( - SEQUENCE_FIELD to sequence + fun asTemplateArg(): Map = + mapOf( + SEQUENCE_FIELD to sequence, ) - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { sequence.writeTo(out) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(COMPOSITE_INPUT_FIELD) .field(SEQUENCE_FIELD, sequence) .endObject() @@ -39,23 +42,20 @@ data class CompositeInput( return builder } - override fun name(): String { - return COMPOSITE_INPUT_FIELD - } + override fun name(): String = COMPOSITE_INPUT_FIELD - fun getMonitorIds(): List { - return sequence.delegates.map { delegate -> delegate.monitorId } - } + fun getMonitorIds(): List = sequence.delegates.map { delegate -> delegate.monitorId } companion object { const val COMPOSITE_INPUT_FIELD = "composite_input" const val SEQUENCE_FIELD = "sequence" - val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - WorkflowInput::class.java, - ParseField(COMPOSITE_INPUT_FIELD), - CheckedFunction { CompositeInput.parse(it) } - ) + val XCONTENT_REGISTRY = + NamedXContentRegistry.Entry( + WorkflowInput::class.java, + ParseField(COMPOSITE_INPUT_FIELD), + CheckedFunction { CompositeInput.parse(it) }, + ) @JvmStatic @Throws(IOException::class) @@ -78,8 +78,6 @@ data class CompositeInput( @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): CompositeInput { - return CompositeInput(sin) - } + fun readFrom(sin: StreamInput): CompositeInput = CompositeInput(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/CorrelationAlert.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/CorrelationAlert.kt index f0a56a86..2a22d819 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/CorrelationAlert.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/CorrelationAlert.kt @@ -11,7 +11,6 @@ import java.io.IOException import java.time.Instant class CorrelationAlert : BaseAlert { - // CorrelationAlert-specific properties val correlatedFindingIds: List val correlationRuleId: String @@ -32,7 +31,7 @@ class CorrelationAlert : BaseAlert { acknowledgedTime: Instant?, errorMessage: String?, severity: String, - actionExecutionResults: List + actionExecutionResults: List, ) : super( id = id, version = version, @@ -45,7 +44,7 @@ class CorrelationAlert : BaseAlert { acknowledgedTime = acknowledgedTime, errorMessage = errorMessage, severity = severity, - actionExecutionResults = actionExecutionResults + actionExecutionResults = actionExecutionResults, ) { this.correlatedFindingIds = correlatedFindingIds this.correlationRuleId = correlationRuleId @@ -60,13 +59,18 @@ class CorrelationAlert : BaseAlert { } // Override to include CorrelationAlert specific fields - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startArray(CORRELATED_FINDING_IDS) correlatedFindingIds.forEach { id -> builder.value(id) } - builder.endArray() + builder + .endArray() .field(CORRELATION_RULE_ID, correlationRuleId) .field(CORRELATION_RULE_NAME, correlationRuleName) super.toXContentWithUser(builder) @@ -81,15 +85,18 @@ class CorrelationAlert : BaseAlert { out.writeString(correlationRuleId) out.writeString(correlationRuleName) } + override fun asTemplateArg(): Map { val superTemplateArgs = super.asTemplateArg() - val correlationSpecificArgs = mapOf( - CORRELATED_FINDING_IDS to correlatedFindingIds, - CORRELATION_RULE_ID to correlationRuleId, - CORRELATION_RULE_NAME to correlationRuleName - ) + val correlationSpecificArgs = + mapOf( + CORRELATED_FINDING_IDS to correlatedFindingIds, + CORRELATION_RULE_ID to correlationRuleId, + CORRELATION_RULE_NAME to correlationRuleName, + ) return superTemplateArgs + correlationSpecificArgs } + companion object { const val CORRELATED_FINDING_IDS = "correlated_finding_ids" const val CORRELATION_RULE_ID = "correlation_rule_id" @@ -97,7 +104,11 @@ class CorrelationAlert : BaseAlert { @JvmStatic @Throws(IOException::class) - fun parse(xcp: XContentParser, id: String = NO_ID, version: Long = NO_VERSION): CorrelationAlert { + fun parse( + xcp: XContentParser, + id: String = NO_ID, + version: Long = NO_VERSION, + ): CorrelationAlert { // Parse additional CorrelationAlert-specific fields val correlatedFindingIds: MutableList = mutableListOf() var correlationRuleId: String? = null @@ -114,8 +125,14 @@ class CorrelationAlert : BaseAlert { correlatedFindingIds.add(xcp.text()) } } - CORRELATION_RULE_ID -> correlationRuleId = xcp.text() - CORRELATION_RULE_NAME -> correlationRuleName = xcp.text() + + CORRELATION_RULE_ID -> { + correlationRuleId = xcp.text() + } + + CORRELATION_RULE_NAME -> { + correlationRuleName = xcp.text() + } } } @@ -135,7 +152,7 @@ class CorrelationAlert : BaseAlert { acknowledgedTime = unifiedAlert.acknowledgedTime, errorMessage = unifiedAlert.errorMessage, severity = requireNotNull(unifiedAlert.severity), - actionExecutionResults = unifiedAlert.actionExecutionResults + actionExecutionResults = unifiedAlert.actionExecutionResults, ) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/DataSources.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/DataSources.kt index 7757a0b3..2b7b51e0 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/DataSources.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/DataSources.kt @@ -13,39 +13,29 @@ import java.io.IOException data class DataSources( /** Configures a custom query index name for the monitor. Creates a new index if index with given name not present.*/ val queryIndex: String = ScheduledJob.DOC_LEVEL_QUERIES_INDEX, - /** Configures a custom index to store findings for a monitor. Creates a new index if index with given name not present. * If index is pre-existing, mapping is updated*/ - val findingsIndex: String = ".opensearch-alerting-finding-history-write", // AlertIndices.FINDING_HISTORY_WRITE_INDEX - + val findingsIndex: String = ".opensearch-alerting-finding-history-write", /** Configures a custom index pattern for findingsIndex alias.*/ - val findingsIndexPattern: String? = "<.opensearch-alerting-finding-history-{now/d}-1>", // AlertIndices.FINDING_HISTORY_INDEX_PATTERN - + val findingsIndexPattern: String? = "<.opensearch-alerting-finding-history-{now/d}-1>", /** Configures a custom index to store alerts for a monitor. Creates a new index if index with given name not present. * If index is pre-existing, mapping is updated. */ - val alertsIndex: String = ".opendistro-alerting-alerts", // AlertIndices.ALERT_INDEX - + val alertsIndex: String = ".opendistro-alerting-alerts", /** Configures a custom index alias to store historic alerts for a monitor.*/ - val alertsHistoryIndex: String? = ".opendistro-alerting-alert-history-write", // AlertIndices.ALERT_HISTORY_WRITE_INDEX - + val alertsHistoryIndex: String? = ".opendistro-alerting-alert-history-write", /** Configures a custom index pattern for alertHistoryIndex alias.*/ - val alertsHistoryIndexPattern: String? = "<.opendistro-alerting-alert-history-{now/d}-1>", // AlertIndices.ALERT_HISTORY_INDEX_PATTERN - + val alertsHistoryIndexPattern: String? = "<.opendistro-alerting-alert-history-{now/d}-1>", /** Configures a custom index alias to store comments associated with alerts.*/ - val commentsIndex: String? = DEFAULT_COMMENTS_INDEX, // CommentsIndices.COMMENTS_HISTORY_WRITE_INDEX - + val commentsIndex: String? = DEFAULT_COMMENTS_INDEX, /** Configures a custom index pattern for commentsIndex alias.*/ - val commentsIndexPattern: String? = DEFAULT_COMMENTS_INDEX_PATTERN, // CommentsIndices.COMMENTS_HISTORY_INDEX_PATTERN - + val commentsIndexPattern: String? = DEFAULT_COMMENTS_INDEX_PATTERN, /** Configures custom mappings by field type for query index. * Custom query index mappings are configurable, only if a custom query index is configured too. */ val queryIndexMappingsByType: Map> = mapOf(), - /** Configures flag to enable or disable creating and storing findings. */ - val findingsEnabled: Boolean? = false - -) : Writeable, ToXContentObject { - + val findingsEnabled: Boolean? = false, +) : Writeable, + ToXContentObject { init { require(queryIndex.isNotEmpty()) { "Query index cannot be empty" @@ -64,7 +54,7 @@ data class DataSources( queryIndexMappingsByType.size == 1 && queryIndexMappingsByType.containsKey("text") && queryIndexMappingsByType.get("text")?.size == 1 && - queryIndexMappingsByType.get("text")!!.containsKey("analyzer") + queryIndexMappingsByType.get("text")!!.containsKey("analyzer"), ) { "Custom query index mappings are currently configurable only for 'text' fields and mapping parameter can only be 'analyzer'" } @@ -83,7 +73,7 @@ data class DataSources( commentsIndex = sin.readOptionalString(), commentsIndexPattern = sin.readOptionalString(), queryIndexMappingsByType = sin.readMap() as Map>, - findingsEnabled = sin.readOptionalBoolean() + findingsEnabled = sin.readOptionalBoolean(), ) constructor( @@ -94,7 +84,7 @@ data class DataSources( alertsHistoryIndex: String?, alertsHistoryIndexPattern: String?, queryIndexMappingsByType: Map>, - findingsEnabled: Boolean? + findingsEnabled: Boolean?, ) : this( queryIndex = queryIndex, findingsIndex = findingsIndex, @@ -105,12 +95,12 @@ data class DataSources( commentsIndex = DEFAULT_COMMENTS_INDEX, commentsIndexPattern = DEFAULT_COMMENTS_INDEX_PATTERN, queryIndexMappingsByType = queryIndexMappingsByType, - findingsEnabled = findingsEnabled + findingsEnabled = findingsEnabled, ) @Suppress("UNCHECKED_CAST") - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( QUERY_INDEX_FIELD to queryIndex, FINDINGS_INDEX_FIELD to findingsIndex, FINDINGS_INDEX_PATTERN_FIELD to findingsIndexPattern, @@ -120,11 +110,13 @@ data class DataSources( COMMENTS_INDEX_FIELD to commentsIndex, COMMENTS_INDEX_PATTERN_FIELD to commentsIndexPattern, QUERY_INDEX_MAPPINGS_BY_TYPE to queryIndexMappingsByType, - FINDINGS_ENABLED_FIELD to findingsEnabled + FINDINGS_ENABLED_FIELD to findingsEnabled, ) - } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { builder.startObject() builder.field(QUERY_INDEX_FIELD, queryIndex) builder.field(FINDINGS_INDEX_FIELD, findingsIndex) @@ -198,7 +190,7 @@ data class DataSources( commentsIndex = commentsIndex, commentsIndexPattern = commentsIndexPattern, queryIndexMappingsByType = queryIndexMappingsByType, - findingsEnabled = findingsEnabled + findingsEnabled = findingsEnabled, ) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Delegate.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Delegate.kt index e32ae78d..165bc67c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Delegate.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Delegate.kt @@ -28,9 +28,8 @@ data class Delegate( * Keeps the track of the previously executed monitor in a chain list. * Used for pre-filtering by getting the findings doc ids for the given monitor */ - val chainedMonitorFindings: ChainedMonitorFindings? = null + val chainedMonitorFindings: ChainedMonitorFindings? = null, ) : BaseModel { - init { validateId(monitorId) validateOrder(order) @@ -40,19 +39,19 @@ data class Delegate( constructor(sin: StreamInput) : this( order = sin.readInt(), monitorId = sin.readString(), - chainedMonitorFindings = if (sin.readBoolean()) { - ChainedMonitorFindings(sin) - } else { - null - } + chainedMonitorFindings = + if (sin.readBoolean()) { + ChainedMonitorFindings(sin) + } else { + null + }, ) - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( ORDER_FIELD to order, - MONITOR_ID_FIELD to monitorId + MONITOR_ID_FIELD to monitorId, ) - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -62,8 +61,12 @@ data class Delegate( chainedMonitorFindings?.writeTo(out) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field(ORDER_FIELD, order) .field(MONITOR_ID_FIELD, monitorId) if (chainedMonitorFindings != null) { @@ -95,10 +98,12 @@ data class Delegate( order = xcp.intValue() validateOrder(order) } + MONITOR_ID_FIELD -> { monitorId = xcp.text() validateId(monitorId) } + CHAINED_FINDINGS_FIELD -> { chainedMonitorFindings = ChainedMonitorFindings.parse(xcp) } @@ -109,9 +114,7 @@ data class Delegate( @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Delegate { - return Delegate(sin) - } + fun readFrom(sin: StreamInput): Delegate = Delegate(sin) fun validateOrder(order: Int) { require(order > 0) { "Invalid delgate order" } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInput.kt index 88483f27..1ede9b82 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInput.kt @@ -16,28 +16,24 @@ data class DocLevelMonitorInput( val description: String = NO_DESCRIPTION, val indices: List, val queries: List, - val fanoutEnabled: Boolean? = true + val fanoutEnabled: Boolean? = true, ) : Input { - @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // description sin.readStringList(), // indices sin.readList(::DocLevelQuery), // docLevelQueries - if (sin.version.onOrAfter(Version.V_2_15_0)) sin.readOptionalBoolean() else true // fanoutEnabled + if (sin.version.onOrAfter(Version.V_2_15_0)) sin.readOptionalBoolean() else true, // fanoutEnabled ) - override fun asTemplateArg(): Map { - return mapOf( + override fun asTemplateArg(): Map = + mapOf( DESCRIPTION_FIELD to description, INDICES_FIELD to indices, - QUERIES_FIELD to queries.map { it.asTemplateArg() } + QUERIES_FIELD to queries.map { it.asTemplateArg() }, ) - } - override fun name(): String { - return DOC_LEVEL_INPUT_FIELD - } + override fun name(): String = DOC_LEVEL_INPUT_FIELD @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -49,8 +45,12 @@ data class DocLevelMonitorInput( } } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(DOC_LEVEL_INPUT_FIELD) .field(DESCRIPTION_FIELD, description) .field(INDICES_FIELD, indices.toTypedArray()) @@ -69,11 +69,12 @@ data class DocLevelMonitorInput( const val FANOUT_FIELD = "fan_out_enabled" const val NO_DESCRIPTION = "" - val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Input::class.java, - ParseField(DOC_LEVEL_INPUT_FIELD), - CheckedFunction { parse(it) } - ) + val XCONTENT_REGISTRY = + NamedXContentRegistry.Entry( + Input::class.java, + ParseField(DOC_LEVEL_INPUT_FIELD), + CheckedFunction { parse(it) }, + ) @JvmStatic @Throws(IOException::class) @@ -89,42 +90,53 @@ data class DocLevelMonitorInput( xcp.nextToken() when (fieldName) { - DESCRIPTION_FIELD -> description = xcp.text() + DESCRIPTION_FIELD -> { + description = xcp.text() + } + INDICES_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { indices.add(xcp.text()) } } + QUERIES_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { docLevelQueries.add(DocLevelQuery.parse(xcp)) } } - FANOUT_FIELD -> fanoutEnabled = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { - fanoutEnabled - } else { - xcp.booleanValue() + + FANOUT_FIELD -> { + fanoutEnabled = + if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + fanoutEnabled + } else { + xcp.booleanValue() + } } } } - return DocLevelMonitorInput(description = description, indices = indices, queries = docLevelQueries, fanoutEnabled = fanoutEnabled) + return DocLevelMonitorInput( + description = description, + indices = indices, + queries = docLevelQueries, + fanoutEnabled = fanoutEnabled, + ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): DocLevelMonitorInput { - return DocLevelMonitorInput(sin) - } + fun readFrom(sin: StreamInput): DocLevelMonitorInput = DocLevelMonitorInput(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelQuery.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelQuery.kt index ebba6bf9..16c4a9ce 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelQuery.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelQuery.kt @@ -17,9 +17,8 @@ data class DocLevelQuery( val fields: List, val query: String, val tags: List = mutableListOf(), - val queryFieldNames: List = mutableListOf() + val queryFieldNames: List = mutableListOf(), ) : BaseModel { - init { // Ensure the name and tags have valid characters validateQueryName(name) @@ -35,19 +34,18 @@ data class DocLevelQuery( sin.readStringList(), // fields sin.readString(), // query sin.readStringList(), // tags, - sin.readStringList() // fieldsBeingQueried + sin.readStringList(), // fieldsBeingQueried ) - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( QUERY_ID_FIELD to id, NAME_FIELD to name, FIELDS_FIELD to fields, QUERY_FIELD to query, TAGS_FIELD to tags, - QUERY_FIELD_NAMES_FIELD to queryFieldNames + QUERY_FIELD_NAMES_FIELD to queryFieldNames, ) - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -59,8 +57,12 @@ data class DocLevelQuery( out.writeStringCollection(queryFieldNames) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field(QUERY_ID_FIELD, id) .field(NAME_FIELD, name) .field(FIELDS_FIELD, fields.toTypedArray()) @@ -98,18 +100,24 @@ data class DocLevelQuery( xcp.nextToken() when (fieldName) { - QUERY_ID_FIELD -> id = xcp.text() + QUERY_ID_FIELD -> { + id = xcp.text() + } + NAME_FIELD -> { name = xcp.text() validateQueryName(name) } - QUERY_FIELD -> query = xcp.text() + QUERY_FIELD -> { + query = xcp.text() + } + TAGS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { val tag = xcp.text() @@ -122,7 +130,7 @@ data class DocLevelQuery( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { val field = xcp.text() @@ -134,7 +142,7 @@ data class DocLevelQuery( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { val field = xcp.text() @@ -150,25 +158,24 @@ data class DocLevelQuery( fields = fields, query = query, tags = tags, - queryFieldNames = queryFieldNames + queryFieldNames = queryFieldNames, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): DocLevelQuery { - return DocLevelQuery(sin) - } + fun readFrom(sin: StreamInput): DocLevelQuery = DocLevelQuery(sin) private fun validateQueryTag(stringVal: String) { for (inValidChar in INVALID_CHARACTERS) { if (stringVal.contains(inValidChar)) { throw IllegalArgumentException( - "The query tag, $stringVal, contains an invalid character: [' ','[',']','{','}','(',')']" + "The query tag, $stringVal, contains an invalid character: [' ','[',']','{','}','(',')']", ) } } } + private fun validateQueryName(stringVal: String) { if (!stringVal.matches(QUERY_NAME_REGEX)) { throw IllegalArgumentException("The query name, $stringVal, should be between 1 - 256 characters.") @@ -182,13 +189,13 @@ data class DocLevelQuery( name: String, fields: MutableList, query: String, - tags: MutableList + tags: MutableList, ) : this( id = id, name = name, fields = fields, query = query, tags = tags, - queryFieldNames = emptyList() + queryFieldNames = emptyList(), ) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTrigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTrigger.kt index a1f8b617..788bcf91 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTrigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTrigger.kt @@ -23,20 +23,23 @@ data class DocumentLevelTrigger( override val name: String, override val severity: String, override val actions: List, - val condition: Script + val condition: Script, ) : Trigger { - @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // id sin.readString(), // name sin.readString(), // severity sin.readList(::Action), // actions - Script(sin) + Script(sin), ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(DOCUMENT_LEVEL_TRIGGER_FIELD) .field(ID_FIELD, id) .field(NAME_FIELD, name) @@ -50,25 +53,24 @@ data class DocumentLevelTrigger( return builder } - override fun name(): String { - return DOCUMENT_LEVEL_TRIGGER_FIELD - } + override fun name(): String = DOCUMENT_LEVEL_TRIGGER_FIELD /** Returns a representation of the trigger suitable for passing into painless and mustache scripts. */ - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( ID_FIELD to id, NAME_FIELD to name, SEVERITY_FIELD to severity, ACTIONS_FIELD to actions.map { it.asTemplateArg() }, - CONDITION_FIELD to mapOf( - SCRIPT_FIELD to mapOf( - SOURCE_FIELD to condition.idOrCode, - LANG_FIELD to condition.lang - ) - ) + CONDITION_FIELD to + mapOf( + SCRIPT_FIELD to + mapOf( + SOURCE_FIELD to condition.idOrCode, + LANG_FIELD to condition.lang, + ), + ), ) - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -87,11 +89,12 @@ data class DocumentLevelTrigger( const val SOURCE_FIELD = "source" const val LANG_FIELD = "lang" - val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Trigger::class.java, - ParseField(DOCUMENT_LEVEL_TRIGGER_FIELD), - CheckedFunction { parseInner(it) } - ) + val XCONTENT_REGISTRY = + NamedXContentRegistry.Entry( + Trigger::class.java, + ParseField(DOCUMENT_LEVEL_TRIGGER_FIELD), + CheckedFunction { parseInner(it) }, + ) @JvmStatic @Throws(IOException::class) @@ -116,9 +119,18 @@ data class DocumentLevelTrigger( xcp.nextToken() when (fieldName) { - ID_FIELD -> id = xcp.text() - NAME_FIELD -> name = xcp.text() - SEVERITY_FIELD -> severity = xcp.text() + ID_FIELD -> { + id = xcp.text() + } + + NAME_FIELD -> { + name = xcp.text() + } + + SEVERITY_FIELD -> { + severity = xcp.text() + } + CONDITION_FIELD -> { xcp.nextToken() condition = Script.parse(xcp) @@ -127,21 +139,23 @@ data class DocumentLevelTrigger( } xcp.nextToken() } + QUERY_IDS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { queryIds.add(xcp.text()) } } + ACTIONS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { actions.add(Action.parse(xcp)) @@ -156,14 +170,12 @@ data class DocumentLevelTrigger( severity = requireNotNull(severity) { "Trigger severity is null" }, condition = requireNotNull(condition) { "Trigger condition is null" }, actions = requireNotNull(actions) { "Trigger actions are null" }, - id = requireNotNull(id) { "Trigger id is null." } + id = requireNotNull(id) { "Trigger id is null." }, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): DocumentLevelTrigger { - return DocumentLevelTrigger(sin) - } + fun readFrom(sin: StreamInput): DocumentLevelTrigger = DocumentLevelTrigger(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTriggerRunResult.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTriggerRunResult.kt index 1acb354b..d2d5cb39 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTriggerRunResult.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTriggerRunResult.kt @@ -16,19 +16,21 @@ data class DocumentLevelTriggerRunResult( override var triggerName: String, var triggeredDocs: List, override var error: Exception?, - var actionResultsMap: MutableMap> = mutableMapOf() + var actionResultsMap: MutableMap> = mutableMapOf(), ) : TriggerRunResult(triggerName, error) { - @Throws(IOException::class) @Suppress("UNCHECKED_CAST") constructor(sin: StreamInput) : this( triggerName = sin.readString(), error = sin.readException(), triggeredDocs = sin.readStringList(), - actionResultsMap = readActionResults(sin) + actionResultsMap = readActionResults(sin), ) - override fun internalXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun internalXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { if (error is ScriptException) error = Exception((error as ScriptException).toJsonString(), error) return builder .field("triggeredDocs", triggeredDocs as List) @@ -53,9 +55,7 @@ data class DocumentLevelTriggerRunResult( companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): TriggerRunResult { - return DocumentLevelTriggerRunResult(sin) - } + fun readFrom(sin: StreamInput): TriggerRunResult = DocumentLevelTriggerRunResult(sin) @JvmStatic fun readActionResults(sin: StreamInput): MutableMap> { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Finding.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Finding.kt index 93915358..d8ffe326 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Finding.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Finding.kt @@ -27,9 +27,9 @@ class Finding( * Keeps the track of the workflow-monitor exact execution. * Used for filtering the data when chaining monitors in a workflow. */ - val executionId: String? = null -) : Writeable, ToXContent { - + val executionId: String? = null, +) : Writeable, + ToXContent { constructor( id: String = NO_ID, relatedDocIds: List, @@ -37,7 +37,7 @@ class Finding( monitorName: String, index: String, docLevelQueries: List, - timestamp: Instant + timestamp: Instant, ) : this ( id = id, relatedDocIds = relatedDocIds, @@ -46,7 +46,7 @@ class Finding( index = index, docLevelQueries = docLevelQueries, timestamp = timestamp, - executionId = null + executionId = null, ) @Throws(IOException::class) @@ -59,11 +59,11 @@ class Finding( index = sin.readString(), docLevelQueries = sin.readList((DocLevelQuery)::readFrom), timestamp = sin.readInstant(), - executionId = sin.readOptionalString() + executionId = sin.readOptionalString(), ) - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( FINDING_ID_FIELD to id, RELATED_DOC_IDS_FIELD to relatedDocIds, CORRELATED_DOC_IDS_FIELD to correlatedDocIds, @@ -72,12 +72,15 @@ class Finding( INDEX_FIELD to index, QUERIES_FIELD to docLevelQueries, TIMESTAMP_FIELD to timestamp.toEpochMilli(), - EXECUTION_ID_FIELD to executionId + EXECUTION_ID_FIELD to executionId, ) - } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field(FINDING_ID_FIELD, id) .field(RELATED_DOC_IDS_FIELD, relatedDocIds) .field(CORRELATED_DOC_IDS_FIELD, correlatedDocIds) @@ -135,32 +138,50 @@ class Finding( xcp.nextToken() when (fieldName) { - FINDING_ID_FIELD -> id = xcp.text() + FINDING_ID_FIELD -> { + id = xcp.text() + } + RELATED_DOC_IDS_FIELD -> { ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { relatedDocIds.add(xcp.text()) } } + CORRELATED_DOC_IDS_FIELD -> { ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { correlatedDocIds.add(xcp.text()) } } - MONITOR_ID_FIELD -> monitorId = xcp.text() - MONITOR_NAME_FIELD -> monitorName = xcp.text() - INDEX_FIELD -> index = xcp.text() + + MONITOR_ID_FIELD -> { + monitorId = xcp.text() + } + + MONITOR_NAME_FIELD -> { + monitorName = xcp.text() + } + + INDEX_FIELD -> { + index = xcp.text() + } + QUERIES_FIELD -> { ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { queries.add(DocLevelQuery.parse(xcp)) } } + TIMESTAMP_FIELD -> { timestamp = requireNotNull(xcp.instant()) } - EXECUTION_ID_FIELD -> executionId = xcp.textOrNull() + + EXECUTION_ID_FIELD -> { + executionId = xcp.textOrNull() + } } } @@ -173,14 +194,12 @@ class Finding( index = index, docLevelQueries = queries, timestamp = timestamp, - executionId = executionId + executionId = executionId, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Finding { - return Finding(sin) - } + fun readFrom(sin: StreamInput): Finding = Finding(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/FindingDocument.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/FindingDocument.kt index 202693fd..c6350dea 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/FindingDocument.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/FindingDocument.kt @@ -16,25 +16,28 @@ class FindingDocument( val index: String, val id: String, val found: Boolean, - val document: String -) : Writeable, ToXContent { - + val document: String, +) : Writeable, + ToXContent { @Throws(IOException::class) constructor(sin: StreamInput) : this( index = sin.readString(), id = sin.readString(), found = sin.readBoolean(), - document = sin.readString() + document = sin.readString(), ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(INDEX_FIELD, index) .field(FINDING_DOCUMENT_ID_FIELD, id) .field(FOUND_FIELD, found) .field(DOCUMENT_FIELD, document) .endObject() - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -55,7 +58,11 @@ class FindingDocument( @JvmStatic @JvmOverloads @Throws(IOException::class) - fun parse(xcp: XContentParser, id: String = NO_ID, index: String = NO_INDEX): FindingDocument { + fun parse( + xcp: XContentParser, + id: String = NO_ID, + index: String = NO_INDEX, + ): FindingDocument { var found = false var document: String = "" @@ -74,14 +81,12 @@ class FindingDocument( index = index, id = id, found = found, - document = document + document = document, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): FindingDocument { - return FindingDocument(sin) - } + fun readFrom(sin: StreamInput): FindingDocument = FindingDocument(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/FindingWithDocs.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/FindingWithDocs.kt index 057e2214..7458dcf7 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/FindingWithDocs.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/FindingWithDocs.kt @@ -14,13 +14,13 @@ private val log = LogManager.getLogger(Finding::class.java) class FindingWithDocs( val finding: Finding, - val documents: List -) : Writeable, ToXContent { - + val documents: List, +) : Writeable, + ToXContent { @Throws(IOException::class) constructor(sin: StreamInput) : this( finding = Finding.readFrom(sin), - documents = sin.readList((FindingDocument)::readFrom) + documents = sin.readList((FindingDocument)::readFrom), ) @Throws(IOException::class) @@ -29,8 +29,12 @@ class FindingWithDocs( out.writeCollection(documents) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field(FINDING_FIELD, finding) .field(DOCUMENTS_FIELD, documents) builder.endObject() @@ -53,7 +57,10 @@ class FindingWithDocs( xcp.nextToken() when (fieldName) { - FINDING_FIELD -> finding = Finding.parse(xcp) + FINDING_FIELD -> { + finding = Finding.parse(xcp) + } + DOCUMENTS_FIELD -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { @@ -65,14 +72,12 @@ class FindingWithDocs( return FindingWithDocs( finding = finding, - documents = documents + documents = documents, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): FindingWithDocs { - return FindingWithDocs(sin) - } + fun readFrom(sin: StreamInput): FindingWithDocs = FindingWithDocs(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/IndexExecutionContext.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/IndexExecutionContext.kt index 6b104d13..dd10b578 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/IndexExecutionContext.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/IndexExecutionContext.kt @@ -23,9 +23,9 @@ data class IndexExecutionContext( val concreteIndexNames: List, val conflictingFields: List, val docIds: List? = emptyList(), - val findingIds: List? = emptyList() -) : Writeable, ToXContent { - + val findingIds: List? = emptyList(), +) : Writeable, + ToXContent { @Throws(IOException::class) constructor(sin: StreamInput) : this( queries = sin.readList { DocLevelQuery(sin) }, @@ -37,7 +37,7 @@ data class IndexExecutionContext( concreteIndexNames = sin.readStringList(), conflictingFields = sin.readStringList(), docIds = sin.readOptionalStringList(), - findingIds = if (sin.version.onOrAfter(Version.V_2_15_0)) sin.readOptionalStringList() else emptyList() + findingIds = if (sin.version.onOrAfter(Version.V_2_15_0)) sin.readOptionalStringList() else emptyList(), ) override fun writeTo(out: StreamOutput?) { @@ -55,8 +55,12 @@ data class IndexExecutionContext( } } - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - builder!!.startObject() + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { + builder!! + .startObject() .field("queries", queries) .field("last_run_context", lastRunContext) .field("updated_last_run_context", updatedLastRunContext) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Input.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Input.kt index 3846cea6..cabdc090 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Input.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Input.kt @@ -14,55 +14,59 @@ import org.opensearch.core.xcontent.XContentParserUtils import java.io.IOException interface Input : BaseModel { - - enum class Type(val value: String) { + enum class Type( + val value: String, + ) { DOCUMENT_LEVEL_INPUT(DOC_LEVEL_INPUT_FIELD), CLUSTER_METRICS_INPUT(URI_FIELD), SEARCH_INPUT(SEARCH_FIELD), REMOTE_MONITOR_INPUT(REMOTE_MONITOR_INPUT_FIELD), - REMOTE_DOC_LEVEL_MONITOR_INPUT(REMOTE_DOC_LEVEL_MONITOR_INPUT_FIELD); + REMOTE_DOC_LEVEL_MONITOR_INPUT(REMOTE_DOC_LEVEL_MONITOR_INPUT_FIELD), + ; - override fun toString(): String { - return value - } + override fun toString(): String = value } companion object { - @Throws(IOException::class) fun parse(xcp: XContentParser): Input { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, xcp.currentToken(), xcp) XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, xcp.nextToken(), xcp) XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, xcp.nextToken(), xcp) - val input = if (xcp.currentName() == Type.SEARCH_INPUT.value) { - SearchInput.parseInner(xcp) - } else if (xcp.currentName() == Type.CLUSTER_METRICS_INPUT.value) { - ClusterMetricsInput.parseInner(xcp) - } else if (xcp.currentName() == Type.DOCUMENT_LEVEL_INPUT.value) { - DocLevelMonitorInput.parse(xcp) - } else if (xcp.currentName() == Type.REMOTE_MONITOR_INPUT.value) { - RemoteMonitorInput.parse(xcp) - } else { - RemoteDocLevelMonitorInput.parse(xcp) - } + val input = + if (xcp.currentName() == Type.SEARCH_INPUT.value) { + SearchInput.parseInner(xcp) + } else if (xcp.currentName() == Type.CLUSTER_METRICS_INPUT.value) { + ClusterMetricsInput.parseInner(xcp) + } else if (xcp.currentName() == Type.DOCUMENT_LEVEL_INPUT.value) { + DocLevelMonitorInput.parse(xcp) + } else if (xcp.currentName() == Type.REMOTE_MONITOR_INPUT.value) { + RemoteMonitorInput.parse(xcp) + } else { + RemoteDocLevelMonitorInput.parse(xcp) + } XContentParserUtils.ensureExpectedToken(XContentParser.Token.END_OBJECT, xcp.nextToken(), xcp) return input } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Input { - return when (val type = sin.readEnum(Input.Type::class.java)) { + fun readFrom(sin: StreamInput): Input = + when (val type = sin.readEnum(Input.Type::class.java)) { Type.DOCUMENT_LEVEL_INPUT -> DocLevelMonitorInput(sin) + Type.CLUSTER_METRICS_INPUT -> ClusterMetricsInput(sin) + Type.SEARCH_INPUT -> SearchInput(sin) + Type.REMOTE_MONITOR_INPUT -> RemoteMonitorInput(sin) + Type.REMOTE_DOC_LEVEL_MONITOR_INPUT -> RemoteDocLevelMonitorInput(sin) + // This shouldn't be reachable but ensuring exhaustiveness as Kotlin warns // enum can be null in Java else -> throw IllegalStateException("Unexpected input [$type] when reading Trigger") } - } } fun name(): String diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt index 18fdde5c..953998a3 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt @@ -45,9 +45,8 @@ data class Monitor( val dataSources: DataSources = DataSources(), val deleteQueryIndexInEveryRun: Boolean? = false, val shouldCreateSingleAlertForFindings: Boolean? = false, - val owner: String? = "alerting" + val owner: String? = "alerting", ) : ScheduledJob { - override val type = MONITOR_TYPE init { @@ -60,14 +59,21 @@ data class Monitor( require(triggerIds.add(trigger.id)) { "Duplicate trigger id: ${trigger.id}. Trigger ids must be unique." } // Verify Trigger type based on Monitor type when (monitorType) { - MonitorType.QUERY_LEVEL_MONITOR.value -> + MonitorType.QUERY_LEVEL_MONITOR.value -> { require(trigger is QueryLevelTrigger) { "Incompatible trigger [${trigger.id}] for monitor type [$monitorType]" } - MonitorType.BUCKET_LEVEL_MONITOR.value -> + } + + MonitorType.BUCKET_LEVEL_MONITOR.value -> { require(trigger is BucketLevelTrigger) { "Incompatible trigger [${trigger.id}] for monitor type [$monitorType]" } - MonitorType.CLUSTER_METRICS_MONITOR.value -> + } + + MonitorType.CLUSTER_METRICS_MONITOR.value -> { require(trigger is QueryLevelTrigger) { "Incompatible trigger [${trigger.id}] for monitor type [$monitorType]" } - MonitorType.DOC_LEVEL_MONITOR.value -> + } + + MonitorType.DOC_LEVEL_MONITOR.value -> { require(trigger is DocumentLevelTrigger) { "Incompatible trigger [${trigger.id}] for monitor type [$monitorType]" } + } } } if (enabled) { @@ -82,7 +88,13 @@ data class Monitor( require(input is SearchInput) { "Unsupported input [$input] for Monitor" } // TODO: Keeping query validation simple for now, only term aggregations have full support for the "group by" on the // initial release. Should either add tests for other aggregation types or add validation to prevent using them. - require(input.query.aggregations() != null && !input.query.aggregations().aggregatorFactories.isEmpty()) { + require( + input.query.aggregations() != null && + !input.query + .aggregations() + .aggregatorFactories + .isEmpty(), + ) { "At least one aggregation is required for the input [$input]" } } @@ -99,49 +111,54 @@ data class Monitor( lastUpdateTime = sin.readInstant(), enabledTime = sin.readOptionalInstant(), monitorType = sin.readString(), - user = if (sin.readBoolean()) { - User(sin) - } else { - null - }, + user = + if (sin.readBoolean()) { + User(sin) + } else { + null + }, schemaVersion = sin.readInt(), inputs = sin.readList((Input)::readFrom), triggers = sin.readList((Trigger)::readFrom), uiMetadata = suppressWarning(sin.readMap()), - dataSources = if (sin.readBoolean()) { - DataSources(sin) - } else { - DataSources() - }, - deleteQueryIndexInEveryRun = if (sin.version.onOrAfter(Version.V_2_15_0)) { - sin.readOptionalBoolean() - } else { - false - }, - shouldCreateSingleAlertForFindings = if (sin.version.onOrAfter(Version.V_2_15_0)) { - sin.readOptionalBoolean() - } else { - false - }, - owner = sin.readOptionalString() + dataSources = + if (sin.readBoolean()) { + DataSources(sin) + } else { + DataSources() + }, + deleteQueryIndexInEveryRun = + if (sin.version.onOrAfter(Version.V_2_15_0)) { + sin.readOptionalBoolean() + } else { + false + }, + shouldCreateSingleAlertForFindings = + if (sin.version.onOrAfter(Version.V_2_15_0)) { + sin.readOptionalBoolean() + } else { + false + }, + owner = sin.readOptionalString(), ) // This enum classifies different Monitors // This is different from 'type' which denotes the Scheduled Job type - enum class MonitorType(val value: String) { + enum class MonitorType( + val value: String, + ) { QUERY_LEVEL_MONITOR("query_level_monitor"), BUCKET_LEVEL_MONITOR("bucket_level_monitor"), CLUSTER_METRICS_MONITOR("cluster_metrics_monitor"), - DOC_LEVEL_MONITOR("doc_level_monitor"); + DOC_LEVEL_MONITOR("doc_level_monitor"), + ; - override fun toString(): String { - return value - } + override fun toString(): String = value } /** Returns a representation of the monitor suitable for passing into painless and mustache scripts. */ - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( _ID to id, _VERSION to version, NAME_FIELD to name, @@ -150,22 +167,28 @@ data class Monitor( ENABLED_TIME_FIELD to enabledTime?.toEpochMilli(), LAST_UPDATE_TIME_FIELD to lastUpdateTime.toEpochMilli(), SCHEDULE_FIELD to schedule.asTemplateArg(), - INPUTS_FIELD to inputs.map { it.asTemplateArg() } + INPUTS_FIELD to inputs.map { it.asTemplateArg() }, ) - } - fun toXContentWithUser(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return createXContentBuilder(builder, params, false) - } + fun toXContentWithUser( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = createXContentBuilder(builder, params, false) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return createXContentBuilder(builder, params, true) - } + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = createXContentBuilder(builder, params, true) - private fun createXContentBuilder(builder: XContentBuilder, params: ToXContent.Params, secure: Boolean): XContentBuilder { + private fun createXContentBuilder( + builder: XContentBuilder, + params: ToXContent.Params, + secure: Boolean, + ): XContentBuilder { builder.startObject() if (params.paramAsBoolean("with_type", false)) builder.startObject(type) - builder.field(TYPE_FIELD, type) + builder + .field(TYPE_FIELD, type) .field(SCHEMA_VERSION_FIELD, schemaVersion) .field(NAME_FIELD, name) .field(MONITOR_TYPE_FIELD, monitorType) @@ -174,7 +197,8 @@ data class Monitor( builder.optionalUserField(USER_FIELD, user) } - builder.field(ENABLED_FIELD, enabled) + builder + .field(ENABLED_FIELD, enabled) .optionalTimeField(ENABLED_TIME_FIELD, enabledTime) .field(SCHEDULE_FIELD, schedule) .field(INPUTS_FIELD, inputs.toTypedArray()) @@ -189,7 +213,10 @@ data class Monitor( return builder.endObject() } - override fun fromDocument(id: String, version: Long): Monitor = copy(id = id, version = version) + override fun fromDocument( + id: String, + version: Long, + ): Monitor = copy(id = id, version = version) @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -268,16 +295,21 @@ data class Monitor( // This is defined here instead of in ScheduledJob to avoid having the ScheduledJob class know about all // the different subclasses and creating circular dependencies - val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - ScheduledJob::class.java, - ParseField(MONITOR_TYPE), - CheckedFunction { parse(it) } - ) + val XCONTENT_REGISTRY = + NamedXContentRegistry.Entry( + ScheduledJob::class.java, + ParseField(MONITOR_TYPE), + CheckedFunction { parse(it) }, + ) @JvmStatic @JvmOverloads @Throws(IOException::class) - fun parse(xcp: XContentParser, id: String = NO_ID, version: Long = NO_VERSION): Monitor { + fun parse( + xcp: XContentParser, + id: String = NO_ID, + version: Long = NO_VERSION, + ): Monitor { var name: String? = null // Default to QUERY_LEVEL_MONITOR to cover Monitors that existed before the addition of MonitorType var monitorType: String = MonitorType.QUERY_LEVEL_MONITOR.toString() @@ -301,8 +333,14 @@ data class Monitor( xcp.nextToken() when (fieldName) { - SCHEMA_VERSION_FIELD -> schemaVersion = xcp.intValue() - NAME_FIELD -> name = xcp.text() + SCHEMA_VERSION_FIELD -> { + schemaVersion = xcp.intValue() + } + + NAME_FIELD -> { + name = xcp.text() + } + MONITOR_TYPE_FIELD -> { monitorType = xcp.text() val matcher = MONITOR_TYPE_PATTERN.matcher(monitorType) @@ -311,14 +349,24 @@ data class Monitor( throw IllegalStateException("Monitor type should follow pattern ${MONITOR_TYPE_PATTERN.pattern()}") } } - USER_FIELD -> user = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) null else User.parse(xcp) - ENABLED_FIELD -> enabled = xcp.booleanValue() - SCHEDULE_FIELD -> schedule = Schedule.parse(xcp) + + USER_FIELD -> { + user = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) null else User.parse(xcp) + } + + ENABLED_FIELD -> { + enabled = xcp.booleanValue() + } + + SCHEDULE_FIELD -> { + schedule = Schedule.parse(xcp) + } + INPUTS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { val input = Input.parse(xcp) @@ -328,35 +376,61 @@ data class Monitor( inputs.add(input) } } + TRIGGERS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { triggers.add(Trigger.parse(xcp)) } } - ENABLED_TIME_FIELD -> enabledTime = xcp.instant() - LAST_UPDATE_TIME_FIELD -> lastUpdateTime = xcp.instant() - UI_METADATA_FIELD -> uiMetadata = xcp.map() - DATA_SOURCES_FIELD -> dataSources = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { - DataSources() - } else { - DataSources.parse(xcp) + + ENABLED_TIME_FIELD -> { + enabledTime = xcp.instant() } - DELETE_QUERY_INDEX_IN_EVERY_RUN_FIELD -> deleteQueryIndexInEveryRun = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { - deleteQueryIndexInEveryRun - } else { - xcp.booleanValue() + + LAST_UPDATE_TIME_FIELD -> { + lastUpdateTime = xcp.instant() } - SHOULD_CREATE_SINGLE_ALERT_FOR_FINDINGS_FIELD -> delegateMonitor = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { - delegateMonitor - } else { - xcp.booleanValue() + + UI_METADATA_FIELD -> { + uiMetadata = xcp.map() } - OWNER_FIELD -> owner = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) owner else xcp.text() + + DATA_SOURCES_FIELD -> { + dataSources = + if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + DataSources() + } else { + DataSources.parse(xcp) + } + } + + DELETE_QUERY_INDEX_IN_EVERY_RUN_FIELD -> { + deleteQueryIndexInEveryRun = + if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + deleteQueryIndexInEveryRun + } else { + xcp.booleanValue() + } + } + + SHOULD_CREATE_SINGLE_ALERT_FOR_FINDINGS_FIELD -> { + delegateMonitor = + if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + delegateMonitor + } else { + xcp.booleanValue() + } + } + + OWNER_FIELD -> { + owner = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) owner else xcp.text() + } + else -> { xcp.skipChildren() } @@ -385,19 +459,15 @@ data class Monitor( dataSources, deleteQueryIndexInEveryRun, delegateMonitor, - owner + owner, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Monitor? { - return Monitor(sin) - } + fun readFrom(sin: StreamInput): Monitor? = Monitor(sin) @Suppress("UNCHECKED_CAST") - fun suppressWarning(map: MutableMap?): MutableMap { - return map as MutableMap - } + fun suppressWarning(map: MutableMap?): MutableMap = map as MutableMap } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorMetadata.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorMetadata.kt index a90f3cc3..5b9dc0ce 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorMetadata.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorMetadata.kt @@ -26,9 +26,9 @@ data class MonitorMetadata( val lastActionExecutionTimes: List, val lastRunContext: Map, // Maps (sourceIndex + monitorId) --> concreteQueryIndex - val sourceToQueryIndexMapping: MutableMap = mutableMapOf() -) : Writeable, ToXContent { - + val sourceToQueryIndexMapping: MutableMap = mutableMapOf(), +) : Writeable, + ToXContent { @Throws(IOException::class) constructor(sin: StreamInput) : this( id = sin.readString(), @@ -37,7 +37,7 @@ data class MonitorMetadata( monitorId = sin.readString(), lastActionExecutionTimes = sin.readList(ActionExecutionTime.Companion::readFrom), lastRunContext = Monitor.suppressWarning(sin.readMap()), - sourceToQueryIndexMapping = sin.readMap() as MutableMap + sourceToQueryIndexMapping = sin.readMap() as MutableMap, ) override fun writeTo(out: StreamOutput) { @@ -50,10 +50,14 @@ data class MonitorMetadata( out.writeMap(sourceToQueryIndexMapping as MutableMap) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { builder.startObject() if (params.paramAsBoolean("with_type", false)) builder.startObject(METADATA) - builder.field(MONITOR_ID_FIELD, monitorId) + builder + .field(MONITOR_ID_FIELD, monitorId) .field(LAST_ACTION_EXECUTION_FIELD, lastActionExecutionTimes.toTypedArray()) if (lastRunContext.isNotEmpty()) builder.field(LAST_RUN_CONTEXT_FIELD, lastRunContext) if (sourceToQueryIndexMapping.isNotEmpty()) { @@ -77,7 +81,7 @@ data class MonitorMetadata( xcp: XContentParser, id: String = NO_ID, seqNo: Long = SequenceNumbers.UNASSIGNED_SEQ_NO, - primaryTerm: Long = SequenceNumbers.UNASSIGNED_PRIMARY_TERM + primaryTerm: Long = SequenceNumbers.UNASSIGNED_PRIMARY_TERM, ): MonitorMetadata { lateinit var monitorId: String val lastActionExecutionTimes = mutableListOf() @@ -90,15 +94,24 @@ data class MonitorMetadata( xcp.nextToken() when (fieldName) { - MONITOR_ID_FIELD -> monitorId = xcp.text() + MONITOR_ID_FIELD -> { + monitorId = xcp.text() + } + LAST_ACTION_EXECUTION_FIELD -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { lastActionExecutionTimes.add(ActionExecutionTime.parse(xcp)) } } - LAST_RUN_CONTEXT_FIELD -> lastRunContext = xcp.map() - SOURCE_TO_QUERY_INDEX_MAP_FIELD -> sourceToQueryIndexMapping = xcp.map() as MutableMap + + LAST_RUN_CONTEXT_FIELD -> { + lastRunContext = xcp.map() + } + + SOURCE_TO_QUERY_INDEX_MAP_FIELD -> { + sourceToQueryIndexMapping = xcp.map() as MutableMap + } } } @@ -109,27 +122,32 @@ data class MonitorMetadata( monitorId = monitorId, lastActionExecutionTimes = lastActionExecutionTimes, lastRunContext = lastRunContext, - sourceToQueryIndexMapping = sourceToQueryIndexMapping + sourceToQueryIndexMapping = sourceToQueryIndexMapping, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): MonitorMetadata { - return MonitorMetadata(sin) - } - - /** workflowMetadataId is used as key for monitor metadata in the case when the workflow execution happens - so the monitor lastRunContext (in the case of doc level monitor) is not interfering with the monitor execution - WorkflowMetadataId will be either workflowId-metadata (when executing the workflow as it is scheduled) - or timestampWithUUID-metadata (when a workflow is executed in a dry-run mode) - In the case of temp workflow, doc level monitors must have lastRunContext created from scratch - That's why we are using workflowMetadataId - in order to ensure that the doc level monitor metadata is created from scratch - **/ - fun getId(monitor: Monitor, workflowMetadataId: String? = null): String { - return if (workflowMetadataId.isNullOrEmpty()) { "${monitor.id}-metadata" } + fun readFrom(sin: StreamInput): MonitorMetadata = MonitorMetadata(sin) + + /** + * workflowMetadataId is used as key for monitor metadata in the case when the workflow execution happens + * so the monitor lastRunContext (in the case of doc level monitor) is not interfering with the monitor execution + * WorkflowMetadataId will be either workflowId-metadata (when executing the workflow as it is scheduled) + * or timestampWithUUID-metadata (when a workflow is executed in a dry-run mode) + * In the case of temp workflow, doc level monitors must have lastRunContext created from scratch + * That's why we are using workflowMetadataId - in order to ensure that the doc level monitor metadata is created from scratch + */ + fun getId( + monitor: Monitor, + workflowMetadataId: String? = null, + ): String { // WorkflowMetadataId already contains -metadata suffix - else { "$workflowMetadataId-${monitor.id}-metadata" } + return if (workflowMetadataId.isNullOrEmpty()) { + "${monitor.id}-metadata" + } else { + "$workflowMetadataId-${monitor.id}-metadata" + } } } } @@ -139,21 +157,24 @@ data class MonitorMetadata( */ data class ActionExecutionTime( val actionId: String, - val executionTime: Instant -) : Writeable, ToXContent { - + val executionTime: Instant, +) : Writeable, + ToXContent { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // actionId - sin.readInstant() // executionTime + sin.readInstant(), // executionTime ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(ACTION_ID_FIELD, actionId) .field(EXECUTION_TIME_FIELD, executionTime) .endObject() - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -184,14 +205,12 @@ data class ActionExecutionTime( return ActionExecutionTime( actionId, - executionTime + executionTime, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): ActionExecutionTime { - return ActionExecutionTime(sin) - } + fun readFrom(sin: StreamInput): ActionExecutionTime = ActionExecutionTime(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorRunResult.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorRunResult.kt index d403313b..ce9be4e2 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorRunResult.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorRunResult.kt @@ -24,9 +24,9 @@ data class MonitorRunResult( val periodEnd: Instant, val error: Exception? = null, val inputResults: InputRunResults = InputRunResults(), - val triggerResults: Map = mapOf() -) : Writeable, ToXContent { - + val triggerResults: Map = mapOf(), +) : Writeable, + ToXContent { @Throws(IOException::class) @Suppress("UNCHECKED_CAST") constructor(sin: StreamInput) : this( @@ -35,11 +35,15 @@ data class MonitorRunResult( sin.readInstant(), // periodEnd sin.readException(), // error InputRunResults.readFrom(sin), // inputResults - suppressWarning(sin.readMap()) as Map // triggerResults + suppressWarning(sin.readMap()) as Map, // triggerResults ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field("monitor_name", monitorName) .optionalTimeField("period_start", periodStart) .optionalTimeField("period_end", periodEnd) @@ -47,7 +51,6 @@ data class MonitorRunResult( .field("input_results", inputResults) .field("trigger_results", triggerResults) .endObject() - } /** Returns error information to store in the Alert. Currently it's just the stack trace but it can be more */ fun alertError(): AlertError? { @@ -61,21 +64,15 @@ data class MonitorRunResult( return null } - fun scriptContextError(trigger: Trigger): Exception? { - return error ?: inputResults.error ?: triggerResults[trigger.id]?.error - } + fun scriptContextError(trigger: Trigger): Exception? = error ?: inputResults.error ?: triggerResults[trigger.id]?.error companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): MonitorRunResult { - return MonitorRunResult(sin) - } + fun readFrom(sin: StreamInput): MonitorRunResult = MonitorRunResult(sin) @Suppress("UNCHECKED_CAST") - fun suppressWarning(map: MutableMap?): Map { - return map as Map - } + fun suppressWarning(map: MutableMap?): Map = map as Map } @Throws(IOException::class) @@ -92,15 +89,18 @@ data class MonitorRunResult( data class InputRunResults( val results: List> = listOf(), val error: Exception? = null, - val aggTriggersAfterKey: MutableMap? = null -) : Writeable, ToXContent { - - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + val aggTriggersAfterKey: MutableMap? = null, +) : Writeable, + ToXContent { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field("results", results) .field("error", error?.message) .endObject() - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -125,9 +125,7 @@ data class InputRunResults( } @Suppress("UNCHECKED_CAST") - fun suppressWarning(map: MutableMap?): Map { - return map as Map - } + fun suppressWarning(map: MutableMap?): Map = map as Map } fun afterKeysPresent(): Boolean { @@ -140,7 +138,10 @@ data class InputRunResults( } } -data class TriggerAfterKey(val afterKey: Map?, val lastPage: Boolean) +data class TriggerAfterKey( + val afterKey: Map?, + val lastPage: Boolean, +) data class ActionRunResult( val actionId: String, @@ -148,9 +149,9 @@ data class ActionRunResult( val output: Map, val throttled: Boolean = false, val executionTime: Instant? = null, - val error: Exception? = null -) : Writeable, ToXContent { - + val error: Exception? = null, +) : Writeable, + ToXContent { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // actionId @@ -158,11 +159,15 @@ data class ActionRunResult( suppressWarning(sin.readMap()), // output sin.readBoolean(), // throttled sin.readOptionalInstant(), // executionTime - sin.readException() // error + sin.readException(), // error ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field("id", actionId) .field("name", actionName) .field("output", output) @@ -170,7 +175,6 @@ data class ActionRunResult( .optionalTimeField("executionTime", executionTime) .field("error", error?.message) .endObject() - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -185,31 +189,33 @@ data class ActionRunResult( companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): ActionRunResult { - return ActionRunResult(sin) - } + fun readFrom(sin: StreamInput): ActionRunResult = ActionRunResult(sin) @Suppress("UNCHECKED_CAST") - fun suppressWarning(map: MutableMap?): MutableMap { - return map as MutableMap - } + fun suppressWarning(map: MutableMap?): MutableMap = map as MutableMap } } private val logger = LogManager.getLogger(MonitorRunResult::class.java) /** Constructs an error message from an exception suitable for human consumption. */ -fun Throwable.userErrorMessage(): String { - return when { - this is ScriptException -> this.scriptStack.joinToString(separator = "\n", limit = 100) - this is OpenSearchException -> this.detailedMessage +fun Throwable.userErrorMessage(): String = + when { + this is ScriptException -> { + this.scriptStack.joinToString(separator = "\n", limit = 100) + } + + this is OpenSearchException -> { + this.detailedMessage + } + this.message != null -> { logger.info("Internal error: ${this.message}. See the opensearch.log for details", this) this.message!! } + else -> { logger.info("Unknown Internal error. See the OpenSearch log for details.", this) "Unknown Internal error. See the OpenSearch log for details." } } -} diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/NoOpTrigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/NoOpTrigger.kt index 3ffacb6e..18226d4c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/NoOpTrigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/NoOpTrigger.kt @@ -17,14 +17,17 @@ data class NoOpTrigger( override val id: String = UUIDs.base64UUID(), override val name: String = "NoOp trigger", override val severity: String = "", - override val actions: List = listOf() + override val actions: List = listOf(), ) : Trigger { - @Throws(IOException::class) constructor(sin: StreamInput) : this() - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(NOOP_TRIGGER_FIELD) .field(ID_FIELD, id) .endObject() @@ -32,13 +35,9 @@ data class NoOpTrigger( return builder } - override fun name(): String { - return NOOP_TRIGGER_FIELD - } + override fun name(): String = NOOP_TRIGGER_FIELD - fun asTemplateArg(): Map { - return mapOf() - } + fun asTemplateArg(): Map = mapOf() @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -47,11 +46,12 @@ data class NoOpTrigger( companion object { const val ID_FIELD = "id" const val NOOP_TRIGGER_FIELD = "noop_trigger" - val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Trigger::class.java, - ParseField(NOOP_TRIGGER_FIELD), - CheckedFunction { parseInner(it) } - ) + val XCONTENT_REGISTRY = + NamedXContentRegistry.Entry( + Trigger::class.java, + ParseField(NOOP_TRIGGER_FIELD), + CheckedFunction { parseInner(it) }, + ) @JvmStatic @Throws(IOException::class) @@ -71,8 +71,6 @@ data class NoOpTrigger( @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): NoOpTrigger { - return NoOpTrigger(sin) - } + fun readFrom(sin: StreamInput): NoOpTrigger = NoOpTrigger(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTrigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTrigger.kt index a88ef9b6..b00d4ac5 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTrigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTrigger.kt @@ -23,20 +23,23 @@ data class QueryLevelTrigger( override val name: String, override val severity: String, override val actions: List, - val condition: Script + val condition: Script, ) : Trigger { - @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // id sin.readString(), // name sin.readString(), // severity sin.readList(::Action), // actions - Script(sin) // condition + Script(sin), // condition ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(QUERY_LEVEL_TRIGGER_FIELD) .field(ID_FIELD, id) .field(NAME_FIELD, name) @@ -50,25 +53,24 @@ data class QueryLevelTrigger( return builder } - override fun name(): String { - return QUERY_LEVEL_TRIGGER_FIELD - } + override fun name(): String = QUERY_LEVEL_TRIGGER_FIELD /** Returns a representation of the trigger suitable for passing into painless and mustache scripts. */ - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( ID_FIELD to id, NAME_FIELD to name, SEVERITY_FIELD to severity, ACTIONS_FIELD to actions.map { it.asTemplateArg() }, - CONDITION_FIELD to mapOf( - SCRIPT_FIELD to mapOf( - SOURCE_FIELD to condition.idOrCode, - LANG_FIELD to condition.lang - ) - ) + CONDITION_FIELD to + mapOf( + SCRIPT_FIELD to + mapOf( + SOURCE_FIELD to condition.idOrCode, + LANG_FIELD to condition.lang, + ), + ), ) - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -86,11 +88,12 @@ data class QueryLevelTrigger( const val SOURCE_FIELD = "source" const val LANG_FIELD = "lang" - val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Trigger::class.java, - ParseField(QUERY_LEVEL_TRIGGER_FIELD), - CheckedFunction { parseInner(it) } - ) + val XCONTENT_REGISTRY = + NamedXContentRegistry.Entry( + Trigger::class.java, + ParseField(QUERY_LEVEL_TRIGGER_FIELD), + CheckedFunction { parseInner(it) }, + ) /** * This parse method needs to account for both the old and new Trigger format. @@ -146,9 +149,18 @@ data class QueryLevelTrigger( xcp.nextToken() when (fieldName) { - ID_FIELD -> id = xcp.text() - NAME_FIELD -> name = xcp.text() - SEVERITY_FIELD -> severity = xcp.text() + ID_FIELD -> { + id = xcp.text() + } + + NAME_FIELD -> { + name = xcp.text() + } + + SEVERITY_FIELD -> { + severity = xcp.text() + } + CONDITION_FIELD -> { xcp.nextToken() condition = Script.parse(xcp) @@ -157,11 +169,12 @@ data class QueryLevelTrigger( } xcp.nextToken() } + ACTIONS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { actions.add(Action.parse(xcp)) @@ -176,14 +189,12 @@ data class QueryLevelTrigger( severity = requireNotNull(severity) { "Trigger severity is null" }, condition = requireNotNull(condition) { "Trigger condition is null" }, actions = requireNotNull(actions) { "Trigger actions are null" }, - id = requireNotNull(id) { "Trigger id is null." } + id = requireNotNull(id) { "Trigger id is null." }, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): QueryLevelTrigger { - return QueryLevelTrigger(sin) - } + fun readFrom(sin: StreamInput): QueryLevelTrigger = QueryLevelTrigger(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTriggerRunResult.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTriggerRunResult.kt index 101d0067..45bbb2a5 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTriggerRunResult.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTriggerRunResult.kt @@ -18,16 +18,15 @@ open class QueryLevelTriggerRunResult( override var triggerName: String, open var triggered: Boolean, override var error: Exception?, - open var actionResults: MutableMap = mutableMapOf() + open var actionResults: MutableMap = mutableMapOf(), ) : TriggerRunResult(triggerName, error) { - @Throws(IOException::class) @Suppress("UNCHECKED_CAST") constructor(sin: StreamInput) : this( triggerName = sin.readString(), error = sin.readException(), triggered = sin.readBoolean(), - actionResults = sin.readMap() as MutableMap + actionResults = sin.readMap() as MutableMap, ) override fun alertError(): AlertError? { @@ -42,7 +41,10 @@ open class QueryLevelTriggerRunResult( return null } - override fun internalXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun internalXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { if (error is ScriptException) error = Exception((error as ScriptException).toJsonString(), error) return builder .field("triggered", triggered) @@ -59,8 +61,6 @@ open class QueryLevelTriggerRunResult( companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): TriggerRunResult { - return QueryLevelTriggerRunResult(sin) - } + fun readFrom(sin: StreamInput): TriggerRunResult = QueryLevelTriggerRunResult(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Schedule.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Schedule.kt index 7b1b1868..1e35fb40 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Schedule.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Schedule.kt @@ -23,6 +23,7 @@ import java.util.Locale sealed class Schedule : BaseModel { enum class TYPE { CRON, INTERVAL } + companion object { const val CRON_FIELD = "cron" const val EXPRESSION_FIELD = "expression" @@ -62,6 +63,7 @@ sealed class Schedule : BaseModel { } } } + PERIOD_FIELD -> { type = TYPE.INTERVAL while (xcp.nextToken() != XContentParser.Token.END_OBJECT) { @@ -73,21 +75,24 @@ sealed class Schedule : BaseModel { } } } + else -> { throw IllegalArgumentException("Invalid field: [$fieldname] found in schedule.") } } } if (type == TYPE.CRON) { - schedule = CronSchedule( - requireNotNull(expression) { "Expression in cron schedule is null." }, - requireNotNull(timezone) { "Timezone in cron schedule is null." } - ) + schedule = + CronSchedule( + requireNotNull(expression) { "Expression in cron schedule is null." }, + requireNotNull(timezone) { "Timezone in cron schedule is null." }, + ) } else if (type == TYPE.INTERVAL) { - schedule = IntervalSchedule( - requireNotNull(interval) { "Interval in period schedule is null." }, - requireNotNull(unit) { "Unit in period schedule is null." } - ) + schedule = + IntervalSchedule( + requireNotNull(interval) { "Interval in period schedule is null." }, + requireNotNull(unit) { "Unit in period schedule is null." }, + ) } return requireNotNull(schedule) { "Schedule is null." } } @@ -125,7 +130,10 @@ sealed class Schedule : BaseModel { * @param expectedPreviousExecutionTime is the calculated previous execution time that should always be correct, * the first time this is called the value passed in is the enabledTime which acts as the expectedPreviousExecutionTime */ - abstract fun getExpectedNextExecutionTime(enabledTime: Instant, expectedPreviousExecutionTime: Instant?): Instant? + abstract fun getExpectedNextExecutionTime( + enabledTime: Instant, + expectedPreviousExecutionTime: Instant?, + ): Instant? /** * Returns the start and end time for this schedule starting at the given start time (if provided). @@ -158,7 +166,7 @@ data class CronSchedule( val expression: String, val timezone: ZoneId, // visible for testing - @Transient val testInstant: Instant? = null + @Transient val testInstant: Instant? = null, ) : Schedule() { @Transient val executionTime: ExecutionTime = ExecutionTime.forCron(cronParser.parse(expression)) @@ -166,15 +174,13 @@ data class CronSchedule( @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // expression - sin.readZoneId() // timezone + sin.readZoneId(), // timezone ) companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): CronSchedule { - return CronSchedule(sin) - } + fun readFrom(sin: StreamInput): CronSchedule = CronSchedule(sin) } /* @@ -186,42 +192,47 @@ data class CronSchedule( return timeToNextExecution.orElse(null) } - override fun getExpectedNextExecutionTime(enabledTime: Instant, expectedPreviousExecutionTime: Instant?): Instant? { + override fun getExpectedNextExecutionTime( + enabledTime: Instant, + expectedPreviousExecutionTime: Instant?, + ): Instant? { val zonedDateTime = ZonedDateTime.ofInstant(expectedPreviousExecutionTime ?: testInstant ?: Instant.now(), timezone) val nextExecution = executionTime.nextExecution(zonedDateTime) return nextExecution.orElse(null)?.toInstant() } override fun getPeriodStartingAt(startTime: Instant?): Pair { - val realStartTime = if (startTime != null) { - startTime - } else { - // Probably the first time we're running. Try to figure out the last execution time - val lastExecutionTime = executionTime.lastExecution(ZonedDateTime.now(timezone)) - // This shouldn't happen unless the cron is configured to run only once, which our current cron syntax doesn't support - if (!lastExecutionTime.isPresent) { - val currentTime = Instant.now() - return Pair(currentTime, currentTime) + val realStartTime = + if (startTime != null) { + startTime + } else { + // Probably the first time we're running. Try to figure out the last execution time + val lastExecutionTime = executionTime.lastExecution(ZonedDateTime.now(timezone)) + // This shouldn't happen unless the cron is configured to run only once, which our current cron syntax doesn't support + if (!lastExecutionTime.isPresent) { + val currentTime = Instant.now() + return Pair(currentTime, currentTime) + } + lastExecutionTime.get().toInstant() } - lastExecutionTime.get().toInstant() - } val zonedDateTime = ZonedDateTime.ofInstant(realStartTime, timezone) val newEndTime = executionTime.nextExecution(zonedDateTime).orElse(null) return Pair(realStartTime, newEndTime?.toInstant() ?: realStartTime) } override fun getPeriodEndingAt(endTime: Instant?): Pair { - val realEndTime = if (endTime != null) { - endTime - } else { - val nextExecutionTime = executionTime.nextExecution(ZonedDateTime.now(timezone)) - // This shouldn't happen unless the cron is configured to run only once which our current cron syntax doesn't support - if (!nextExecutionTime.isPresent) { - val currentTime = Instant.now() - return Pair(currentTime, currentTime) + val realEndTime = + if (endTime != null) { + endTime + } else { + val nextExecutionTime = executionTime.nextExecution(ZonedDateTime.now(timezone)) + // This shouldn't happen unless the cron is configured to run only once which our current cron syntax doesn't support + if (!nextExecutionTime.isPresent) { + val currentTime = Instant.now() + return Pair(currentTime, currentTime) + } + nextExecutionTime.get().toInstant() } - nextExecutionTime.get().toInstant() - } val zonedDateTime = ZonedDateTime.ofInstant(realEndTime, timezone) val newStartTime = executionTime.lastExecution(zonedDateTime).orElse(null) return Pair(newStartTime?.toInstant() ?: realEndTime, realEndTime) @@ -245,8 +256,12 @@ data class CronSchedule( return ChronoUnit.SECONDS.between(expectedExecutionTime.get(), actualExecutionTime) == 0L } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(CRON_FIELD) .field(EXPRESSION_FIELD, expression) .field(TIMEZONE_FIELD, timezone.id) @@ -263,10 +278,11 @@ data class CronSchedule( override fun asTemplateArg(): Map = mapOf( - CRON_FIELD to mapOf( - EXPRESSION_FIELD to expression, - TIMEZONE_FIELD to timezone.toString() - ) + CRON_FIELD to + mapOf( + EXPRESSION_FIELD to expression, + TIMEZONE_FIELD to timezone.toString(), + ), ) } @@ -274,13 +290,14 @@ data class IntervalSchedule( val interval: Int, val unit: ChronoUnit, // visible for testing - @Transient val testInstant: Instant? = null + @Transient val testInstant: Instant? = null, ) : Schedule() { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readInt(), // interval - sin.readEnum(ChronoUnit::class.java) // unit + sin.readEnum(ChronoUnit::class.java), // unit ) + companion object { // Including SECONDS in this list for testing purposes to run test monitors in order of seconds @Transient @@ -288,9 +305,7 @@ data class IntervalSchedule( @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): IntervalSchedule { - return IntervalSchedule(sin) - } + fun readFrom(sin: StreamInput): IntervalSchedule = IntervalSchedule(sin) } init { @@ -317,7 +332,10 @@ data class IntervalSchedule( return Duration.of(remainingScheduleTime, ChronoUnit.MILLIS) } - override fun getExpectedNextExecutionTime(enabledTime: Instant, expectedPreviousExecutionTime: Instant?): Instant? { + override fun getExpectedNextExecutionTime( + enabledTime: Instant, + expectedPreviousExecutionTime: Instant?, + ): Instant? { val expectedPreviousExecutionTimeEpochMillis = (expectedPreviousExecutionTime ?: enabledTime).toEpochMilli() // We still need to calculate the delta even when using expectedPreviousExecutionTime because the initial value passed in // is the enabledTime (which also happens with cluster/node restart) @@ -351,8 +369,12 @@ data class IntervalSchedule( return 0 < delta && delta < intervalInMills } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(PERIOD_FIELD) .field(INTERVAL_FIELD, interval) .field(UNIT_FIELD, unit.name) @@ -369,9 +391,10 @@ data class IntervalSchedule( override fun asTemplateArg(): Map = mapOf( - PERIOD_FIELD to mapOf( - INTERVAL_FIELD to interval, - UNIT_FIELD to unit.toString() - ) + PERIOD_FIELD to + mapOf( + INTERVAL_FIELD to interval, + UNIT_FIELD to unit.toString(), + ), ) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/ScheduledJob.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/ScheduledJob.kt index cf8417c2..ce99c35e 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/ScheduledJob.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/ScheduledJob.kt @@ -9,7 +9,6 @@ import java.io.IOException import java.time.Instant interface ScheduledJob : BaseModel { - fun toXContentWithType(builder: XContentBuilder): XContentBuilder = toXContent(builder, XCONTENT_WITH_TYPE) companion object { @@ -32,7 +31,11 @@ interface ScheduledJob : BaseModel { * If the job comes from an OpenSearch index it's [id] and [version] can also be supplied. */ @Throws(IOException::class) - fun parse(xcp: XContentParser, id: String = NO_ID, version: Long = NO_VERSION): ScheduledJob { + fun parse( + xcp: XContentParser, + id: String = NO_ID, + version: Long = NO_VERSION, + ): ScheduledJob { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, xcp.nextToken(), xcp) XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, xcp.nextToken(), xcp) XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, xcp.nextToken(), xcp) @@ -48,7 +51,12 @@ interface ScheduledJob : BaseModel { * the above parse function. */ @Throws(IOException::class) - fun parse(xcp: XContentParser, type: String, id: String = NO_ID, version: Long = NO_VERSION): ScheduledJob { + fun parse( + xcp: XContentParser, + type: String, + id: String = NO_ID, + version: Long = NO_VERSION, + ): ScheduledJob { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, xcp.nextToken(), xcp) val job = xcp.namedObject(ScheduledJob::class.java, type, null) XContentParserUtils.ensureExpectedToken(XContentParser.Token.END_OBJECT, xcp.nextToken(), xcp) @@ -81,5 +89,8 @@ interface ScheduledJob : BaseModel { val enabledTime: Instant? /** Copy constructor for persisted jobs */ - fun fromDocument(id: String, version: Long): ScheduledJob + fun fromDocument( + id: String, + version: Long, + ): ScheduledJob } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/SearchInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/SearchInput.kt index 99a5cb8d..ab30dd6c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/SearchInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/SearchInput.kt @@ -12,26 +12,29 @@ import org.opensearch.core.xcontent.XContentParserUtils import org.opensearch.search.builder.SearchSourceBuilder import java.io.IOException -data class SearchInput(val indices: List, val query: SearchSourceBuilder) : Input { - +data class SearchInput( + val indices: List, + val query: SearchSourceBuilder, +) : Input { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readStringList(), // indices - SearchSourceBuilder(sin) // query + SearchSourceBuilder(sin), // query ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .startObject(SEARCH_FIELD) .field(INDICES_FIELD, indices.toTypedArray()) .field(QUERY_FIELD, query) .endObject() .endObject() - } - override fun name(): String { - return SEARCH_FIELD - } + override fun name(): String = SEARCH_FIELD @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -61,12 +64,13 @@ data class SearchInput(val indices: List, val query: SearchSourceBuilder XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { indices.add(xcp.text()) } } + QUERY_FIELD -> { searchSourceBuilder = SearchSourceBuilder.fromXContent(xcp, false) } @@ -75,22 +79,21 @@ data class SearchInput(val indices: List, val query: SearchSourceBuilder return SearchInput( indices, - requireNotNull(searchSourceBuilder) { "SearchInput query is null" } + requireNotNull(searchSourceBuilder) { "SearchInput query is null" }, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): SearchInput { - return SearchInput(sin) - } + fun readFrom(sin: StreamInput): SearchInput = SearchInput(sin) } override fun asTemplateArg(): Map = mapOf( - SEARCH_FIELD to mapOf( - INDICES_FIELD to indices, - QUERY_FIELD to query.toString() - ) + SEARCH_FIELD to + mapOf( + INDICES_FIELD to indices, + QUERY_FIELD to query.toString(), + ), ) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Sequence.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Sequence.kt index e1f6150d..b1fb3599 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Sequence.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Sequence.kt @@ -11,19 +11,17 @@ import java.io.IOException /** Delegate monitors passed as input for composite monitors. */ data class Sequence( - val delegates: List + val delegates: List, ) : BaseModel { - @Throws(IOException::class) constructor(sin: StreamInput) : this( - sin.readList(::Delegate) + sin.readList(::Delegate), ) - fun asTemplateArg(): Map { - return mapOf( - DELEGATES_FIELD to delegates + fun asTemplateArg(): Map = + mapOf( + DELEGATES_FIELD to delegates, ) - } companion object { const val SEQUENCE_FIELD = "sequence" @@ -44,7 +42,7 @@ data class Sequence( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { delegates.add(Delegate.parse(xcp)) @@ -57,9 +55,7 @@ data class Sequence( @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): DocLevelMonitorInput { - return DocLevelMonitorInput(sin) - } + fun readFrom(sin: StreamInput): DocLevelMonitorInput = DocLevelMonitorInput(sin) } @Throws(IOException::class) @@ -67,9 +63,12 @@ data class Sequence( out.writeCollection(delegates) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(DELEGATES_FIELD, delegates.toTypedArray()) .endObject() - } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Table.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Table.kt index 56d8a575..a1435dcb 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Table.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Table.kt @@ -11,9 +11,8 @@ data class Table( val missing: String?, val size: Int, val startIndex: Int, - val searchString: String? + val searchString: String?, ) : Writeable { - @Throws(IOException::class) constructor(sin: StreamInput) : this( sortOrder = sin.readString(), @@ -21,7 +20,7 @@ data class Table( missing = sin.readOptionalString(), size = sin.readInt(), startIndex = sin.readInt(), - searchString = sin.readOptionalString() + searchString = sin.readOptionalString(), ) @Throws(IOException::class) @@ -37,8 +36,6 @@ data class Table( companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Table { - return Table(sin) - } + fun readFrom(sin: StreamInput): Table = Table(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Trigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Trigger.kt index 7cfb9f41..9a42071b 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Trigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Trigger.kt @@ -9,18 +9,18 @@ import org.opensearch.core.xcontent.XContentParserUtils import java.io.IOException interface Trigger : BaseModel { - - enum class Type(val value: String) { + enum class Type( + val value: String, + ) { DOCUMENT_LEVEL_TRIGGER(DocumentLevelTrigger.DOCUMENT_LEVEL_TRIGGER_FIELD), QUERY_LEVEL_TRIGGER(QueryLevelTrigger.QUERY_LEVEL_TRIGGER_FIELD), BUCKET_LEVEL_TRIGGER(BucketLevelTrigger.BUCKET_LEVEL_TRIGGER_FIELD), NOOP_TRIGGER(NoOpTrigger.NOOP_TRIGGER_FIELD), CHAINED_ALERT_TRIGGER(ChainedAlertTrigger.CHAINED_ALERT_TRIGGER_FIELD), - REMOTE_MONITOR_TRIGGER(RemoteMonitorTrigger.REMOTE_MONITOR_TRIGGER_FIELD); + REMOTE_MONITOR_TRIGGER(RemoteMonitorTrigger.REMOTE_MONITOR_TRIGGER_FIELD), + ; - override fun toString(): String { - return value - } + override fun toString(): String = value } companion object { @@ -51,18 +51,22 @@ interface Trigger : BaseModel { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Trigger { - return when (val type = sin.readEnum(Trigger.Type::class.java)) { + fun readFrom(sin: StreamInput): Trigger = + when (val type = sin.readEnum(Trigger.Type::class.java)) { Type.QUERY_LEVEL_TRIGGER -> QueryLevelTrigger(sin) + Type.BUCKET_LEVEL_TRIGGER -> BucketLevelTrigger(sin) + Type.DOCUMENT_LEVEL_TRIGGER -> DocumentLevelTrigger(sin) + Type.CHAINED_ALERT_TRIGGER -> ChainedAlertTrigger(sin) + Type.REMOTE_MONITOR_TRIGGER -> RemoteMonitorTrigger(sin) + // This shouldn't be reachable but ensuring exhaustiveness as Kotlin warns // enum can be null in Java else -> throw IllegalStateException("Unexpected input [$type] when reading Trigger") } - } } /** The id of the Trigger in the [SCHEDULED_JOBS_INDEX] */ diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/TriggerRunResult.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/TriggerRunResult.kt index 84efde39..80b074b9 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/TriggerRunResult.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/TriggerRunResult.kt @@ -15,22 +15,30 @@ import java.time.Instant abstract class TriggerRunResult( open var triggerName: String, - open var error: Exception? = null -) : Writeable, ToXContent { - - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + open var error: Exception? = null, +) : Writeable, + ToXContent { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field("name", triggerName) internalXContent(builder, params) val msg = error?.message - builder.field("error", msg) + builder + .field("error", msg) .endObject() return builder } - abstract fun internalXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder + abstract fun internalXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder /** Returns error information to store in the Alert. Currently it's just the stack trace but it can be more */ open fun alertError(): AlertError? { @@ -48,8 +56,7 @@ abstract class TriggerRunResult( companion object { @Suppress("UNCHECKED_CAST") - fun suppressWarning(map: MutableMap?): MutableMap { - return map as MutableMap - } + fun suppressWarning(map: MutableMap?): MutableMap = + map as MutableMap } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Workflow.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Workflow.kt index d0e57e63..710bc23e 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Workflow.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Workflow.kt @@ -37,7 +37,7 @@ data class Workflow( val inputs: List, val owner: String? = DEFAULT_OWNER, val triggers: List, - val auditDelegateMonitorAlerts: Boolean? = true + val auditDelegateMonitorAlerts: Boolean? = true, ) : ScheduledJob { override val type = WORKFLOW_TYPE @@ -65,49 +65,52 @@ data class Workflow( lastUpdateTime = sin.readInstant(), enabledTime = sin.readOptionalInstant(), workflowType = sin.readEnum(WorkflowType::class.java), - user = if (sin.readBoolean()) { - User(sin) - } else { - null - }, + user = + if (sin.readBoolean()) { + User(sin) + } else { + null + }, schemaVersion = sin.readInt(), inputs = sin.readList((WorkflowInput)::readFrom), owner = sin.readOptionalString(), triggers = sin.readList((Trigger)::readFrom), - auditDelegateMonitorAlerts = sin.readOptionalBoolean() + auditDelegateMonitorAlerts = sin.readOptionalBoolean(), ) // This enum classifies different workflows // This is different from 'type' which denotes the Scheduled Job type - enum class WorkflowType(val value: String) { - COMPOSITE("composite"); + enum class WorkflowType( + val value: String, + ) { + COMPOSITE("composite"), + ; - override fun toString(): String { - return value - } + override fun toString(): String = value } /** Returns a representation of the workflow suitable for passing into painless and mustache scripts. */ - fun asTemplateArg(): Map { - return mapOf(_ID to id, _VERSION to version, NAME_FIELD to name, ENABLED_FIELD to enabled) - } + fun asTemplateArg(): Map = mapOf(_ID to id, _VERSION to version, NAME_FIELD to name, ENABLED_FIELD to enabled) - fun toXContentWithUser(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return createXContentBuilder(builder, params, false) - } + fun toXContentWithUser( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = createXContentBuilder(builder, params, false) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return createXContentBuilder(builder, params, true) - } + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = createXContentBuilder(builder, params, true) private fun createXContentBuilder( builder: XContentBuilder, params: ToXContent.Params, - secure: Boolean + secure: Boolean, ): XContentBuilder { builder.startObject() if (params.paramAsBoolean("with_type", false)) builder.startObject(type) - builder.field(TYPE_FIELD, type) + builder + .field(TYPE_FIELD, type) .field(SCHEMA_VERSION_FIELD, schemaVersion) .field(NAME_FIELD, name) .field(WORKFLOW_TYPE_FIELD, workflowType) @@ -116,7 +119,8 @@ data class Workflow( builder.optionalUserField(USER_FIELD, user) } - builder.field(ENABLED_FIELD, enabled) + builder + .field(ENABLED_FIELD, enabled) .optionalTimeField(ENABLED_TIME_FIELD, enabledTime) .field(SCHEDULE_FIELD, schedule) .field(INPUTS_FIELD, inputs.toTypedArray()) @@ -130,7 +134,10 @@ data class Workflow( return builder.endObject() } - override fun fromDocument(id: String, version: Long): Workflow = copy(id = id, version = version) + override fun fromDocument( + id: String, + version: Long, + ): Workflow = copy(id = id, version = version) @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -189,16 +196,21 @@ data class Workflow( // This is defined here instead of in ScheduledJob to avoid having the ScheduledJob class know about all // the different subclasses and creating circular dependencies - val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - ScheduledJob::class.java, - ParseField(WORKFLOW_TYPE), - CheckedFunction { parse(it) } - ) + val XCONTENT_REGISTRY = + NamedXContentRegistry.Entry( + ScheduledJob::class.java, + ParseField(WORKFLOW_TYPE), + CheckedFunction { parse(it) }, + ) @JvmStatic @JvmOverloads @Throws(IOException::class) - fun parse(xcp: XContentParser, id: String = NO_ID, version: Long = NO_VERSION): Workflow { + fun parse( + xcp: XContentParser, + id: String = NO_ID, + version: Long = NO_VERSION, + ): Workflow { var name: String? = null var workflowType: String = WorkflowType.COMPOSITE.toString() var user: User? = null @@ -218,8 +230,14 @@ data class Workflow( xcp.nextToken() when (fieldName) { - SCHEMA_VERSION_FIELD -> schemaVersion = xcp.intValue() - NAME_FIELD -> name = xcp.text() + SCHEMA_VERSION_FIELD -> { + schemaVersion = xcp.intValue() + } + + NAME_FIELD -> { + name = xcp.text() + } + WORKFLOW_TYPE_FIELD -> { workflowType = xcp.text() val allowedTypes = WorkflowType.values().map { it.value } @@ -227,38 +245,58 @@ data class Workflow( throw IllegalStateException("Workflow type should be one of $allowedTypes") } } + USER_FIELD -> { user = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) null else User.parse(xcp) } - ENABLED_FIELD -> enabled = xcp.booleanValue() - SCHEDULE_FIELD -> schedule = Schedule.parse(xcp) + + ENABLED_FIELD -> { + enabled = xcp.booleanValue() + } + + SCHEDULE_FIELD -> { + schedule = Schedule.parse(xcp) + } + Monitor.TRIGGERS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { triggers.add(Trigger.parse(xcp)) } } + INPUTS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { val input = WorkflowInput.parse(xcp) inputs.add(input) } } - ENABLED_TIME_FIELD -> enabledTime = xcp.instant() - LAST_UPDATE_TIME_FIELD -> lastUpdateTime = xcp.instant() - AUDIT_DELEGATE_MONITOR_ALERTS_FIELD -> auditDelegateMonitorAlerts = xcp.booleanValue() + + ENABLED_TIME_FIELD -> { + enabledTime = xcp.instant() + } + + LAST_UPDATE_TIME_FIELD -> { + lastUpdateTime = xcp.instant() + } + + AUDIT_DELEGATE_MONITOR_ALERTS_FIELD -> { + auditDelegateMonitorAlerts = xcp.booleanValue() + } + OWNER_FIELD -> { owner = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) owner else xcp.text() } + else -> { xcp.skipChildren() } @@ -284,20 +322,16 @@ data class Workflow( inputs.toList(), owner, triggers, - auditDelegateMonitorAlerts + auditDelegateMonitorAlerts, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Workflow? { - return Workflow(sin) - } + fun readFrom(sin: StreamInput): Workflow? = Workflow(sin) @Suppress("UNCHECKED_CAST") - fun suppressWarning(map: MutableMap?): MutableMap { - return map as MutableMap - } + fun suppressWarning(map: MutableMap?): MutableMap = map as MutableMap private const val DEFAULT_OWNER = "alerting" } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowInput.kt index d9fd2129..54b8a616 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowInput.kt @@ -7,41 +7,41 @@ import org.opensearch.core.xcontent.XContentParserUtils import java.io.IOException interface WorkflowInput : BaseModel { + enum class Type( + val value: String, + ) { + COMPOSITE_INPUT(CompositeInput.COMPOSITE_INPUT_FIELD), + ; - enum class Type(val value: String) { - COMPOSITE_INPUT(CompositeInput.COMPOSITE_INPUT_FIELD); - - override fun toString(): String { - return value - } + override fun toString(): String = value } companion object { - @Throws(IOException::class) fun parse(xcp: XContentParser): WorkflowInput { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, xcp.currentToken(), xcp) XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, xcp.nextToken(), xcp) XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, xcp.nextToken(), xcp) - val input = if (xcp.currentName() == Type.COMPOSITE_INPUT.value) { - CompositeInput.parse(xcp) - } else { - throw IllegalStateException("Unexpected input type when reading Input") - } + val input = + if (xcp.currentName() == Type.COMPOSITE_INPUT.value) { + CompositeInput.parse(xcp) + } else { + throw IllegalStateException("Unexpected input type when reading Input") + } XContentParserUtils.ensureExpectedToken(XContentParser.Token.END_OBJECT, xcp.nextToken(), xcp) return input } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): WorkflowInput { - return when (val type = sin.readEnum(Type::class.java)) { + fun readFrom(sin: StreamInput): WorkflowInput = + when (val type = sin.readEnum(Type::class.java)) { Type.COMPOSITE_INPUT -> CompositeInput(sin) + // This shouldn't be reachable but ensuring exhaustiveness as Kotlin warns // enum can be null in Java else -> throw IllegalStateException("Unexpected input [$type] when reading Trigger") } - } } fun name(): String diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowMetadata.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowMetadata.kt index 48deaed6..5d0193ac 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowMetadata.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowMetadata.kt @@ -22,16 +22,16 @@ data class WorkflowMetadata( val workflowId: String, val monitorIds: List, val latestRunTime: Instant, - val latestExecutionId: String -) : Writeable, ToXContent { - + val latestExecutionId: String, +) : Writeable, + ToXContent { @Throws(IOException::class) constructor(sin: StreamInput) : this( id = sin.readString(), workflowId = sin.readString(), monitorIds = sin.readStringList(), latestRunTime = sin.readInstant(), - latestExecutionId = sin.readString() + latestExecutionId = sin.readString(), ) override fun writeTo(out: StreamOutput) { @@ -42,10 +42,14 @@ data class WorkflowMetadata( out.writeString(latestExecutionId) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { builder.startObject() if (params.paramAsBoolean("with_type", false)) builder.startObject(METADATA) - builder.field(WORKFLOW_ID_FIELD, workflowId) + builder + .field(WORKFLOW_ID_FIELD, workflowId) .field(MONITOR_IDS_FIELD, monitorIds) .optionalTimeField(LATEST_RUN_TIME, latestRunTime) .field(LATEST_EXECUTION_ID, latestExecutionId) @@ -75,15 +79,24 @@ data class WorkflowMetadata( xcp.nextToken() when (fieldName) { - WORKFLOW_ID_FIELD -> workflowId = xcp.text() + WORKFLOW_ID_FIELD -> { + workflowId = xcp.text() + } + MONITOR_IDS_FIELD -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { monitorIds.add(xcp.text()) } } - LATEST_RUN_TIME -> latestRunTime = xcp.instant()!! - LATEST_EXECUTION_ID -> latestExecutionId = xcp.text() + + LATEST_RUN_TIME -> { + latestRunTime = xcp.instant()!! + } + + LATEST_EXECUTION_ID -> { + latestExecutionId = xcp.text() + } } } return WorkflowMetadata( @@ -91,15 +104,13 @@ data class WorkflowMetadata( workflowId = workflowId, monitorIds = monitorIds, latestRunTime = latestRunTime, - latestExecutionId = latestExecutionId + latestExecutionId = latestExecutionId, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): WorkflowMetadata { - return WorkflowMetadata(sin) - } + fun readFrom(sin: StreamInput): WorkflowMetadata = WorkflowMetadata(sin) fun getId(workflowId: String? = null) = "$workflowId-metadata" } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt index a83b8815..bbf5b1b1 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt @@ -20,12 +20,11 @@ data class WorkflowRunContext( val chainedMonitorId: String?, val matchingDocIdsPerIndex: Map>, val auditDelegateMonitorAlerts: Boolean, - val findingIds: List? = null -) : Writeable, ToXContentObject { + val findingIds: List? = null, +) : Writeable, + ToXContentObject { companion object { - fun readFrom(sin: StreamInput): WorkflowRunContext { - return WorkflowRunContext(sin) - } + fun readFrom(sin: StreamInput): WorkflowRunContext = WorkflowRunContext(sin) } constructor(sin: StreamInput) : this( @@ -34,7 +33,7 @@ data class WorkflowRunContext( chainedMonitorId = sin.readOptionalString(), matchingDocIdsPerIndex = sin.readMap() as Map>, auditDelegateMonitorAlerts = sin.readBoolean(), - findingIds = if (sin.version.onOrAfter(Version.V_2_15_0)) sin.readOptionalStringList() else emptyList() + findingIds = if (sin.version.onOrAfter(Version.V_2_15_0)) sin.readOptionalStringList() else emptyList(), ) override fun writeTo(out: StreamOutput) { @@ -48,8 +47,12 @@ data class WorkflowRunContext( } } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params?): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params?, + ): XContentBuilder { + builder + .startObject() .field("workflow_id", workflowId) .field("workflow_metadata_id", workflowMetadataId) .field("chained_monitor_id", chainedMonitorId) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunResult.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunResult.kt index 1b5fe3d8..32281863 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunResult.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunResult.kt @@ -22,9 +22,9 @@ data class WorkflowRunResult( var executionEndTime: Instant? = null, val executionId: String, val error: Exception? = null, - val triggerResults: Map = mapOf() -) : Writeable, ToXContent { - + val triggerResults: Map = mapOf(), +) : Writeable, + ToXContent { @Throws(IOException::class) @Suppress("UNCHECKED_CAST") constructor(sin: StreamInput) : this( @@ -35,7 +35,7 @@ data class WorkflowRunResult( executionEndTime = sin.readOptionalInstant(), executionId = sin.readString(), error = sin.readException(), - triggerResults = suppressWarning(sin.readMap()) as Map + triggerResults = suppressWarning(sin.readMap()) as Map, ) override fun writeTo(out: StreamOutput) { @@ -49,7 +49,10 @@ data class WorkflowRunResult( out.writeMap(triggerResults) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { builder.startObject() builder.field("execution_id", executionId) builder.field("workflow_name", workflowName) @@ -59,7 +62,8 @@ data class WorkflowRunResult( for (monitorResult in monitorRunResults) { monitorResult.toXContent(builder, ToXContent.EMPTY_PARAMS) } - builder.endArray() + builder + .endArray() .field("execution_start_time", executionStartTime) .field("execution_end_time", executionEndTime) .field("error", error?.message) @@ -70,13 +74,9 @@ data class WorkflowRunResult( companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): WorkflowRunResult { - return WorkflowRunResult(sin) - } + fun readFrom(sin: StreamInput): WorkflowRunResult = WorkflowRunResult(sin) @Suppress("UNCHECKED_CAST") - fun suppressWarning(map: MutableMap?): Map { - return map as Map - } + fun suppressWarning(map: MutableMap?): Map = map as Map } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/action/Action.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/action/Action.kt index 88d15210..9a8839fd 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/action/Action.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/action/Action.kt @@ -19,9 +19,8 @@ data class Action( val throttleEnabled: Boolean, val throttle: Throttle?, val id: String = UUIDs.base64UUID(), - val actionExecutionPolicy: ActionExecutionPolicy? = null + val actionExecutionPolicy: ActionExecutionPolicy? = null, ) : BaseModel { - init { if (subjectTemplate != null) { require(subjectTemplate.lang == MUSTACHE) { "subject_template must be a mustache script" } @@ -42,16 +41,21 @@ data class Action( sin.readBoolean(), // throttleEnabled sin.readOptionalWriteable(::Throttle), // throttle sin.readString(), // id - sin.readOptionalWriteable(::ActionExecutionPolicy) // actionExecutionPolicy + sin.readOptionalWriteable(::ActionExecutionPolicy), // actionExecutionPolicy ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - val xContentBuilder = builder.startObject() - .field(ID_FIELD, id) - .field(NAME_FIELD, name) - .field(DESTINATION_ID_FIELD, destinationId) - .field(MESSAGE_TEMPLATE_FIELD, messageTemplate) - .field(THROTTLE_ENABLED_FIELD, throttleEnabled) + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + val xContentBuilder = + builder + .startObject() + .field(ID_FIELD, id) + .field(NAME_FIELD, name) + .field(DESTINATION_ID_FIELD, destinationId) + .field(MESSAGE_TEMPLATE_FIELD, messageTemplate) + .field(THROTTLE_ENABLED_FIELD, throttleEnabled) if (subjectTemplate != null) { xContentBuilder.field(SUBJECT_TEMPLATE_FIELD, subjectTemplate) } @@ -64,14 +68,13 @@ data class Action( return xContentBuilder.endObject() } - fun asTemplateArg(): Map { - return mapOf( + fun asTemplateArg(): Map = + mapOf( ID_FIELD to id, NAME_FIELD to name, DESTINATION_ID_FIELD to destinationId, - THROTTLE_ENABLED_FIELD to throttleEnabled + THROTTLE_ENABLED_FIELD to throttleEnabled, ) - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -131,30 +134,48 @@ data class Action( val fieldName = xcp.currentName() xcp.nextToken() when (fieldName) { - ID_FIELD -> id = xcp.text() - NAME_FIELD -> name = xcp.textOrNull() - DESTINATION_ID_FIELD -> destinationId = xcp.textOrNull() + ID_FIELD -> { + id = xcp.text() + } + + NAME_FIELD -> { + name = xcp.textOrNull() + } + + DESTINATION_ID_FIELD -> { + destinationId = xcp.textOrNull() + } + SUBJECT_TEMPLATE_FIELD -> { - subjectTemplate = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { - null - } else { - Script.parse(xcp, Script.DEFAULT_TEMPLATE_LANG) - } + subjectTemplate = + if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + null + } else { + Script.parse(xcp, Script.DEFAULT_TEMPLATE_LANG) + } } - MESSAGE_TEMPLATE_FIELD -> messageTemplate = Script.parse(xcp, Script.DEFAULT_TEMPLATE_LANG) + + MESSAGE_TEMPLATE_FIELD -> { + messageTemplate = Script.parse(xcp, Script.DEFAULT_TEMPLATE_LANG) + } + THROTTLE_FIELD -> { throttle = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) null else Throttle.parse(xcp) } + THROTTLE_ENABLED_FIELD -> { throttleEnabled = xcp.booleanValue() } + ACTION_EXECUTION_POLICY_FIELD -> { - actionExecutionPolicy = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { - null - } else { - ActionExecutionPolicy.parse(xcp) - } + actionExecutionPolicy = + if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + null + } else { + ActionExecutionPolicy.parse(xcp) + } } + else -> { throw IllegalStateException("Unexpected field: $fieldName, while parsing action") } @@ -173,14 +194,12 @@ data class Action( throttleEnabled, throttle, id = requireNotNull(id), - actionExecutionPolicy = actionExecutionPolicy + actionExecutionPolicy = actionExecutionPolicy, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Action { - return Action(sin) - } + fun readFrom(sin: StreamInput): Action = Action(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/action/ActionExecutionPolicy.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/action/ActionExecutionPolicy.kt index 024d9cb2..51527cc5 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/action/ActionExecutionPolicy.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/action/ActionExecutionPolicy.kt @@ -10,16 +10,19 @@ import org.opensearch.core.xcontent.XContentParserUtils import java.io.IOException data class ActionExecutionPolicy( - val actionExecutionScope: ActionExecutionScope + val actionExecutionScope: ActionExecutionScope, ) : BaseModel { - @Throws(IOException::class) constructor(sin: StreamInput) : this ( - ActionExecutionScope.readFrom(sin) // actionExecutionScope + ActionExecutionScope.readFrom(sin), // actionExecutionScope ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .field(ACTION_EXECUTION_SCOPE, actionExecutionScope) return builder.endObject() } @@ -53,15 +56,13 @@ data class ActionExecutionPolicy( } return ActionExecutionPolicy( - requireNotNull(actionExecutionScope) { "Action execution scope is null" } + requireNotNull(actionExecutionScope) { "Action execution scope is null" }, ) } @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): ActionExecutionPolicy { - return ActionExecutionPolicy(sin) - } + fun readFrom(sin: StreamInput): ActionExecutionPolicy = ActionExecutionPolicy(sin) /** * The default [ActionExecutionPolicy] configuration for Bucket-Level Monitors. @@ -70,9 +71,10 @@ data class ActionExecutionPolicy( * will need to be made depending on the desired behavior. */ fun getDefaultConfigurationForBucketLevelMonitor(): ActionExecutionPolicy { - val defaultActionExecutionScope = PerAlertActionScope( - actionableAlerts = setOf(AlertCategory.DEDUPED, AlertCategory.NEW) - ) + val defaultActionExecutionScope = + PerAlertActionScope( + actionableAlerts = setOf(AlertCategory.DEDUPED, AlertCategory.NEW), + ) return ActionExecutionPolicy(actionExecutionScope = defaultActionExecutionScope) } @@ -83,9 +85,10 @@ data class ActionExecutionPolicy( * will need to be made depending on the desired behavior. */ fun getDefaultConfigurationForDocumentLevelMonitor(): ActionExecutionPolicy { - val defaultActionExecutionScope = PerAlertActionScope( - actionableAlerts = setOf(AlertCategory.DEDUPED, AlertCategory.NEW) - ) + val defaultActionExecutionScope = + PerAlertActionScope( + actionableAlerts = setOf(AlertCategory.DEDUPED, AlertCategory.NEW), + ) return ActionExecutionPolicy(actionExecutionScope = defaultActionExecutionScope) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/action/ActionExecutionScope.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/action/ActionExecutionScope.kt index 6342c33e..c476098b 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/action/ActionExecutionScope.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/action/ActionExecutionScope.kt @@ -10,7 +10,6 @@ import org.opensearch.core.xcontent.XContentParserUtils import java.io.IOException sealed class ActionExecutionScope : BaseModel { - enum class Type { PER_ALERT, PER_EXECUTION } companion object { @@ -46,7 +45,7 @@ sealed class ActionExecutionScope : BaseModel { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) val allowedCategories = AlertCategory.values().map { it.toString() } while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { @@ -57,19 +56,26 @@ sealed class ActionExecutionScope : BaseModel { alertFilter.add(AlertCategory.valueOf(alertCategory)) } } - else -> throw IllegalArgumentException( - "Invalid field [$perAlertFieldName] found in per alert action execution scope." - ) + + else -> { + throw IllegalArgumentException( + "Invalid field [$perAlertFieldName] found in per alert action execution scope.", + ) + } } } } + PER_EXECUTION_FIELD -> { type = Type.PER_EXECUTION while (xcp.nextToken() != XContentParser.Token.END_OBJECT) { // empty while block } } - else -> throw IllegalArgumentException("Invalid field [$fieldName] found in action execution scope.") + + else -> { + throw IllegalArgumentException("Invalid field [$fieldName] found in action execution scope.") + } } } @@ -98,18 +104,21 @@ sealed class ActionExecutionScope : BaseModel { } data class PerAlertActionScope( - val actionableAlerts: Set + val actionableAlerts: Set, ) : ActionExecutionScope() { - @Throws(IOException::class) constructor(sin: StreamInput) : this( - sin.readSet { si -> si.readEnum(AlertCategory::class.java) } // alertFilter + sin.readSet { si -> si.readEnum(AlertCategory::class.java) }, // alertFilter ) override fun getExecutionScope(): Type = Type.PER_ALERT - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(PER_ALERT_FIELD) .field(ACTIONABLE_ALERTS_FIELD, actionableAlerts.toTypedArray()) .endObject() @@ -124,20 +133,15 @@ data class PerAlertActionScope( companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): PerAlertActionScope { - return PerAlertActionScope(sin) - } + fun readFrom(sin: StreamInput): PerAlertActionScope = PerAlertActionScope(sin) } } class PerExecutionActionScope() : ActionExecutionScope() { - @Throws(IOException::class) constructor(sin: StreamInput) : this() - override fun hashCode(): Int { - return javaClass.hashCode() - } + override fun hashCode(): Int = javaClass.hashCode() // Creating an equals method that just checks class type rather than reference since this is currently stateless. // Otherwise, it would have been a dataclass which would have handled this. @@ -149,8 +153,12 @@ class PerExecutionActionScope() : ActionExecutionScope() { override fun getExecutionScope(): Type = Type.PER_EXECUTION - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder + .startObject() .startObject(PER_EXECUTION_FIELD) .endObject() return builder.endObject() @@ -164,9 +172,7 @@ class PerExecutionActionScope() : ActionExecutionScope() { companion object { @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): PerExecutionActionScope { - return PerExecutionActionScope(sin) - } + fun readFrom(sin: StreamInput): PerExecutionActionScope = PerExecutionActionScope(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/action/Throttle.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/action/Throttle.kt index 79bdb6e3..9f6c4b12 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/action/Throttle.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/action/Throttle.kt @@ -14,21 +14,23 @@ import java.util.Locale data class Throttle( val value: Int, - val unit: ChronoUnit + val unit: ChronoUnit, ) : BaseModel { - @Throws(IOException::class) constructor(sin: StreamInput) : this ( sin.readInt(), // value - sin.readEnum(ChronoUnit::class.java) // unit + sin.readEnum(ChronoUnit::class.java), // unit ) - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(VALUE_FIELD, value) .field(UNIT_FIELD, unit.name) .endObject() - } @Throws(IOException::class) override fun writeTo(out: StreamOutput) { @@ -56,6 +58,7 @@ data class Throttle( require(StringUtils.equals(unitString, ChronoUnit.MINUTES.name), { "Only support MINUTES throttle unit currently" }) unit = ChronoUnit.valueOf(unitString) } + VALUE_FIELD -> { val currentToken = xcp.currentToken() require(currentToken != XContentParser.Token.VALUE_NULL, { "Throttle value can't be null" }) @@ -64,6 +67,7 @@ data class Throttle( value = xcp.intValue() require(value > 0, { "Can only set positive throttle period" }) } + else -> { XContentParserUtils.throwUnknownToken(currentToken, xcp.tokenLocation) } @@ -80,8 +84,6 @@ data class Throttle( @JvmStatic @Throws(IOException::class) - fun readFrom(sin: StreamInput): Throttle { - return Throttle(sin) - } + fun readFrom(sin: StreamInput): Throttle = Throttle(sin) } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteDocLevelMonitorInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteDocLevelMonitorInput.kt index 1e6184f3..4eef594c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteDocLevelMonitorInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteDocLevelMonitorInput.kt @@ -13,12 +13,14 @@ import org.opensearch.core.xcontent.XContentParserUtils import java.io.IOException import java.nio.ByteBuffer -data class RemoteDocLevelMonitorInput(val input: BytesReference, val docLevelMonitorInput: DocLevelMonitorInput) : Input { - +data class RemoteDocLevelMonitorInput( + val input: BytesReference, + val docLevelMonitorInput: DocLevelMonitorInput, +) : Input { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readBytesReference(), - DocLevelMonitorInput.readFrom(sin) + DocLevelMonitorInput.readFrom(sin), ) override fun asTemplateArg(): Map { @@ -26,22 +28,24 @@ data class RemoteDocLevelMonitorInput(val input: BytesReference, val docLevelMon return mapOf( RemoteDocLevelMonitorInput.INPUT_SIZE to bytes.size, RemoteDocLevelMonitorInput.INPUT_FIELD to bytes, - DOC_LEVEL_INPUT_FIELD to docLevelMonitorInput + DOC_LEVEL_INPUT_FIELD to docLevelMonitorInput, ) } - override fun name(): String { - return REMOTE_DOC_LEVEL_MONITOR_INPUT_FIELD - } + override fun name(): String = REMOTE_DOC_LEVEL_MONITOR_INPUT_FIELD override fun writeTo(out: StreamOutput) { out.writeBytesReference(input) docLevelMonitorInput.writeTo(out) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { val bytes = input.toBytesRef().bytes - return builder.startObject() + return builder + .startObject() .startObject(REMOTE_DOC_LEVEL_MONITOR_INPUT_FIELD) .field(RemoteMonitorInput.INPUT_SIZE, bytes.size) .field(RemoteMonitorInput.INPUT_FIELD, bytes) @@ -66,8 +70,14 @@ data class RemoteDocLevelMonitorInput(val input: BytesReference, val docLevelMon xcp.nextToken() when (fieldName) { - RemoteMonitorInput.INPUT_FIELD -> bytes = xcp.binaryValue() - RemoteMonitorInput.INPUT_SIZE -> size = xcp.intValue() + RemoteMonitorInput.INPUT_FIELD -> { + bytes = xcp.binaryValue() + } + + RemoteMonitorInput.INPUT_SIZE -> { + size = xcp.intValue() + } + Input.Type.DOCUMENT_LEVEL_INPUT.value -> { docLevelMonitorInput = DocLevelMonitorInput.parse(xcp) XContentParserUtils.ensureExpectedToken(XContentParser.Token.END_OBJECT, xcp.nextToken(), xcp) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteMonitorInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteMonitorInput.kt index 29a939ff..ff3dbb5c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteMonitorInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteMonitorInput.kt @@ -11,32 +11,35 @@ import org.opensearch.core.xcontent.XContentParserUtils import java.io.IOException import java.nio.ByteBuffer -data class RemoteMonitorInput(val input: BytesReference) : Input { - +data class RemoteMonitorInput( + val input: BytesReference, +) : Input { @Throws(IOException::class) constructor(sin: StreamInput) : this( - sin.readBytesReference() + sin.readBytesReference(), ) override fun asTemplateArg(): Map { val bytes = input.toBytesRef().bytes return mapOf( INPUT_SIZE to bytes.size, - INPUT_FIELD to bytes + INPUT_FIELD to bytes, ) } - override fun name(): String { - return REMOTE_MONITOR_INPUT_FIELD - } + override fun name(): String = REMOTE_MONITOR_INPUT_FIELD override fun writeTo(out: StreamOutput) { out.writeBytesReference(input) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { val bytes = input.toBytesRef().bytes - return builder.startObject() + return builder + .startObject() .startObject(REMOTE_MONITOR_INPUT_FIELD) .field(INPUT_SIZE, bytes.size) .field(INPUT_FIELD, bytes) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteMonitorTrigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteMonitorTrigger.kt index 0e89e5ba..944eb498 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteMonitorTrigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/remote/monitors/RemoteMonitorTrigger.kt @@ -21,7 +21,7 @@ data class RemoteMonitorTrigger( override val name: String, override val severity: String, override val actions: List, - val trigger: BytesReference + val trigger: BytesReference, ) : Trigger { @Throws(IOException::class) constructor(sin: StreamInput) : this( @@ -29,7 +29,7 @@ data class RemoteMonitorTrigger( sin.readString(), sin.readString(), sin.readList(::Action), - sin.readBytesReference() + sin.readBytesReference(), ) fun asTemplateArg(): Map { @@ -40,13 +40,11 @@ data class RemoteMonitorTrigger( Trigger.SEVERITY_FIELD to severity, Trigger.ACTIONS_FIELD to actions.map { it.asTemplateArg() }, TRIGGER_SIZE to bytes.size, - TRIGGER_FIELD to bytes + TRIGGER_FIELD to bytes, ) } - override fun name(): String { - return REMOTE_MONITOR_TRIGGER_FIELD - } + override fun name(): String = REMOTE_MONITOR_TRIGGER_FIELD override fun writeTo(out: StreamOutput) { out.writeString(id) @@ -56,9 +54,13 @@ data class RemoteMonitorTrigger( out.writeBytesReference(trigger) } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { val bytes = trigger.toBytesRef().bytes - return builder.startObject() + return builder + .startObject() .startObject(REMOTE_MONITOR_TRIGGER_FIELD) .field(Trigger.ID_FIELD, id) .field(Trigger.NAME_FIELD, name) @@ -75,11 +77,12 @@ data class RemoteMonitorTrigger( const val TRIGGER_SIZE = "size" const val REMOTE_MONITOR_TRIGGER_FIELD = "remote_monitor_trigger" - val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Trigger::class.java, - ParseField(REMOTE_MONITOR_TRIGGER_FIELD), - CheckedFunction { parseInner(it) } - ) + val XCONTENT_REGISTRY = + NamedXContentRegistry.Entry( + Trigger::class.java, + ParseField(REMOTE_MONITOR_TRIGGER_FIELD), + CheckedFunction { parseInner(it) }, + ) fun parseInner(xcp: XContentParser): RemoteMonitorTrigger { var id = UUIDs.base64UUID() // assign a default triggerId if one is not specified @@ -101,21 +104,36 @@ data class RemoteMonitorTrigger( xcp.nextToken() when (fieldName) { - Trigger.ID_FIELD -> id = xcp.text() - Trigger.NAME_FIELD -> name = xcp.text() - Trigger.SEVERITY_FIELD -> severity = xcp.text() + Trigger.ID_FIELD -> { + id = xcp.text() + } + + Trigger.NAME_FIELD -> { + name = xcp.text() + } + + Trigger.SEVERITY_FIELD -> { + severity = xcp.text() + } + Trigger.ACTIONS_FIELD -> { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_ARRAY, xcp.currentToken(), - xcp + xcp, ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { actions.add(Action.parse(xcp)) } } - TRIGGER_FIELD -> bytes = xcp.binaryValue() - TRIGGER_SIZE -> size = xcp.intValue() + + TRIGGER_FIELD -> { + bytes = xcp.binaryValue() + } + + TRIGGER_SIZE -> { + size = xcp.intValue() + } } xcp.nextToken() } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/util/AlertingException.kt b/src/main/kotlin/org/opensearch/commons/alerting/util/AlertingException.kt index 312758f0..e4a97630 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/util/AlertingException.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/util/AlertingException.kt @@ -20,11 +20,12 @@ private val log = LogManager.getLogger(AlertingException::class.java) /** * Converts into a user friendly message. */ -class AlertingException(message: String, val status: RestStatus, val ex: Exception) : OpenSearchException(message, ex) { - - override fun status(): RestStatus { - return status - } +class AlertingException( + message: String, + val status: RestStatus, + val ex: Exception, +) : OpenSearchException(message, ex) { + override fun status(): RestStatus = status companion object { @JvmStatic @@ -38,26 +39,32 @@ class AlertingException(message: String, val status: RestStatus, val ex: Excepti status = ex.status() friendlyMsg = "Configured indices are not found: ${ex.index}" } + is OpenSearchSecurityException -> { status = ex.status() friendlyMsg = "User doesn't have permissions to execute this action. Contact administrator." } + is OpenSearchStatusException -> { status = ex.status() friendlyMsg = ex.message as String } + is IllegalArgumentException -> { status = RestStatus.BAD_REQUEST friendlyMsg = ex.message as String } + is VersionConflictEngineException -> { status = ex.status() friendlyMsg = ex.message as String } + is InvalidIndexNameException -> { status = RestStatus.BAD_REQUEST friendlyMsg = ex.message as String } + else -> { if (!Strings.isNullOrEmpty(ex.message)) { friendlyMsg = ex.message as String diff --git a/src/main/kotlin/org/opensearch/commons/alerting/util/IndexPatternUtils.kt b/src/main/kotlin/org/opensearch/commons/alerting/util/IndexPatternUtils.kt index 6d38dc2f..892c299f 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/util/IndexPatternUtils.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/util/IndexPatternUtils.kt @@ -4,22 +4,23 @@ package org.opensearch.commons.alerting.util * Validates that index patterns, wildcards and regex are not used in index names. */ object IndexPatternUtils { - private val PATTERN_SPECIAL_CHARS = setOf( - '*', // wildcard for any number of characters - '?', // wildcard for single character - '+', // one or more quantifier - '[', // character class start - ']', // character class end - '(', // group start - ')', // group end - '{', // range quantifier start - '}', // range quantifier end - '|', // OR operator - '\\', // escape character - '.', // any character - '^', // start anchor/negation in character class - '$' // end anchor - ) + private val PATTERN_SPECIAL_CHARS = + setOf( + '*', // wildcard for any number of characters + '?', // wildcard for single character + '+', // one or more quantifier + '[', // character class start + ']', // character class end + '(', // group start + ')', // group end + '{', // range quantifier start + '}', // range quantifier end + '|', // OR operator + '\\', // escape character + '.', // any character + '^', // start anchor/negation in character class + '$', // end anchor + ) fun containsPatternSyntax(indexName: String): Boolean { if (indexName.isEmpty() || indexName == "_all") { @@ -34,8 +35,11 @@ object IndexPatternUtils { var i = 0 while (i < indexName.length) { when (val currentChar = indexName[i]) { - '\\' -> i += 2 // Skip escaped character + '\\' -> i += 2 + + // Skip escaped character in PATTERN_SPECIAL_CHARS -> return true + else -> i++ } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/util/IndexUtils.kt b/src/main/kotlin/org/opensearch/commons/alerting/util/IndexUtils.kt index 887e8430..65305a9a 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/util/IndexUtils.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/util/IndexUtils.kt @@ -38,10 +38,16 @@ class IndexUtils { const val MONITOR_MAX_TRIGGERS = 10 + @Suppress("ktlint:standard:property-naming", "ktlint:standard:backing-property-naming") const val _ID = "_id" + + @Suppress("ktlint:standard:property-naming", "ktlint:standard:backing-property-naming") const val _VERSION = "_version" + @Suppress("ktlint:standard:property-naming", "ktlint:standard:backing-property-naming") const val _SEQ_NO = "_seq_no" + + @Suppress("ktlint:standard:property-naming", "ktlint:standard:backing-property-naming") const val _PRIMARY_TERM = "_primary_term" var supportedClusterMetricsSettings: SupportedClusterMetricsSettings? = null @@ -52,21 +58,30 @@ fun Monitor.isBucketLevelMonitor(): Boolean = isMonitorOfStandardType() && Monitor.MonitorType.valueOf(this.monitorType.uppercase(Locale.ROOT)) == Monitor.MonitorType.BUCKET_LEVEL_MONITOR -fun XContentBuilder.optionalUserField(name: String, user: User?): XContentBuilder { +fun XContentBuilder.optionalUserField( + name: String, + user: User?, +): XContentBuilder { if (user == null) { return nullField(name) } return this.field(name, user) } -fun XContentBuilder.optionalUsernameField(name: String, user: User?): XContentBuilder { +fun XContentBuilder.optionalUsernameField( + name: String, + user: User?, +): XContentBuilder { if (user == null) { return nullField(name) } return this.field(name, user.name) } -fun XContentBuilder.optionalTimeField(name: String, instant: Instant?): XContentBuilder { +fun XContentBuilder.optionalTimeField( + name: String, + instant: Instant?, +): XContentBuilder { if (instant == null) { return nullField(name) } @@ -74,16 +89,21 @@ fun XContentBuilder.optionalTimeField(name: String, instant: Instant?): XContent return this.timeField(name, "${name}_in_millis", instant.toEpochMilli()) } -fun XContentParser.instant(): Instant? { - return when { - currentToken() == XContentParser.Token.VALUE_NULL -> null - currentToken().isValue -> Instant.ofEpochMilli(longValue()) +fun XContentParser.instant(): Instant? = + when { + currentToken() == XContentParser.Token.VALUE_NULL -> { + null + } + + currentToken().isValue -> { + Instant.ofEpochMilli(longValue()) + } + else -> { XContentParserUtils.throwUnknownToken(currentToken(), tokenLocation) null // unreachable } } -} /** * Extension function for ES 6.3 and above that duplicates the ES 6.2 XContentBuilder.string() method. @@ -91,7 +111,11 @@ fun XContentParser.instant(): Instant? { fun XContentBuilder.string(): String = BytesReference.bytes(this).utf8ToString() fun Monitor.isMonitorOfStandardType(): Boolean { - val standardMonitorTypes = Monitor.MonitorType.values().map { it.value.uppercase(Locale.ROOT) }.toSet() + val standardMonitorTypes = + Monitor.MonitorType + .values() + .map { it.value.uppercase(Locale.ROOT) } + .toSet() return standardMonitorTypes.contains(this.monitorType.uppercase(Locale.ROOT)) } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterface.kt b/src/main/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterface.kt index 40822303..1cc4a191 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterface.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterface.kt @@ -43,7 +43,6 @@ import org.opensearch.transport.client.node.NodeClient * All the transport action plugin interfaces for the Notification plugin */ object NotificationsPluginInterface { - /** * Create notification configuration. * @param client Node client for making transport action @@ -53,12 +52,12 @@ object NotificationsPluginInterface { fun createNotificationConfig( client: NodeClient, request: CreateNotificationConfigRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( CREATE_NOTIFICATION_CONFIG_ACTION_TYPE, request, - wrapActionListener(listener) { response -> recreateObject(response) { CreateNotificationConfigResponse(it) } } + wrapActionListener(listener) { response -> recreateObject(response) { CreateNotificationConfigResponse(it) } }, ) } @@ -71,12 +70,12 @@ object NotificationsPluginInterface { fun updateNotificationConfig( client: NodeClient, request: UpdateNotificationConfigRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( UPDATE_NOTIFICATION_CONFIG_ACTION_TYPE, request, - wrapActionListener(listener) { response -> recreateObject(response) { UpdateNotificationConfigResponse(it) } } + wrapActionListener(listener) { response -> recreateObject(response) { UpdateNotificationConfigResponse(it) } }, ) } @@ -89,12 +88,12 @@ object NotificationsPluginInterface { fun deleteNotificationConfig( client: NodeClient, request: DeleteNotificationConfigRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( DELETE_NOTIFICATION_CONFIG_ACTION_TYPE, request, - wrapActionListener(listener) { response -> recreateObject(response) { DeleteNotificationConfigResponse(it) } } + wrapActionListener(listener) { response -> recreateObject(response) { DeleteNotificationConfigResponse(it) } }, ) } @@ -107,12 +106,12 @@ object NotificationsPluginInterface { fun getNotificationConfig( client: NodeClient, request: GetNotificationConfigRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( GET_NOTIFICATION_CONFIG_ACTION_TYPE, request, - wrapActionListener(listener) { response -> recreateObject(response) { GetNotificationConfigResponse(it) } } + wrapActionListener(listener) { response -> recreateObject(response) { GetNotificationConfigResponse(it) } }, ) } @@ -125,12 +124,12 @@ object NotificationsPluginInterface { fun getPluginFeatures( client: NodeClient, request: GetPluginFeaturesRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( GET_PLUGIN_FEATURES_ACTION_TYPE, request, - wrapActionListener(listener) { response -> recreateObject(response) { GetPluginFeaturesResponse(it) } } + wrapActionListener(listener) { response -> recreateObject(response) { GetPluginFeaturesResponse(it) } }, ) } @@ -143,12 +142,12 @@ object NotificationsPluginInterface { fun getChannelList( client: NodeClient, request: GetChannelListRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( GET_CHANNEL_LIST_ACTION_TYPE, request, - wrapActionListener(listener) { response -> recreateObject(response) { GetChannelListResponse(it) } } + wrapActionListener(listener) { response -> recreateObject(response) { GetChannelListResponse(it) } }, ) } @@ -165,7 +164,7 @@ object NotificationsPluginInterface { eventSource: EventSource, channelMessage: ChannelMessage, channelIds: List, - listener: ActionListener + listener: ActionListener, ) { val threadContext: String? = client.threadPool().threadContext.getTransient(OPENSEARCH_SECURITY_USER_INFO_THREAD_CONTEXT) @@ -173,7 +172,7 @@ object NotificationsPluginInterface { wrapper.execute( SEND_NOTIFICATION_ACTION_TYPE, SendNotificationRequest(eventSource, channelMessage, channelIds, threadContext), - wrapActionListener(listener) { response -> recreateObject(response) { SendNotificationResponse(it) } } + wrapActionListener(listener) { response -> recreateObject(response) { SendNotificationResponse(it) } }, ) } @@ -187,12 +186,12 @@ object NotificationsPluginInterface { fun publishLegacyNotification( client: NodeClient, request: LegacyPublishNotificationRequest, - listener: ActionListener + listener: ActionListener, ) { client.execute( LEGACY_PUBLISH_NOTIFICATION_ACTION_TYPE, request, - wrapActionListener(listener) { response -> recreateObject(response) { LegacyPublishNotificationResponse(it) } } + wrapActionListener(listener) { response -> recreateObject(response) { LegacyPublishNotificationResponse(it) } }, ) } @@ -205,9 +204,9 @@ object NotificationsPluginInterface { @Suppress("UNCHECKED_CAST") private fun wrapActionListener( listener: ActionListener, - recreate: (Writeable) -> Response - ): ActionListener { - return object : ActionListener { + recreate: (Writeable) -> Response, + ): ActionListener = + object : ActionListener { override fun onResponse(response: ActionResponse) { val recreated = response as? Response ?: recreate(response) listener.onResponse(recreated) @@ -217,5 +216,4 @@ object NotificationsPluginInterface { listener.onFailure(exception) } } as ActionListener - } } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/BaseResponse.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/BaseResponse.kt index ecbbf4e9..b8a01609 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/BaseResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/BaseResponse.kt @@ -14,8 +14,9 @@ import java.io.IOException /** * Base response which give REST status. */ -abstract class BaseResponse : ActionResponse, ToXContentObject { - +abstract class BaseResponse : + ActionResponse, + ToXContentObject { /** * constructor for creating the class */ @@ -31,7 +32,5 @@ abstract class BaseResponse : ActionResponse, ToXContentObject { * get rest status for the response. Useful override for multi-status response. * @return RestStatus for the response */ - open fun getStatus(): RestStatus { - return RestStatus.OK - } + open fun getStatus(): RestStatus = RestStatus.OK } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequest.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequest.kt index dea36ef0..5d878ff4 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequest.kt @@ -25,7 +25,9 @@ import java.io.IOException /** * Action request for creating new configuration. */ -class CreateNotificationConfigRequest : ActionRequest, ToXContentObject { +class CreateNotificationConfigRequest : + ActionRequest, + ToXContentObject { val configId: String? val notificationConfig: NotificationConfig @@ -44,21 +46,30 @@ class CreateNotificationConfigRequest : ActionRequest, ToXContentObject { */ @JvmStatic @Throws(IOException::class) - fun parse(parser: XContentParser, id: String? = null): CreateNotificationConfigRequest { + fun parse( + parser: XContentParser, + id: String? = null, + ): CreateNotificationConfigRequest { var configId: String? = id var notificationConfig: NotificationConfig? = null XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - CONFIG_ID_TAG -> configId = parser.textOrNull() - CONFIG_TAG -> notificationConfig = NotificationConfig.parse(parser) + CONFIG_ID_TAG -> { + configId = parser.textOrNull() + } + + CONFIG_TAG -> { + notificationConfig = NotificationConfig.parse(parser) + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing CreateNotificationConfigRequest") @@ -76,9 +87,13 @@ class CreateNotificationConfigRequest : ActionRequest, ToXContentObject { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .fieldIfNotNull(CONFIG_ID_TAG, configId) .field(CONFIG_TAG, notificationConfig) .endObject() @@ -116,7 +131,5 @@ class CreateNotificationConfigRequest : ActionRequest, ToXContentObject { /** * {@inheritDoc} */ - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigResponse.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigResponse.kt index 3e32a49b..5aa74093 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigResponse.kt @@ -41,13 +41,16 @@ class CreateNotificationConfigResponse : BaseResponse { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - CONFIG_ID_TAG -> configId = parser.text() + CONFIG_ID_TAG -> { + configId = parser.text() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing CreateNotificationConfigResponse") @@ -86,9 +89,13 @@ class CreateNotificationConfigResponse : BaseResponse { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(CONFIG_ID_TAG, configId) .endObject() } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigRequest.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigRequest.kt index 6dd78923..77251167 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigRequest.kt @@ -23,7 +23,9 @@ import java.io.IOException /** * Action Response for creating new configuration. */ -class DeleteNotificationConfigRequest : ActionRequest, ToXContentObject { +class DeleteNotificationConfigRequest : + ActionRequest, + ToXContentObject { val configIds: Set companion object { @@ -46,13 +48,16 @@ class DeleteNotificationConfigRequest : ActionRequest, ToXContentObject { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - CONFIG_ID_LIST_TAG -> configIds = parser.stringList().toSet() + CONFIG_ID_LIST_TAG -> { + configIds = parser.stringList().toSet() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing DeleteNotificationConfigRequest") @@ -92,9 +97,13 @@ class DeleteNotificationConfigRequest : ActionRequest, ToXContentObject { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(CONFIG_ID_LIST_TAG, configIds) .endObject() } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigResponse.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigResponse.kt index 2337355f..d4d5255f 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigResponse.kt @@ -46,13 +46,16 @@ class DeleteNotificationConfigResponse : BaseResponse { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - DELETE_RESPONSE_LIST_TAG -> configIdToStatus = convertMapStrings(parser.mapStrings()) + DELETE_RESPONSE_LIST_TAG -> { + configIdToStatus = convertMapStrings(parser.mapStrings()) + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing DeleteNotificationConfigResponse") @@ -63,9 +66,8 @@ class DeleteNotificationConfigResponse : BaseResponse { return DeleteNotificationConfigResponse(configIdToStatus) } - private fun convertMapStrings(inputMap: Map): Map { - return inputMap.mapValues { RestStatus.valueOf(it.value) } - } + private fun convertMapStrings(inputMap: Map): Map = + inputMap.mapValues { RestStatus.valueOf(it.value) } } /** @@ -95,9 +97,13 @@ class DeleteNotificationConfigResponse : BaseResponse { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(DELETE_RESPONSE_LIST_TAG, configIdToStatus) .endObject() } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/GetChannelListRequest.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/GetChannelListRequest.kt index c62f38a7..2899639d 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/GetChannelListRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/GetChannelListRequest.kt @@ -21,7 +21,9 @@ import java.io.IOException /** * This request is plugin-only call. i.e. REST interface is not exposed. */ -class GetChannelListRequest : ActionRequest, ToXContentObject { +class GetChannelListRequest : + ActionRequest, + ToXContentObject { val compact: Boolean // Dummy request parameter for transport request companion object { @@ -44,13 +46,16 @@ class GetChannelListRequest : ActionRequest, ToXContentObject { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - COMPACT_TAG -> compact = parser.booleanValue() + COMPACT_TAG -> { + compact = parser.booleanValue() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing GetChannelListRequest") @@ -64,11 +69,14 @@ class GetChannelListRequest : ActionRequest, ToXContentObject { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - return builder!!.startObject() + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder = + builder!! + .startObject() .field(COMPACT_TAG, compact) .endObject() - } /** * constructor for creating the class @@ -98,7 +106,5 @@ class GetChannelListRequest : ActionRequest, ToXContentObject { /** * {@inheritDoc} */ - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/GetChannelListResponse.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/GetChannelListResponse.kt index 57a94a4e..966d419b 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/GetChannelListResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/GetChannelListResponse.kt @@ -20,7 +20,6 @@ class GetChannelListResponse : BaseResponse { val searchResult: ChannelList companion object { - /** * reader to create instance of class from writable. */ @@ -32,9 +31,7 @@ class GetChannelListResponse : BaseResponse { */ @JvmStatic @Throws(IOException::class) - fun parse(parser: XContentParser): GetChannelListResponse { - return GetChannelListResponse(ChannelList(parser)) - } + fun parse(parser: XContentParser): GetChannelListResponse = GetChannelListResponse(ChannelList(parser)) } /** @@ -64,7 +61,8 @@ class GetChannelListResponse : BaseResponse { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - return searchResult.toXContent(builder, params) - } + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder = searchResult.toXContent(builder, params) } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigRequest.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigRequest.kt index 34485a3c..4231c16d 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigRequest.kt @@ -34,7 +34,9 @@ import java.io.IOException /** * Action Request for getting notification configuration. */ -class GetNotificationConfigRequest : ActionRequest, ToXContentObject { +class GetNotificationConfigRequest : + ActionRequest, + ToXContentObject { val configIds: Set val fromIndex: Int val maxItems: Int @@ -67,18 +69,36 @@ class GetNotificationConfigRequest : ActionRequest, ToXContentObject { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - CONFIG_ID_LIST_TAG -> configIdList = parser.stringList().toSet() - FROM_INDEX_TAG -> fromIndex = parser.intValue() - MAX_ITEMS_TAG -> maxItems = parser.intValue() - SORT_FIELD_TAG -> sortField = parser.textOrNull() - SORT_ORDER_TAG -> sortOrder = SortOrder.fromString(parser.text()) - FILTER_PARAM_LIST_TAG -> filterParams = parser.mapStrings() + CONFIG_ID_LIST_TAG -> { + configIdList = parser.stringList().toSet() + } + + FROM_INDEX_TAG -> { + fromIndex = parser.intValue() + } + + MAX_ITEMS_TAG -> { + maxItems = parser.intValue() + } + + SORT_FIELD_TAG -> { + sortField = parser.textOrNull() + } + + SORT_ORDER_TAG -> { + sortOrder = SortOrder.fromString(parser.text()) + } + + FILTER_PARAM_LIST_TAG -> { + filterParams = parser.mapStrings() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing GetNotificationConfigRequest") @@ -92,8 +112,12 @@ class GetNotificationConfigRequest : ActionRequest, ToXContentObject { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - return builder!!.startObject() + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder = + builder!! + .startObject() .field(CONFIG_ID_LIST_TAG, configIds) .field(FROM_INDEX_TAG, fromIndex) .field(MAX_ITEMS_TAG, maxItems) @@ -101,7 +125,6 @@ class GetNotificationConfigRequest : ActionRequest, ToXContentObject { .fieldIfNotNull(SORT_ORDER_TAG, sortOrder) .field(FILTER_PARAM_LIST_TAG, filterParams) .endObject() - } /** * constructor for creating the class @@ -118,7 +141,7 @@ class GetNotificationConfigRequest : ActionRequest, ToXContentObject { maxItems: Int = DEFAULT_MAX_ITEMS, sortField: String? = null, sortOrder: SortOrder? = null, - filterParams: Map = mapOf() + filterParams: Map = mapOf(), ) { this.configIds = configIds this.fromIndex = fromIndex diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigResponse.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigResponse.kt index 6723c015..68e29be0 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigResponse.kt @@ -20,7 +20,6 @@ class GetNotificationConfigResponse : BaseResponse { val searchResult: NotificationConfigSearchResult companion object { - /** * reader to create instance of class from writable. */ @@ -32,9 +31,8 @@ class GetNotificationConfigResponse : BaseResponse { */ @JvmStatic @Throws(IOException::class) - fun parse(parser: XContentParser): GetNotificationConfigResponse { - return GetNotificationConfigResponse(NotificationConfigSearchResult(parser)) - } + fun parse(parser: XContentParser): GetNotificationConfigResponse = + GetNotificationConfigResponse(NotificationConfigSearchResult(parser)) } /** @@ -64,7 +62,8 @@ class GetNotificationConfigResponse : BaseResponse { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - return searchResult.toXContent(builder, params) - } + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder = searchResult.toXContent(builder, params) } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesRequest.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesRequest.kt index 0eb0d14d..9f4c7ef2 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesRequest.kt @@ -21,7 +21,9 @@ import java.io.IOException /** * Action Request for getting notification plugin features. */ -class GetPluginFeaturesRequest : ActionRequest, ToXContentObject { +class GetPluginFeaturesRequest : + ActionRequest, + ToXContentObject { val compact: Boolean // Dummy request parameter for transport request companion object { @@ -44,13 +46,16 @@ class GetPluginFeaturesRequest : ActionRequest, ToXContentObject { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - COMPACT_TAG -> compact = parser.booleanValue() + COMPACT_TAG -> { + compact = parser.booleanValue() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing GetPluginFeaturesRequest") @@ -64,11 +69,14 @@ class GetPluginFeaturesRequest : ActionRequest, ToXContentObject { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - return builder!!.startObject() + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder = + builder!! + .startObject() .field(COMPACT_TAG, compact) .endObject() - } /** * constructor for creating the class @@ -98,7 +106,5 @@ class GetPluginFeaturesRequest : ActionRequest, ToXContentObject { /** * {@inheritDoc} */ - override fun validate(): ActionRequestValidationException? { - return null - } + override fun validate(): ActionRequestValidationException? = null } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesResponse.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesResponse.kt index 41a80875..acb38325 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesResponse.kt @@ -47,14 +47,20 @@ class GetPluginFeaturesResponse : BaseResponse { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - ALLOWED_CONFIG_TYPE_LIST_TAG -> allowedConfigTypeList = parser.stringList() - PLUGIN_FEATURES_TAG -> pluginFeatures = parser.mapStrings() + ALLOWED_CONFIG_TYPE_LIST_TAG -> { + allowedConfigTypeList = parser.stringList() + } + + PLUGIN_FEATURES_TAG -> { + pluginFeatures = parser.mapStrings() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing DeleteNotificationConfigResponse") @@ -70,12 +76,15 @@ class GetPluginFeaturesResponse : BaseResponse { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - return builder!!.startObject() + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder = + builder!! + .startObject() .field(ALLOWED_CONFIG_TYPE_LIST_TAG, allowedConfigTypeList) .field(PLUGIN_FEATURES_TAG, pluginFeatures) .endObject() - } /** * constructor for creating the class @@ -84,7 +93,7 @@ class GetPluginFeaturesResponse : BaseResponse { */ constructor( allowedConfigTypeList: List, - pluginFeatures: Map + pluginFeatures: Map, ) { this.allowedConfigTypeList = allowedConfigTypeList this.pluginFeatures = pluginFeatures diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationRequest.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationRequest.kt index 7d8cf391..ad76aa19 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationRequest.kt @@ -38,7 +38,7 @@ class LegacyPublishNotificationRequest : ActionRequest { * @param baseMessage the base message to send */ constructor( - baseMessage: LegacyBaseMessage + baseMessage: LegacyBaseMessage, ) { this.baseMessage = baseMessage } @@ -48,13 +48,14 @@ class LegacyPublishNotificationRequest : ActionRequest { */ @Throws(IOException::class) constructor(input: StreamInput) : super(input) { - baseMessage = when (requireNotNull(input.readEnum(LegacyDestinationType::class.java)) { "Destination type cannot be null" }) { - LegacyDestinationType.LEGACY_CHIME -> LegacyChimeMessage(input) - LegacyDestinationType.LEGACY_CUSTOM_WEBHOOK -> LegacyCustomWebhookMessage(input) - LegacyDestinationType.LEGACY_SLACK -> LegacySlackMessage(input) - LegacyDestinationType.LEGACY_EMAIL -> LegacyEmailMessage(input) - LegacyDestinationType.LEGACY_SNS -> LegacySNSMessage(input) - } + baseMessage = + when (requireNotNull(input.readEnum(LegacyDestinationType::class.java)) { "Destination type cannot be null" }) { + LegacyDestinationType.LEGACY_CHIME -> LegacyChimeMessage(input) + LegacyDestinationType.LEGACY_CUSTOM_WEBHOOK -> LegacyCustomWebhookMessage(input) + LegacyDestinationType.LEGACY_SLACK -> LegacySlackMessage(input) + LegacyDestinationType.LEGACY_EMAIL -> LegacyEmailMessage(input) + LegacyDestinationType.LEGACY_SNS -> LegacySNSMessage(input) + } } /** diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationResponse.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationResponse.kt index c6084358..06a95f24 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationResponse.kt @@ -51,7 +51,9 @@ class LegacyPublishNotificationResponse : BaseResponse { } // This class is only used across transport wire and does not need to implement toXContent - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = throw IllegalStateException("Legacy notification response is not intended for REST or persistence and does not support XContent.") - } } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/SendNotificationRequest.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/SendNotificationRequest.kt index 060ae545..ce72de19 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/SendNotificationRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/SendNotificationRequest.kt @@ -29,7 +29,9 @@ import java.io.IOException /** * Action Request to send notification. */ -class SendNotificationRequest : ActionRequest, ToXContentObject { +class SendNotificationRequest : + ActionRequest, + ToXContentObject { val eventSource: EventSource val channelMessage: ChannelMessage val channelIds: List @@ -58,16 +60,28 @@ class SendNotificationRequest : ActionRequest, ToXContentObject { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - EVENT_SOURCE_TAG -> eventSource = EventSource.parse(parser) - CHANNEL_MESSAGE_TAG -> channelMessage = ChannelMessage.parse(parser) - CHANNEL_ID_LIST_TAG -> channelIds = parser.stringList() - THREAD_CONTEXT_TAG -> threadContext = parser.textOrNull() + EVENT_SOURCE_TAG -> { + eventSource = EventSource.parse(parser) + } + + CHANNEL_MESSAGE_TAG -> { + channelMessage = ChannelMessage.parse(parser) + } + + CHANNEL_ID_LIST_TAG -> { + channelIds = parser.stringList() + } + + THREAD_CONTEXT_TAG -> { + threadContext = parser.textOrNull() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing SendNotificationRequest") @@ -92,7 +106,7 @@ class SendNotificationRequest : ActionRequest, ToXContentObject { eventSource: EventSource, channelMessage: ChannelMessage, channelIds: List, - threadContext: String? + threadContext: String?, ) { this.eventSource = eventSource this.channelMessage = channelMessage @@ -126,9 +140,13 @@ class SendNotificationRequest : ActionRequest, ToXContentObject { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(EVENT_SOURCE_TAG, eventSource) .field(CHANNEL_MESSAGE_TAG, channelMessage) .field(CHANNEL_ID_LIST_TAG, channelIds) diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponse.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponse.kt index e3642e1b..bfefe63d 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponse.kt @@ -20,7 +20,6 @@ class SendNotificationResponse : BaseResponse { val notificationEvent: NotificationEvent companion object { - /** * reader to create instance of class from writable. */ @@ -32,9 +31,7 @@ class SendNotificationResponse : BaseResponse { */ @JvmStatic @Throws(IOException::class) - fun parse(parser: XContentParser): SendNotificationResponse { - return SendNotificationResponse(NotificationEvent.parse(parser)) - } + fun parse(parser: XContentParser): SendNotificationResponse = SendNotificationResponse(NotificationEvent.parse(parser)) } /** @@ -64,7 +61,8 @@ class SendNotificationResponse : BaseResponse { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - return notificationEvent.toXContent(builder, params) - } + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder = notificationEvent.toXContent(builder, params) } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequest.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequest.kt index d28060aa..7e82dc57 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequest.kt @@ -25,7 +25,9 @@ import java.io.IOException /** * Action request for updating notification configuration. */ -class UpdateNotificationConfigRequest : ActionRequest, ToXContentObject { +class UpdateNotificationConfigRequest : + ActionRequest, + ToXContentObject { val configId: String val notificationConfig: NotificationConfig @@ -44,21 +46,30 @@ class UpdateNotificationConfigRequest : ActionRequest, ToXContentObject { */ @JvmStatic @Throws(IOException::class) - fun parse(parser: XContentParser, id: String? = null): UpdateNotificationConfigRequest { + fun parse( + parser: XContentParser, + id: String? = null, + ): UpdateNotificationConfigRequest { var configId: String? = id var notificationConfig: NotificationConfig? = null XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - CONFIG_ID_TAG -> configId = parser.text() - CONFIG_TAG -> notificationConfig = NotificationConfig.parse(parser) + CONFIG_ID_TAG -> { + configId = parser.text() + } + + CONFIG_TAG -> { + notificationConfig = NotificationConfig.parse(parser) + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing UpdateNotificationConfigRequest") @@ -74,9 +85,13 @@ class UpdateNotificationConfigRequest : ActionRequest, ToXContentObject { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(CONFIG_ID_TAG, configId) .field(CONFIG_TAG, notificationConfig) .endObject() diff --git a/src/main/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigResponse.kt b/src/main/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigResponse.kt index 42e71a13..bade704b 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigResponse.kt @@ -41,13 +41,16 @@ class UpdateNotificationConfigResponse : BaseResponse { XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - CONFIG_ID_TAG -> configId = parser.text() + CONFIG_ID_TAG -> { + configId = parser.text() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing UpdateNotificationConfigResponse") @@ -86,9 +89,13 @@ class UpdateNotificationConfigResponse : BaseResponse { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(CONFIG_ID_TAG, configId) .endObject() } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/Attachment.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/Attachment.kt index ff650a20..0a999f13 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/Attachment.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/Attachment.kt @@ -26,7 +26,7 @@ data class Attachment( val fileName: String, val fileEncoding: String, val fileData: String, - val fileContentType: String? + val fileContentType: String?, ) : BaseModel { companion object { private val log by logger(Attachment::class.java) @@ -49,16 +49,28 @@ data class Attachment( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val dataType = parser.currentName() parser.nextToken() when (dataType) { - FILE_NAME_TAG -> fileName = parser.text() - FILE_ENCODING_TAG -> fileEncoding = parser.text() - FILE_DATA_TAG -> fileData = parser.text() - FILE_CONTENT_TYPE_TAG -> fileContentType = parser.textOrNull() + FILE_NAME_TAG -> { + fileName = parser.text() + } + + FILE_ENCODING_TAG -> { + fileEncoding = parser.text() + } + + FILE_DATA_TAG -> { + fileData = parser.text() + } + + FILE_CONTENT_TYPE_TAG -> { + fileContentType = parser.textOrNull() + } + else -> { parser.skipChildren() log.info("Skipping Unknown field $dataType") @@ -72,14 +84,17 @@ data class Attachment( } } - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - return builder!!.startObject() + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder = + builder!! + .startObject() .field(FILE_NAME_TAG, fileName) .field(FILE_ENCODING_TAG, fileEncoding) .field(FILE_DATA_TAG, fileData) .fieldIfNotNull(FILE_CONTENT_TYPE_TAG, fileContentType) .endObject() - } /** * Constructor used in transport action communication. @@ -89,7 +104,7 @@ data class Attachment( fileName = input.readString(), fileEncoding = input.readString(), fileData = input.readString(), - fileContentType = input.readOptionalString() + fileContentType = input.readOptionalString(), ) /** diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/BaseModel.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/BaseModel.kt index 2271fa7f..18f1cf7c 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/BaseModel.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/BaseModel.kt @@ -10,4 +10,6 @@ import org.opensearch.core.xcontent.ToXContentObject /** * interface for representing objects. */ -interface BaseModel : Writeable, ToXContentObject +interface BaseModel : + Writeable, + ToXContentObject diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/Channel.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/Channel.kt index 68f42b27..3afbb4f9 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/Channel.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/Channel.kt @@ -28,9 +28,8 @@ data class Channel( val name: String, val description: String, val configType: ConfigType, - val isEnabled: Boolean = true + val isEnabled: Boolean = true, ) : BaseModel { - init { require(!Strings.isNullOrEmpty(name)) { "name is null or empty" } require(!Strings.isNullOrEmpty(configId)) { "config id is null or empty" } @@ -61,17 +60,32 @@ data class Channel( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - CONFIG_ID_TAG -> configId = parser.text() - NAME_TAG -> name = parser.text() - DESCRIPTION_TAG -> description = parser.text() - CONFIG_TYPE_TAG -> configType = ConfigType.fromTagOrDefault(parser.text()) - IS_ENABLED_TAG -> isEnabled = parser.booleanValue() + CONFIG_ID_TAG -> { + configId = parser.text() + } + + NAME_TAG -> { + name = parser.text() + } + + DESCRIPTION_TAG -> { + description = parser.text() + } + + CONFIG_TYPE_TAG -> { + configType = ConfigType.fromTagOrDefault(parser.text()) + } + + IS_ENABLED_TAG -> { + isEnabled = parser.booleanValue() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing Channel") @@ -86,7 +100,7 @@ data class Channel( name, description, configType, - isEnabled + isEnabled, ) } } @@ -100,7 +114,7 @@ data class Channel( name = input.readString(), description = input.readString(), configType = input.readEnum(ConfigType::class.java), - isEnabled = input.readBoolean() + isEnabled = input.readBoolean(), ) /** @@ -117,9 +131,13 @@ data class Channel( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(CONFIG_ID_TAG, configId) .field(NAME_TAG, name) .field(DESCRIPTION_TAG, description) diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelList.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelList.kt index b92b8425..af8e852f 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelList.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelList.kt @@ -15,7 +15,6 @@ import org.opensearch.core.xcontent.XContentParser * Channel search results */ class ChannelList : SearchResults { - /** * single item result constructor */ @@ -28,7 +27,7 @@ class ChannelList : SearchResults { 0, objectList.size.toLong(), TotalHits.Relation.EQUAL_TO, - objectList + objectList, ) /** @@ -38,7 +37,7 @@ class ChannelList : SearchResults { startIndex: Long, totalHits: Long, totalHitRelation: TotalHits.Relation, - objectList: List + objectList: List, ) : super(startIndex, totalHits, totalHitRelation, CHANNEL_LIST_TAG, objectList) /** @@ -59,13 +58,11 @@ class ChannelList : SearchResults { from, response, searchHitParser, - CHANNEL_LIST_TAG + CHANNEL_LIST_TAG, ) /** * {@inheritDoc} */ - override fun parseItem(parser: XContentParser): Channel { - return Channel.parse(parser) - } + override fun parseItem(parser: XContentParser): Channel = Channel.parse(parser) } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelMessage.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelMessage.kt index d733a8bc..95d55118 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelMessage.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelMessage.kt @@ -26,9 +26,8 @@ import java.io.IOException data class ChannelMessage( val textDescription: String, val htmlDescription: String?, - val attachment: Attachment? + val attachment: Attachment?, ) : BaseModel { - init { require(!Strings.isNullOrEmpty(textDescription)) { "text message part is null or empty" } } @@ -55,16 +54,25 @@ data class ChannelMessage( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - TEXT_DESCRIPTION_TAG -> textDescription = parser.text() - HTML_DESCRIPTION_TAG -> htmlDescription = parser.textOrNull() - ATTACHMENT_TAG -> attachment = Attachment.parse(parser) + TEXT_DESCRIPTION_TAG -> { + textDescription = parser.text() + } + + HTML_DESCRIPTION_TAG -> { + htmlDescription = parser.textOrNull() + } + + ATTACHMENT_TAG -> { + attachment = Attachment.parse(parser) + } + else -> { parser.skipChildren() log.info("Skipping Unknown field $fieldName") @@ -76,7 +84,7 @@ data class ChannelMessage( return ChannelMessage( textDescription, htmlDescription, - attachment + attachment, ) } } @@ -88,7 +96,7 @@ data class ChannelMessage( constructor(input: StreamInput) : this( textDescription = input.readString(), htmlDescription = input.readOptionalString(), - attachment = input.readOptionalWriteable(Attachment.reader) + attachment = input.readOptionalWriteable(Attachment.reader), ) /** @@ -103,9 +111,13 @@ data class ChannelMessage( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(TEXT_DESCRIPTION_TAG, textDescription) .fieldIfNotNull(HTML_DESCRIPTION_TAG, htmlDescription) .fieldIfNotNull(ATTACHMENT_TAG, attachment) diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/Chime.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/Chime.kt index ee1c5aa8..e92c95a8 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/Chime.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/Chime.kt @@ -21,9 +21,8 @@ import java.io.IOException * Data class representing Chime channel. */ data class Chime( - val url: String + val url: String, ) : BaseConfigData { - init { require(!Strings.isNullOrEmpty(url)) { "URL is null or empty" } validateUrl(url) @@ -54,13 +53,16 @@ data class Chime( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - URL_TAG -> url = parser.text() + URL_TAG -> { + url = parser.text() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing Chime destination") @@ -77,7 +79,7 @@ data class Chime( * @param input StreamInput stream to deserialize data from. */ constructor(input: StreamInput) : this( - url = input.readString() + url = input.readString(), ) /** @@ -90,9 +92,13 @@ data class Chime( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(URL_TAG, url) .endObject() } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/ConfigType.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/ConfigType.kt index 50f1f3bc..e3d7bd52 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/ConfigType.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/ConfigType.kt @@ -9,57 +9,39 @@ import org.opensearch.commons.utils.EnumParser /** * Enum for Notification config type */ -enum class ConfigType(val tag: String) { +enum class ConfigType( + val tag: String, +) { NONE("none") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, SLACK("slack") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, CHIME("chime") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, WEBHOOK("webhook") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, EMAIL("email") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, SNS("sns") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, SES_ACCOUNT("ses_account") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, SMTP_ACCOUNT("smtp_account") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, EMAIL_GROUP("email_group") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, MICROSOFT_TEAMS("microsoft_teams") { - override fun toString(): String { - return tag - } - }; + override fun toString(): String = tag + }, ; companion object { private val tagMap = values().associateBy { it.tag } @@ -71,8 +53,6 @@ enum class ConfigType(val tag: String) { * @param tag the tag * @return ConfigType corresponding to tag. NONE if invalid tag. */ - fun fromTagOrDefault(tag: String): ConfigType { - return tagMap[tag] ?: NONE - } + fun fromTagOrDefault(tag: String): ConfigType = tagMap[tag] ?: NONE } } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/DeliveryStatus.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/DeliveryStatus.kt index 2e25cc70..c42f15d4 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/DeliveryStatus.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/DeliveryStatus.kt @@ -22,9 +22,8 @@ import java.io.IOException */ data class DeliveryStatus( val statusCode: String, - val statusText: String + val statusText: String, ) : BaseModel { - init { require(!Strings.isNullOrEmpty(statusCode)) { "StatusCode is null or empty" } require(!Strings.isNullOrEmpty(statusText)) { "statusText is null or empty" } @@ -51,14 +50,20 @@ data class DeliveryStatus( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - STATUS_CODE_TAG -> statusCode = parser.text() - STATUS_TEXT_TAG -> statusText = parser.text() + STATUS_CODE_TAG -> { + statusCode = parser.text() + } + + STATUS_TEXT_TAG -> { + statusText = parser.text() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing deliveryStatus") @@ -69,7 +74,7 @@ data class DeliveryStatus( statusText ?: throw IllegalArgumentException("$STATUS_TEXT_TAG field absent") return DeliveryStatus( statusCode, - statusText + statusText, ) } } @@ -80,7 +85,7 @@ data class DeliveryStatus( */ constructor(input: StreamInput) : this( statusCode = input.readString(), - statusText = input.readString() + statusText = input.readString(), ) /** @@ -94,9 +99,13 @@ data class DeliveryStatus( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(STATUS_CODE_TAG, statusCode) .field(STATUS_TEXT_TAG, statusText) .endObject() diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/Email.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/Email.kt index a67619b0..cd3f883d 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/Email.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/Email.kt @@ -26,9 +26,8 @@ import java.io.IOException data class Email( val emailAccountID: String, val recipients: List, - val emailGroupIds: List + val emailGroupIds: List, ) : BaseConfigData { - init { require(!Strings.isNullOrEmpty(emailAccountID)) { "emailAccountID is null or empty" } } @@ -60,15 +59,24 @@ data class Email( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - EMAIL_ACCOUNT_ID_TAG -> emailAccountID = parser.text() - RECIPIENT_LIST_TAG -> recipients = parser.objectList { EmailRecipient.parse(it) } - EMAIL_GROUP_ID_LIST_TAG -> emailGroupIds = parser.stringList() + EMAIL_ACCOUNT_ID_TAG -> { + emailAccountID = parser.text() + } + + RECIPIENT_LIST_TAG -> { + recipients = parser.objectList { EmailRecipient.parse(it) } + } + + EMAIL_GROUP_ID_LIST_TAG -> { + emailGroupIds = parser.stringList() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing Email") @@ -87,7 +95,7 @@ data class Email( constructor(input: StreamInput) : this( emailAccountID = input.readString(), recipients = input.readList(EmailRecipient.reader), - emailGroupIds = input.readStringList() + emailGroupIds = input.readStringList(), ) /** @@ -102,9 +110,13 @@ data class Email( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(EMAIL_ACCOUNT_ID_TAG, emailAccountID) .field(RECIPIENT_LIST_TAG, recipients) .field(EMAIL_GROUP_ID_LIST_TAG, emailGroupIds) diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/EmailGroup.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/EmailGroup.kt index c5377530..aa76d380 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/EmailGroup.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/EmailGroup.kt @@ -20,9 +20,8 @@ import java.io.IOException * Data class representing Email group. */ data class EmailGroup( - val recipients: List + val recipients: List, ) : BaseConfigData { - companion object { private val log by logger(EmailGroup::class.java) @@ -48,13 +47,16 @@ data class EmailGroup( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - RECIPIENT_LIST_TAG -> recipients = parser.objectList { EmailRecipient.parse(it) } + RECIPIENT_LIST_TAG -> { + recipients = parser.objectList { EmailRecipient.parse(it) } + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing EmailGroup") @@ -71,7 +73,7 @@ data class EmailGroup( * @param input StreamInput stream to deserialize data from. */ constructor(input: StreamInput) : this( - recipients = input.readList(EmailRecipient.reader) + recipients = input.readList(EmailRecipient.reader), ) /** @@ -84,9 +86,13 @@ data class EmailGroup( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(RECIPIENT_LIST_TAG, recipients) .endObject() } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/EmailRecipient.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/EmailRecipient.kt index c601e840..e9c6dede 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/EmailRecipient.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/EmailRecipient.kt @@ -20,9 +20,8 @@ import java.io.IOException * Data class representing Email recipient. */ data class EmailRecipient( - val recipient: String + val recipient: String, ) : BaseConfigData { - init { validateEmail(recipient) } @@ -52,13 +51,16 @@ data class EmailRecipient( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - RECIPIENT_TAG -> recipient = parser.text() + RECIPIENT_TAG -> { + recipient = parser.text() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing EmailRecipient") @@ -75,7 +77,7 @@ data class EmailRecipient( * @param input StreamInput stream to deserialize data from. */ constructor(input: StreamInput) : this( - recipient = input.readString() + recipient = input.readString(), ) /** @@ -88,9 +90,13 @@ data class EmailRecipient( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(RECIPIENT_TAG, recipient) .endObject() } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/EmailRecipientStatus.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/EmailRecipientStatus.kt index d1d78165..e48f8e74 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/EmailRecipientStatus.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/EmailRecipientStatus.kt @@ -23,9 +23,8 @@ import java.io.IOException */ data class EmailRecipientStatus( val recipient: String, - val deliveryStatus: DeliveryStatus + val deliveryStatus: DeliveryStatus, ) : BaseModel { - init { validateEmail(recipient) } @@ -51,14 +50,20 @@ data class EmailRecipientStatus( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - RECIPIENT_TAG -> recipient = parser.text() - DELIVERY_STATUS_TAG -> deliveryStatus = DeliveryStatus.parse(parser) + RECIPIENT_TAG -> { + recipient = parser.text() + } + + DELIVERY_STATUS_TAG -> { + deliveryStatus = DeliveryStatus.parse(parser) + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing Email Recipient Status") @@ -77,7 +82,7 @@ data class EmailRecipientStatus( */ constructor(input: StreamInput) : this( recipient = input.readString(), - deliveryStatus = DeliveryStatus.reader.read(input) + deliveryStatus = DeliveryStatus.reader.read(input), ) /** @@ -91,9 +96,13 @@ data class EmailRecipientStatus( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(RECIPIENT_TAG, recipient) .field(DELIVERY_STATUS_TAG, deliveryStatus) .endObject() diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/EventSource.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/EventSource.kt index 91deb445..aa3fc44c 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/EventSource.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/EventSource.kt @@ -27,9 +27,8 @@ data class EventSource( val title: String, val referenceId: String, val severity: SeverityType = SeverityType.INFO, - val tags: List = listOf() + val tags: List = listOf(), ) : BaseModel { - init { require(!Strings.isNullOrEmpty(title)) { "name is null or empty" } } @@ -57,16 +56,28 @@ data class EventSource( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - TITLE_TAG -> title = parser.text() - REFERENCE_ID_TAG -> referenceId = parser.text() - SEVERITY_TAG -> severity = SeverityType.fromTagOrDefault(parser.text()) - TAGS_TAG -> tags = parser.stringList() + TITLE_TAG -> { + title = parser.text() + } + + REFERENCE_ID_TAG -> { + referenceId = parser.text() + } + + SEVERITY_TAG -> { + severity = SeverityType.fromTagOrDefault(parser.text()) + } + + TAGS_TAG -> { + tags = parser.stringList() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing EventSource") @@ -80,7 +91,7 @@ data class EventSource( title, referenceId, severity, - tags + tags, ) } } @@ -88,9 +99,13 @@ data class EventSource( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(TITLE_TAG, title) .field(REFERENCE_ID_TAG, referenceId) .field(SEVERITY_TAG, severity.tag) @@ -106,7 +121,7 @@ data class EventSource( title = input.readString(), referenceId = input.readString(), severity = input.readEnum(SeverityType::class.java), - tags = input.readStringList() + tags = input.readStringList(), ) /** diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/EventStatus.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/EventStatus.kt index 8d1b5a7c..696fbc2a 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/EventStatus.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/EventStatus.kt @@ -31,20 +31,40 @@ data class EventStatus( val configName: String, val configType: ConfigType, val emailRecipientStatus: List = listOf(), - val deliveryStatus: DeliveryStatus? = null + val deliveryStatus: DeliveryStatus? = null, ) : BaseModel { - init { require(!Strings.isNullOrEmpty(configId)) { "config id is null or empty" } require(!Strings.isNullOrEmpty(configName)) { "config name is null or empty" } when (configType) { - ConfigType.CHIME -> requireNotNull(deliveryStatus) - ConfigType.WEBHOOK -> requireNotNull(deliveryStatus) - ConfigType.SLACK -> requireNotNull(deliveryStatus) - ConfigType.EMAIL -> require(emailRecipientStatus.isNotEmpty()) - ConfigType.SNS -> requireNotNull(deliveryStatus) - ConfigType.MICROSOFT_TEAMS -> requireNotNull(deliveryStatus) - ConfigType.NONE -> log.info("Some config field not recognized") + ConfigType.CHIME -> { + requireNotNull(deliveryStatus) + } + + ConfigType.WEBHOOK -> { + requireNotNull(deliveryStatus) + } + + ConfigType.SLACK -> { + requireNotNull(deliveryStatus) + } + + ConfigType.EMAIL -> { + require(emailRecipientStatus.isNotEmpty()) + } + + ConfigType.SNS -> { + requireNotNull(deliveryStatus) + } + + ConfigType.MICROSOFT_TEAMS -> { + requireNotNull(deliveryStatus) + } + + ConfigType.NONE -> { + log.info("Some config field not recognized") + } + else -> { log.info("non-allowed config type for Status") } @@ -75,17 +95,32 @@ data class EventStatus( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - CONFIG_NAME_TAG -> configName = parser.text() - CONFIG_ID_TAG -> configId = parser.text() - CONFIG_TYPE_TAG -> configType = ConfigType.fromTagOrDefault(parser.text()) - EMAIL_RECIPIENT_STATUS_TAG -> emailRecipientStatus = parser.objectList { EmailRecipientStatus.parse(it) } - DELIVERY_STATUS_TAG -> deliveryStatus = DeliveryStatus.parse(parser) + CONFIG_NAME_TAG -> { + configName = parser.text() + } + + CONFIG_ID_TAG -> { + configId = parser.text() + } + + CONFIG_TYPE_TAG -> { + configType = ConfigType.fromTagOrDefault(parser.text()) + } + + EMAIL_RECIPIENT_STATUS_TAG -> { + emailRecipientStatus = parser.objectList { EmailRecipientStatus.parse(it) } + } + + DELIVERY_STATUS_TAG -> { + deliveryStatus = DeliveryStatus.parse(parser) + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing EventStatus") @@ -101,7 +136,7 @@ data class EventStatus( configName, configType, emailRecipientStatus, - deliveryStatus + deliveryStatus, ) } } @@ -115,7 +150,7 @@ data class EventStatus( configName = input.readString(), configType = input.readEnum(ConfigType::class.java), emailRecipientStatus = input.readList(EmailRecipientStatus.reader), - deliveryStatus = input.readOptionalWriteable(DeliveryStatus.reader) + deliveryStatus = input.readOptionalWriteable(DeliveryStatus.reader), ) /** @@ -132,9 +167,13 @@ data class EventStatus( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(CONFIG_ID_TAG, configId) .field(CONFIG_TYPE_TAG, configType.tag) .field(CONFIG_NAME_TAG, configName) diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/HttpMethodType.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/HttpMethodType.kt index 8485e4fd..e2743bf9 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/HttpMethodType.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/HttpMethodType.kt @@ -2,22 +2,18 @@ package org.opensearch.commons.notifications.model import org.opensearch.commons.utils.EnumParser -enum class HttpMethodType(val tag: String) { +enum class HttpMethodType( + val tag: String, +) { POST("POST") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, PUT("PUT") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, PATCH("PATCH") { - override fun toString(): String { - return tag - } - }; + override fun toString(): String = tag + }, ; companion object { private val tagMap = values().associateBy { it.tag } @@ -29,8 +25,6 @@ enum class HttpMethodType(val tag: String) { * @param tag the tag * @return MethodType corresponding to tag. POST if invalid tag. */ - fun fromTagOrDefault(tag: String): HttpMethodType { - return tagMap[tag] ?: POST - } + fun fromTagOrDefault(tag: String): HttpMethodType = tagMap[tag] ?: POST } } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/MethodType.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/MethodType.kt index 99f5694a..cefe747f 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/MethodType.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/MethodType.kt @@ -2,22 +2,18 @@ package org.opensearch.commons.notifications.model import org.opensearch.commons.utils.EnumParser -enum class MethodType(val tag: String) { +enum class MethodType( + val tag: String, +) { NONE("none") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, SSL("ssl") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, START_TLS("start_tls") { - override fun toString(): String { - return tag - } - }; + override fun toString(): String = tag + }, ; companion object { private val tagMap = values().associateBy { it.tag } @@ -29,8 +25,6 @@ enum class MethodType(val tag: String) { * @param tag the tag * @return MethodType corresponding to tag. NONE if invalid tag. */ - fun fromTagOrDefault(tag: String): MethodType { - return tagMap[tag] ?: NONE - } + fun fromTagOrDefault(tag: String): MethodType = tagMap[tag] ?: NONE } } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeams.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeams.kt index 48e32f15..c97ca851 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeams.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeams.kt @@ -21,9 +21,8 @@ import java.io.IOException * Data class representing MicrosoftTeams channel. */ data class MicrosoftTeams( - val url: String + val url: String, ) : BaseConfigData { - init { require(!Strings.isNullOrEmpty(url)) { "URL is null or empty" } validateUrl(url) @@ -54,13 +53,16 @@ data class MicrosoftTeams( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - URL_TAG -> url = parser.text() + URL_TAG -> { + url = parser.text() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing MicrosoftTeams destination") @@ -77,7 +79,7 @@ data class MicrosoftTeams( * @param input StreamInput stream to deserialize data from. */ constructor(input: StreamInput) : this( - url = input.readString() + url = input.readString(), ) /** @@ -90,9 +92,13 @@ data class MicrosoftTeams( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(URL_TAG, url) .endObject() } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfig.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfig.kt index 5b0b8a90..b9184ce9 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfig.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfig.kt @@ -31,9 +31,8 @@ data class NotificationConfig( val description: String, val configType: ConfigType, val configData: BaseConfigData?, - val isEnabled: Boolean = true + val isEnabled: Boolean = true, ) : BaseModel { - init { require(!Strings.isNullOrEmpty(name)) { "name is null or empty" } if (!validateConfigData(configType, configData)) { @@ -68,16 +67,28 @@ data class NotificationConfig( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - NAME_TAG -> name = parser.text() - DESCRIPTION_TAG -> description = parser.text() - CONFIG_TYPE_TAG -> configType = ConfigType.fromTagOrDefault(parser.text()) - IS_ENABLED_TAG -> isEnabled = parser.booleanValue() + NAME_TAG -> { + name = parser.text() + } + + DESCRIPTION_TAG -> { + description = parser.text() + } + + CONFIG_TYPE_TAG -> { + configType = ConfigType.fromTagOrDefault(parser.text()) + } + + IS_ENABLED_TAG -> { + isEnabled = parser.booleanValue() + } + else -> { val configTypeForTag = ConfigType.fromTagOrDefault(fieldName) if (configTypeForTag != ConfigType.NONE && configData == null) { @@ -96,7 +107,7 @@ data class NotificationConfig( description, configType, configData, - isEnabled + isEnabled, ) } } @@ -104,9 +115,13 @@ data class NotificationConfig( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(NAME_TAG, name) .field(DESCRIPTION_TAG, description) .field(CONFIG_TYPE_TAG, configType.tag) @@ -124,7 +139,7 @@ data class NotificationConfig( description = input.readString(), configType = input.readEnum(ConfigType::class.java), isEnabled = input.readBoolean(), - configData = input.readOptionalWriteable(getReaderForConfigType(input.readEnum(ConfigType::class.java))) + configData = input.readOptionalWriteable(getReaderForConfigType(input.readEnum(ConfigType::class.java))), ) /** diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfigInfo.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfigInfo.kt index 34b6285b..b7e229d6 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfigInfo.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfigInfo.kt @@ -28,9 +28,8 @@ data class NotificationConfigInfo( val configId: String, val lastUpdatedTime: Instant, val createdTime: Instant, - val notificationConfig: NotificationConfig + val notificationConfig: NotificationConfig, ) : BaseModel { - init { require(!Strings.isNullOrEmpty(configId)) { "config id is null or empty" } } @@ -58,16 +57,28 @@ data class NotificationConfigInfo( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - CONFIG_ID_TAG -> configId = parser.text() - UPDATED_TIME_TAG -> lastUpdatedTime = Instant.ofEpochMilli(parser.longValue()) - CREATED_TIME_TAG -> createdTime = Instant.ofEpochMilli(parser.longValue()) - CONFIG_TAG -> notificationConfig = NotificationConfig.parse(parser) + CONFIG_ID_TAG -> { + configId = parser.text() + } + + UPDATED_TIME_TAG -> { + lastUpdatedTime = Instant.ofEpochMilli(parser.longValue()) + } + + CREATED_TIME_TAG -> { + createdTime = Instant.ofEpochMilli(parser.longValue()) + } + + CONFIG_TAG -> { + notificationConfig = NotificationConfig.parse(parser) + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing configuration") @@ -82,7 +93,7 @@ data class NotificationConfigInfo( configId, lastUpdatedTime, createdTime, - notificationConfig + notificationConfig, ) } } @@ -95,7 +106,7 @@ data class NotificationConfigInfo( configId = input.readString(), lastUpdatedTime = input.readInstant(), createdTime = input.readInstant(), - notificationConfig = NotificationConfig.reader.read(input) + notificationConfig = NotificationConfig.reader.read(input), ) /** @@ -111,9 +122,13 @@ data class NotificationConfigInfo( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(CONFIG_ID_TAG, configId) .field(UPDATED_TIME_TAG, lastUpdatedTime.toEpochMilli()) .field(CREATED_TIME_TAG, createdTime.toEpochMilli()) diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfigSearchResult.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfigSearchResult.kt index 7a44836e..b38805b4 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfigSearchResult.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationConfigSearchResult.kt @@ -15,7 +15,6 @@ import org.opensearch.core.xcontent.XContentParser * NotificationConfig search results */ class NotificationConfigSearchResult : SearchResults { - /** * single item result constructor */ @@ -28,7 +27,7 @@ class NotificationConfigSearchResult : SearchResults { 0, objectList.size.toLong(), TotalHits.Relation.EQUAL_TO, - objectList + objectList, ) /** @@ -38,7 +37,7 @@ class NotificationConfigSearchResult : SearchResults { startIndex: Long, totalHits: Long, totalHitRelation: TotalHits.Relation, - objectList: List + objectList: List, ) : super(startIndex, totalHits, totalHitRelation, CONFIG_LIST_TAG, objectList) /** @@ -59,13 +58,11 @@ class NotificationConfigSearchResult : SearchResults { from, response, searchHitParser, - CONFIG_LIST_TAG + CONFIG_LIST_TAG, ) /** * {@inheritDoc} */ - override fun parseItem(parser: XContentParser): NotificationConfigInfo { - return NotificationConfigInfo.parse(parser) - } + override fun parseItem(parser: XContentParser): NotificationConfigInfo = NotificationConfigInfo.parse(parser) } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationEvent.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationEvent.kt index 2b3c8f40..774257ae 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationEvent.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/NotificationEvent.kt @@ -25,9 +25,8 @@ import java.io.IOException */ data class NotificationEvent( val eventSource: EventSource, - val statusList: List = listOf() + val statusList: List = listOf(), ) : BaseModel { - init { require(statusList.isNotEmpty()) { "statusList is null or empty" } } @@ -53,14 +52,20 @@ data class NotificationEvent( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - EVENT_SOURCE_TAG -> eventSource = EventSource.parse(parser) - STATUS_LIST_TAG -> statusList = parser.objectList { EventStatus.parse(it) } + EVENT_SOURCE_TAG -> { + eventSource = EventSource.parse(parser) + } + + STATUS_LIST_TAG -> { + statusList = parser.objectList { EventStatus.parse(it) } + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing notification event") @@ -73,7 +78,7 @@ data class NotificationEvent( } return NotificationEvent( eventSource, - statusList + statusList, ) } } @@ -84,7 +89,7 @@ data class NotificationEvent( */ constructor(input: StreamInput) : this( eventSource = EventSource.reader.read(input), - statusList = input.readList(EventStatus.reader) + statusList = input.readList(EventStatus.reader), ) /** @@ -98,21 +103,24 @@ data class NotificationEvent( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(EVENT_SOURCE_TAG, eventSource) .field(STATUS_LIST_TAG, statusList) .endObject() } // Overriding toString so consuming plugins can log/output this from the sendNotification response if needed - override fun toString(): String { - return try { + override fun toString(): String = + try { XContentHelper.toXContent(this, XContentType.JSON, EMPTY_PARAMS, true).utf8ToString() } catch (e: IOException) { log.debug("Failed to convert NotificationEvent to string", e) super.toString() + " threw " + e.toString() } - } } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/SearchResults.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/SearchResults.kt index f6b3a295..564ae122 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/SearchResults.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/SearchResults.kt @@ -35,26 +35,25 @@ abstract class SearchResults : BaseModel { companion object { private val log by logger(SearchResults::class.java) - private fun convertRelation(totalHitRelation: Relation): String { - return if (totalHitRelation == EQUAL_TO) { + + private fun convertRelation(totalHitRelation: Relation): String = + if (totalHitRelation == EQUAL_TO) { "eq" } else { "gte" } - } - private fun convertRelation(totalHitRelation: String): Relation { - return if (totalHitRelation == "eq") { + private fun convertRelation(totalHitRelation: String): Relation = + if (totalHitRelation == "eq") { EQUAL_TO } else { GREATER_THAN_OR_EQUAL_TO } - } } constructor( objectListFieldName: String, - objectItem: ItemClass + objectItem: ItemClass, ) { this.startIndex = 0 this.totalHits = 1 @@ -68,7 +67,7 @@ abstract class SearchResults : BaseModel { totalHits: Long, totalHitRelation: Relation, objectListFieldName: String, - objectList: List + objectList: List, ) { this.startIndex = startIndex this.totalHits = totalHits @@ -81,7 +80,7 @@ abstract class SearchResults : BaseModel { from: Long, response: SearchResponse, searchHitParser: SearchHitParser, - objectListFieldName: String + objectListFieldName: String, ) { val mutableList: MutableList = mutableListOf() response.hits.forEach { @@ -118,10 +117,22 @@ abstract class SearchResults : BaseModel { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - START_INDEX_TAG -> startIndex = parser.longValue() - TOTAL_HITS_TAG -> totalHits = parser.longValue() - TOTAL_HIT_RELATION_TAG -> totalHitRelation = convertRelation(parser.text()) - objectListFieldName -> objectList = parseItemList(parser) + START_INDEX_TAG -> { + startIndex = parser.longValue() + } + + TOTAL_HITS_TAG -> { + totalHits = parser.longValue() + } + + TOTAL_HIT_RELATION_TAG -> { + totalHitRelation = convertRelation(parser.text()) + } + + objectListFieldName -> { + objectList = parseItemList(parser) + } + else -> { parser.skipChildren() log.info("Skipping Unknown field $fieldName") @@ -170,7 +181,7 @@ abstract class SearchResults : BaseModel { totalHits = input.readLong(), totalHitRelation = input.readEnum(Relation::class.java), objectListFieldName = input.readString(), - objectList = input.readList(reader) + objectList = input.readList(reader), ) /** @@ -187,8 +198,12 @@ abstract class SearchResults : BaseModel { /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: Params?): XContentBuilder { - builder!!.startObject() + override fun toXContent( + builder: XContentBuilder?, + params: Params?, + ): XContentBuilder { + builder!! + .startObject() .field(START_INDEX_TAG, startIndex) .field(TOTAL_HITS_TAG, totalHits) .field(TOTAL_HIT_RELATION_TAG, convertRelation(totalHitRelation)) diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/SesAccount.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/SesAccount.kt index 13370ed9..5fe001ca 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/SesAccount.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/SesAccount.kt @@ -28,9 +28,8 @@ import java.io.IOException data class SesAccount( val awsRegion: String, val roleArn: String?, - val fromAddress: String + val fromAddress: String, ) : BaseConfigData { - init { require(!Strings.isNullOrEmpty(awsRegion)) { "awsRegion is null or empty" } validateEmail(fromAddress) @@ -62,15 +61,24 @@ data class SesAccount( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - REGION_TAG -> awsRegion = parser.text() - ROLE_ARN_TAG -> roleArn = parser.textOrNull() - FROM_ADDRESS_TAG -> fromAddress = parser.text() + REGION_TAG -> { + awsRegion = parser.text() + } + + ROLE_ARN_TAG -> { + roleArn = parser.textOrNull() + } + + FROM_ADDRESS_TAG -> { + fromAddress = parser.text() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing SesAccount") @@ -82,7 +90,7 @@ data class SesAccount( return SesAccount( awsRegion, roleArn, - fromAddress + fromAddress, ) } } @@ -90,13 +98,16 @@ data class SesAccount( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - return builder!!.startObject() + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder = + builder!! + .startObject() .field(REGION_TAG, awsRegion) .fieldIfNotNull(ROLE_ARN_TAG, roleArn) .field(FROM_ADDRESS_TAG, fromAddress) .endObject() - } /** * Constructor used in transport action communication. @@ -105,7 +116,7 @@ data class SesAccount( constructor(input: StreamInput) : this( awsRegion = input.readString(), roleArn = input.readOptionalString(), - fromAddress = input.readString() + fromAddress = input.readString(), ) /** diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/SeverityType.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/SeverityType.kt index 0fa8a427..257e35fd 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/SeverityType.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/SeverityType.kt @@ -10,27 +10,21 @@ import org.opensearch.commons.utils.EnumParser /** * Notification severity type */ -enum class SeverityType(val tag: String) { +enum class SeverityType( + val tag: String, +) { NONE("none") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, HIGH("high") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, INFO("info") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, CRITICAL("critical") { - override fun toString(): String { - return tag - } - }; + override fun toString(): String = tag + }, ; companion object { private val tagMap = values().associateBy { it.tag } @@ -42,8 +36,6 @@ enum class SeverityType(val tag: String) { * @param tag the tag * @return SeverityType corresponding to tag. NONE if invalid tag. */ - fun fromTagOrDefault(tag: String): SeverityType { - return tagMap[tag] ?: NONE - } + fun fromTagOrDefault(tag: String): SeverityType = tagMap[tag] ?: NONE } } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/Slack.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/Slack.kt index b4433b95..050f7464 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/Slack.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/Slack.kt @@ -21,9 +21,8 @@ import java.io.IOException * Data class representing Slack channel. */ data class Slack( - val url: String + val url: String, ) : BaseConfigData { - init { require(!Strings.isNullOrEmpty(url)) { "URL is null or empty" } validateUrl(url) @@ -54,13 +53,16 @@ data class Slack( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - URL_TAG -> url = parser.text() + URL_TAG -> { + url = parser.text() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing Slack destination") @@ -77,7 +79,7 @@ data class Slack( * @param input StreamInput stream to deserialize data from. */ constructor(input: StreamInput) : this( - url = input.readString() + url = input.readString(), ) /** @@ -90,9 +92,13 @@ data class Slack( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(URL_TAG, url) .endObject() } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/SmtpAccount.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/SmtpAccount.kt index ca3a762a..a21b8119 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/SmtpAccount.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/SmtpAccount.kt @@ -27,9 +27,8 @@ data class SmtpAccount( val host: String, val port: Int, val method: MethodType, - val fromAddress: String + val fromAddress: String, ) : BaseConfigData { - init { require(!Strings.isNullOrEmpty(host)) { "host is null or empty" } require(port > 0) { "port should be positive value" } @@ -60,16 +59,28 @@ data class SmtpAccount( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - HOST_TAG -> host = parser.text() - PORT_TAG -> port = parser.intValue() - METHOD_TAG -> method = MethodType.fromTagOrDefault(parser.text()) - FROM_ADDRESS_TAG -> fromAddress = parser.text() + HOST_TAG -> { + host = parser.text() + } + + PORT_TAG -> { + port = parser.intValue() + } + + METHOD_TAG -> { + method = MethodType.fromTagOrDefault(parser.text()) + } + + FROM_ADDRESS_TAG -> { + fromAddress = parser.text() + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing SmtpAccount") @@ -84,7 +95,7 @@ data class SmtpAccount( host, port, method, - fromAddress + fromAddress, ) } } @@ -92,14 +103,17 @@ data class SmtpAccount( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { - return builder!!.startObject() + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder = + builder!! + .startObject() .field(HOST_TAG, host) .field(PORT_TAG, port) .field(METHOD_TAG, method.tag) .field(FROM_ADDRESS_TAG, fromAddress) .endObject() - } /** * Constructor used in transport action communication. @@ -109,7 +123,7 @@ data class SmtpAccount( host = input.readString(), port = input.readInt(), method = input.readEnum(MethodType::class.java), - fromAddress = input.readString() + fromAddress = input.readString(), ) /** diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/Sns.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/Sns.kt index d0809f9f..3ba91f7e 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/Sns.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/Sns.kt @@ -23,8 +23,10 @@ import java.util.regex.Pattern /** * SNS notification data model */ -data class Sns(val topicArn: String, val roleArn: String?) : BaseConfigData { - +data class Sns( + val topicArn: String, + val roleArn: String?, +) : BaseConfigData { init { require(SNS_ARN_REGEX.matcher(topicArn).find()) { "Invalid AWS SNS topic ARN: $topicArn" } if (roleArn != null) { @@ -32,12 +34,15 @@ data class Sns(val topicArn: String, val roleArn: String?) : BaseConfigData { } } - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - return builder.startObject() + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder = + builder + .startObject() .field(TOPIC_ARN_TAG, topicArn) .fieldIfNotNull(ROLE_ARN_TAG, roleArn) .endObject() - } /** * Constructor used in transport action communication. @@ -45,7 +50,7 @@ data class Sns(val topicArn: String, val roleArn: String?) : BaseConfigData { */ constructor(input: StreamInput) : this( topicArn = input.readString(), - roleArn = input.readOptionalString() + roleArn = input.readOptionalString(), ) @Throws(IOException::class) @@ -81,8 +86,14 @@ data class Sns(val topicArn: String, val roleArn: String?) : BaseConfigData { val fieldName = xcp.currentName() xcp.nextToken() when (fieldName) { - TOPIC_ARN_TAG -> topicArn = xcp.textOrNull() - ROLE_ARN_TAG -> roleArn = xcp.textOrNull() + TOPIC_ARN_TAG -> { + topicArn = xcp.textOrNull() + } + + ROLE_ARN_TAG -> { + roleArn = xcp.textOrNull() + } + else -> { xcp.skipChildren() log.info("Unexpected field: $fieldName, while parsing SNS destination") diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/Webhook.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/Webhook.kt index e48f29f4..da6d04e7 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/Webhook.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/Webhook.kt @@ -27,9 +27,8 @@ import java.io.IOException data class Webhook( val url: String, val headerParams: Map = mapOf(), - val method: HttpMethodType = HttpMethodType.POST + val method: HttpMethodType = HttpMethodType.POST, ) : BaseConfigData { - init { require(!Strings.isNullOrEmpty(url)) { "URL is null or empty" } validateUrl(url) @@ -62,15 +61,24 @@ data class Webhook( XContentParserUtils.ensureExpectedToken( XContentParser.Token.START_OBJECT, parser.currentToken(), - parser + parser, ) while (parser.nextToken() != XContentParser.Token.END_OBJECT) { val fieldName = parser.currentName() parser.nextToken() when (fieldName) { - URL_TAG -> url = parser.text() - HEADER_PARAMS_TAG -> headerParams = parser.mapStrings() - METHOD_TAG -> method = HttpMethodType.fromTagOrDefault(parser.text()) + URL_TAG -> { + url = parser.text() + } + + HEADER_PARAMS_TAG -> { + headerParams = parser.mapStrings() + } + + METHOD_TAG -> { + method = HttpMethodType.fromTagOrDefault(parser.text()) + } + else -> { parser.skipChildren() log.info("Unexpected field: $fieldName, while parsing Webhook destination") @@ -85,9 +93,13 @@ data class Webhook( /** * {@inheritDoc} */ - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { builder!! - return builder.startObject() + return builder + .startObject() .field(URL_TAG, url) .field(HEADER_PARAMS_TAG, headerParams) .field(METHOD_TAG, method.tag) @@ -101,7 +113,7 @@ data class Webhook( constructor(input: StreamInput) : this( url = input.readString(), headerParams = input.readMap(STRING_READER, STRING_READER), - method = input.readEnum(HttpMethodType::class.java) + method = input.readEnum(HttpMethodType::class.java), ) /** diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/config/ConfigDataProperties.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/config/ConfigDataProperties.kt index 28063e30..8e123841 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/config/ConfigDataProperties.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/config/ConfigDataProperties.kt @@ -26,36 +26,39 @@ internal object ConfigDataProperties { */ private data class ConfigProperty( val configDataReader: Reader, - val configDataParser: XParser + val configDataParser: XParser, ) - private val CONFIG_PROPERTIES_MAP = mapOf( - Pair(ConfigType.SLACK, ConfigProperty(Slack.reader, Slack.xParser)), - Pair(ConfigType.CHIME, ConfigProperty(Chime.reader, Chime.xParser)), - Pair(ConfigType.WEBHOOK, ConfigProperty(Webhook.reader, Webhook.xParser)), - Pair(ConfigType.EMAIL, ConfigProperty(Email.reader, Email.xParser)), - Pair(ConfigType.SNS, ConfigProperty(Sns.reader, Sns.xParser)), - Pair(ConfigType.SES_ACCOUNT, ConfigProperty(SesAccount.reader, SesAccount.xParser)), - Pair(ConfigType.EMAIL_GROUP, ConfigProperty(EmailGroup.reader, EmailGroup.xParser)), - Pair(ConfigType.SMTP_ACCOUNT, ConfigProperty(SmtpAccount.reader, SmtpAccount.xParser)), - Pair(ConfigType.MICROSOFT_TEAMS, ConfigProperty(MicrosoftTeams.reader, MicrosoftTeams.xParser)) - ) + private val CONFIG_PROPERTIES_MAP = + mapOf( + Pair(ConfigType.SLACK, ConfigProperty(Slack.reader, Slack.xParser)), + Pair(ConfigType.CHIME, ConfigProperty(Chime.reader, Chime.xParser)), + Pair(ConfigType.WEBHOOK, ConfigProperty(Webhook.reader, Webhook.xParser)), + Pair(ConfigType.EMAIL, ConfigProperty(Email.reader, Email.xParser)), + Pair(ConfigType.SNS, ConfigProperty(Sns.reader, Sns.xParser)), + Pair(ConfigType.SES_ACCOUNT, ConfigProperty(SesAccount.reader, SesAccount.xParser)), + Pair(ConfigType.EMAIL_GROUP, ConfigProperty(EmailGroup.reader, EmailGroup.xParser)), + Pair(ConfigType.SMTP_ACCOUNT, ConfigProperty(SmtpAccount.reader, SmtpAccount.xParser)), + Pair(ConfigType.MICROSOFT_TEAMS, ConfigProperty(MicrosoftTeams.reader, MicrosoftTeams.xParser)), + ) /** * Get Reader for provided config type * @param @ConfigType * @return Reader */ - fun getReaderForConfigType(configType: ConfigType): Reader { - return CONFIG_PROPERTIES_MAP[configType]?.configDataReader + fun getReaderForConfigType(configType: ConfigType): Reader = + CONFIG_PROPERTIES_MAP[configType]?.configDataReader ?: throw IllegalArgumentException("Transport action used with unknown ConfigType:$configType") - } /** * Validate config data is of ConfigType */ - fun validateConfigData(configType: ConfigType, configData: BaseConfigData?): Boolean { - return when (configType) { + fun validateConfigData( + configType: ConfigType, + configData: BaseConfigData?, + ): Boolean = + when (configType) { ConfigType.SLACK -> configData is Slack ConfigType.WEBHOOK -> configData is Webhook ConfigType.EMAIL -> configData is Email @@ -67,7 +70,6 @@ internal object ConfigDataProperties { ConfigType.MICROSOFT_TEAMS -> configData is MicrosoftTeams ConfigType.NONE -> true } - } /** * Creates config data from parser for given configType @@ -76,7 +78,8 @@ internal object ConfigDataProperties { * @return created BaseConfigData on success. null if configType is not recognized * */ - fun createConfigData(configType: ConfigType, parser: XContentParser): BaseConfigData? { - return CONFIG_PROPERTIES_MAP[configType]?.configDataParser?.parse(parser) - } + fun createConfigData( + configType: ConfigType, + parser: XContentParser, + ): BaseConfigData? = CONFIG_PROPERTIES_MAP[configType]?.configDataParser?.parse(parser) } diff --git a/src/main/kotlin/org/opensearch/commons/replication/ReplicationPluginInterface.kt b/src/main/kotlin/org/opensearch/commons/replication/ReplicationPluginInterface.kt index b646f192..4f0766ff 100644 --- a/src/main/kotlin/org/opensearch/commons/replication/ReplicationPluginInterface.kt +++ b/src/main/kotlin/org/opensearch/commons/replication/ReplicationPluginInterface.kt @@ -1,68 +1,66 @@ -/* - * Copyright OpenSearch Contributors - * SPDX-License-Identifier: Apache-2.0 - */ -package org.opensearch.commons.replication - -import org.opensearch.action.support.clustermanager.AcknowledgedResponse -import org.opensearch.commons.replication.action.ReplicationActions.INTERNAL_STOP_REPLICATION_ACTION_TYPE -import org.opensearch.commons.replication.action.StopIndexReplicationRequest -import org.opensearch.commons.utils.recreateObject -import org.opensearch.core.action.ActionListener -import org.opensearch.core.action.ActionResponse -import org.opensearch.core.common.io.stream.Writeable -import org.opensearch.transport.client.Client -import org.opensearch.transport.client.node.NodeClient - -/** - * Transport action plugin interfaces for the cross-cluster-replication plugin. - */ -object ReplicationPluginInterface { - - /** - * Stop replication. - * @param client Node client for making transport action - * @param request The request object - * @param listener The listener for getting response - */ - - fun stopReplication( - client: Client, - request: StopIndexReplicationRequest, - listener: ActionListener - ) { - val nodeClient = client as NodeClient - return nodeClient.execute( - INTERNAL_STOP_REPLICATION_ACTION_TYPE, - request, - wrapActionListener(listener) { response -> - recreateObject(response) { - AcknowledgedResponse(it) - } - } - ) - } - - /** - * Wrap action listener on concrete response class by a new created one on ActionResponse. - * This is required because the response may be loaded by different classloader across plugins. - * The onResponse(ActionResponse) avoids type cast exception and give a chance to recreate - * the response object. - */ - @Suppress("UNCHECKED_CAST") - private fun wrapActionListener( - listener: ActionListener, - recreate: (Writeable) -> Response - ): ActionListener { - return object : ActionListener { - override fun onResponse(response: ActionResponse) { - val recreated = response as? Response ?: recreate(response) - listener.onResponse(recreated) - } - - override fun onFailure(exception: java.lang.Exception) { - listener.onFailure(exception) - } - } as ActionListener - } -} +/* + * Copyright OpenSearch Contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package org.opensearch.commons.replication + +import org.opensearch.action.support.clustermanager.AcknowledgedResponse +import org.opensearch.commons.replication.action.ReplicationActions.INTERNAL_STOP_REPLICATION_ACTION_TYPE +import org.opensearch.commons.replication.action.StopIndexReplicationRequest +import org.opensearch.commons.utils.recreateObject +import org.opensearch.core.action.ActionListener +import org.opensearch.core.action.ActionResponse +import org.opensearch.core.common.io.stream.Writeable +import org.opensearch.transport.client.Client +import org.opensearch.transport.client.node.NodeClient + +/** + * Transport action plugin interfaces for the cross-cluster-replication plugin. + */ +object ReplicationPluginInterface { + /** + * Stop replication. + * @param client Node client for making transport action + * @param request The request object + * @param listener The listener for getting response + */ + + fun stopReplication( + client: Client, + request: StopIndexReplicationRequest, + listener: ActionListener, + ) { + val nodeClient = client as NodeClient + return nodeClient.execute( + INTERNAL_STOP_REPLICATION_ACTION_TYPE, + request, + wrapActionListener(listener) { response -> + recreateObject(response) { + AcknowledgedResponse(it) + } + }, + ) + } + + /** + * Wrap action listener on concrete response class by a new created one on ActionResponse. + * This is required because the response may be loaded by different classloader across plugins. + * The onResponse(ActionResponse) avoids type cast exception and give a chance to recreate + * the response object. + */ + @Suppress("UNCHECKED_CAST") + private fun wrapActionListener( + listener: ActionListener, + recreate: (Writeable) -> Response, + ): ActionListener = + object : ActionListener { + override fun onResponse(response: ActionResponse) { + val recreated = response as? Response ?: recreate(response) + listener.onResponse(recreated) + } + + override fun onFailure(exception: java.lang.Exception) { + listener.onFailure(exception) + } + } as ActionListener +} diff --git a/src/main/kotlin/org/opensearch/commons/replication/action/ReplicationActions.kt b/src/main/kotlin/org/opensearch/commons/replication/action/ReplicationActions.kt index 711fb217..0020a0c2 100644 --- a/src/main/kotlin/org/opensearch/commons/replication/action/ReplicationActions.kt +++ b/src/main/kotlin/org/opensearch/commons/replication/action/ReplicationActions.kt @@ -1,30 +1,29 @@ -/* - * Copyright OpenSearch Contributors - * SPDX-License-Identifier: Apache-2.0 - */ -package org.opensearch.commons.replication.action - -import org.opensearch.action.ActionType -import org.opensearch.action.support.clustermanager.AcknowledgedResponse - -/** - * Information related to the transport stop replication action for the Replication plugin - */ -object ReplicationActions { - - /** - * Action names for stopping replication - * STOP_REPLICATION_ACTION_NAME: action used for _replication/_stop REST API - * INTERNAL_STOP_REPLICATION_ACTION_NAME: Internal only - Used by Index Management plugin to invoke stop replication - */ - const val STOP_REPLICATION_ACTION_NAME = "indices:admin/plugins/replication/index/stop" - const val INTERNAL_STOP_REPLICATION_ACTION_NAME = "indices:internal/plugins/replication/index/stop" - - /** - * Stop replication transport action types. - */ - val STOP_REPLICATION_ACTION_TYPE = - ActionType(STOP_REPLICATION_ACTION_NAME, ::AcknowledgedResponse) - val INTERNAL_STOP_REPLICATION_ACTION_TYPE = - ActionType(INTERNAL_STOP_REPLICATION_ACTION_NAME, ::AcknowledgedResponse) -} +/* + * Copyright OpenSearch Contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package org.opensearch.commons.replication.action + +import org.opensearch.action.ActionType +import org.opensearch.action.support.clustermanager.AcknowledgedResponse + +/** + * Information related to the transport stop replication action for the Replication plugin + */ +object ReplicationActions { + /** + * Action names for stopping replication + * STOP_REPLICATION_ACTION_NAME: action used for _replication/_stop REST API + * INTERNAL_STOP_REPLICATION_ACTION_NAME: Internal only - Used by Index Management plugin to invoke stop replication + */ + const val STOP_REPLICATION_ACTION_NAME = "indices:admin/plugins/replication/index/stop" + const val INTERNAL_STOP_REPLICATION_ACTION_NAME = "indices:internal/plugins/replication/index/stop" + + /** + * Stop replication transport action types. + */ + val STOP_REPLICATION_ACTION_TYPE = + ActionType(STOP_REPLICATION_ACTION_NAME, ::AcknowledgedResponse) + val INTERNAL_STOP_REPLICATION_ACTION_TYPE = + ActionType(INTERNAL_STOP_REPLICATION_ACTION_NAME, ::AcknowledgedResponse) +} diff --git a/src/main/kotlin/org/opensearch/commons/replication/action/StopIndexReplicationRequest.kt b/src/main/kotlin/org/opensearch/commons/replication/action/StopIndexReplicationRequest.kt index e4940ea3..f81827c8 100644 --- a/src/main/kotlin/org/opensearch/commons/replication/action/StopIndexReplicationRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/replication/action/StopIndexReplicationRequest.kt @@ -1,70 +1,73 @@ -/* - * Copyright OpenSearch Contributors - * SPDX-License-Identifier: Apache-2.0 - */ -package org.opensearch.commons.replication.action - -import org.opensearch.action.ActionRequestValidationException -import org.opensearch.action.IndicesRequest -import org.opensearch.action.support.IndicesOptions -import org.opensearch.action.support.clustermanager.AcknowledgedRequest -import org.opensearch.core.common.io.stream.StreamInput -import org.opensearch.core.common.io.stream.StreamOutput -import org.opensearch.core.xcontent.ObjectParser -import org.opensearch.core.xcontent.ToXContent -import org.opensearch.core.xcontent.ToXContentObject -import org.opensearch.core.xcontent.XContentBuilder -import org.opensearch.core.xcontent.XContentParser - -class StopIndexReplicationRequest : - AcknowledgedRequest, IndicesRequest.Replaceable, ToXContentObject { - lateinit var indexName: String - constructor(indexName: String) { - this.indexName = indexName - } - - private constructor() { - } - - constructor(inp: StreamInput) : super(inp) { - indexName = inp.readString() - } - companion object { - private val PARSER = ObjectParser("StopReplicationRequestParser") { - StopIndexReplicationRequest() - } - - fun fromXContent(parser: XContentParser, followerIndex: String): StopIndexReplicationRequest { - val stopIndexReplicationRequest = PARSER.parse(parser, null) - stopIndexReplicationRequest.indexName = followerIndex - return stopIndexReplicationRequest - } - } - - override fun validate(): ActionRequestValidationException? { - return null - } - - override fun indices(vararg indices: String?): IndicesRequest { - return this - } - override fun indices(): Array { - return arrayOf(indexName) - } - - override fun indicesOptions(): IndicesOptions { - return IndicesOptions.strictSingleIndexNoExpandForbidClosed() - } - - override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject() - builder.field("indexName", indexName) - builder.endObject() - return builder - } - - override fun writeTo(out: StreamOutput) { - super.writeTo(out) - out.writeString(indexName) - } -} +/* + * Copyright OpenSearch Contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package org.opensearch.commons.replication.action + +import org.opensearch.action.ActionRequestValidationException +import org.opensearch.action.IndicesRequest +import org.opensearch.action.support.IndicesOptions +import org.opensearch.action.support.clustermanager.AcknowledgedRequest +import org.opensearch.core.common.io.stream.StreamInput +import org.opensearch.core.common.io.stream.StreamOutput +import org.opensearch.core.xcontent.ObjectParser +import org.opensearch.core.xcontent.ToXContent +import org.opensearch.core.xcontent.ToXContentObject +import org.opensearch.core.xcontent.XContentBuilder +import org.opensearch.core.xcontent.XContentParser + +class StopIndexReplicationRequest : + AcknowledgedRequest, + IndicesRequest.Replaceable, + ToXContentObject { + lateinit var indexName: String + constructor(indexName: String) { + this.indexName = indexName + } + + private constructor() { + } + + constructor(inp: StreamInput) : super(inp) { + indexName = inp.readString() + } + + companion object { + private val PARSER = + ObjectParser("StopReplicationRequestParser") { + StopIndexReplicationRequest() + } + + fun fromXContent( + parser: XContentParser, + followerIndex: String, + ): StopIndexReplicationRequest { + val stopIndexReplicationRequest = PARSER.parse(parser, null) + stopIndexReplicationRequest.indexName = followerIndex + return stopIndexReplicationRequest + } + } + + override fun validate(): ActionRequestValidationException? = null + + override fun indices(vararg indices: String?): IndicesRequest = this + + override fun indices(): Array = arrayOf(indexName) + + override fun indicesOptions(): IndicesOptions = IndicesOptions.strictSingleIndexNoExpandForbidClosed() + + override fun toXContent( + builder: XContentBuilder, + params: ToXContent.Params, + ): XContentBuilder { + builder.startObject() + builder.field("indexName", indexName) + builder.endObject() + return builder + } + + override fun writeTo(out: StreamOutput) { + super.writeTo(out) + out.writeString(indexName) + } +} diff --git a/src/main/kotlin/org/opensearch/commons/utils/EnumHelpers.kt b/src/main/kotlin/org/opensearch/commons/utils/EnumHelpers.kt index 6ffcdaed..f1a67b9e 100644 --- a/src/main/kotlin/org/opensearch/commons/utils/EnumHelpers.kt +++ b/src/main/kotlin/org/opensearch/commons/utils/EnumHelpers.kt @@ -19,15 +19,13 @@ inline fun > XContentParser.enumSet(enumParser: EnumParser> enumReader(enumClass: Class): Writeable.Reader { - return Writeable.Reader { +inline fun > enumReader(enumClass: Class): Writeable.Reader = + Writeable.Reader { it.readEnum(enumClass) } -} @Suppress("UnusedPrivateMember") -inline fun > enumWriter(ignore: Class): Writeable.Writer { - return Writeable.Writer { streamOutput: StreamOutput, value: E -> +inline fun > enumWriter(ignore: Class): Writeable.Writer = + Writeable.Writer { streamOutput: StreamOutput, value: E -> streamOutput.writeEnum(value) } -} diff --git a/src/main/kotlin/org/opensearch/commons/utils/Helpers.kt b/src/main/kotlin/org/opensearch/commons/utils/Helpers.kt index c31f0cab..d8ab6fbe 100644 --- a/src/main/kotlin/org/opensearch/commons/utils/Helpers.kt +++ b/src/main/kotlin/org/opensearch/commons/utils/Helpers.kt @@ -8,6 +8,4 @@ package org.opensearch.commons.utils import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger -fun logger(forClass: Class): Lazy { - return lazy { LogManager.getLogger(forClass) } -} +fun logger(forClass: Class): Lazy = lazy { LogManager.getLogger(forClass) } diff --git a/src/main/kotlin/org/opensearch/commons/utils/SecureClientWrapper.kt b/src/main/kotlin/org/opensearch/commons/utils/SecureClientWrapper.kt index 4179b54b..c83124cb 100644 --- a/src/main/kotlin/org/opensearch/commons/utils/SecureClientWrapper.kt +++ b/src/main/kotlin/org/opensearch/commons/utils/SecureClientWrapper.kt @@ -44,15 +44,21 @@ import org.opensearch.transport.client.Client * Wrapper class on [Client] with security context removed. */ @Suppress("TooManyFunctions") -class SecureClientWrapper(private val client: Client) : Client by client { +class SecureClientWrapper( + private val client: Client, +) : Client by client { /** * {@inheritDoc} */ override fun execute( action: ActionType, - request: Request + request: Request, ): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.execute(action, request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.execute(action, request) } } /** @@ -61,156 +67,274 @@ class SecureClientWrapper(private val client: Client) : Client by client { override fun execute( action: ActionType, request: Request, - listener: ActionListener + listener: ActionListener, ) { - client.threadPool().threadContext.stashContext().use { return client.execute(action, request, listener) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.execute(action, request, listener) } } /** * {@inheritDoc} */ override fun index(request: IndexRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.index(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.index(request) } } /** * {@inheritDoc} */ - override fun index(request: IndexRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.index(request, listener) } + override fun index( + request: IndexRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.index(request, listener) } } /** * {@inheritDoc} */ override fun update(request: UpdateRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.update(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.update(request) } } /** * {@inheritDoc} */ - override fun update(request: UpdateRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.update(request, listener) } + override fun update( + request: UpdateRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.update(request, listener) } } /** * {@inheritDoc} */ override fun delete(request: DeleteRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.delete(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.delete(request) } } /** * {@inheritDoc} */ - override fun delete(request: DeleteRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.delete(request, listener) } + override fun delete( + request: DeleteRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.delete(request, listener) } } /** * {@inheritDoc} */ override fun bulk(request: BulkRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.bulk(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.bulk(request) } } /** * {@inheritDoc} */ - override fun bulk(request: BulkRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.bulk(request, listener) } + override fun bulk( + request: BulkRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.bulk(request, listener) } } /** * {@inheritDoc} */ override fun get(request: GetRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.get(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.get(request) } } /** * {@inheritDoc} */ - override fun get(request: GetRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.get(request, listener) } + override fun get( + request: GetRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.get(request, listener) } } /** * {@inheritDoc} */ override fun multiGet(request: MultiGetRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.multiGet(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.multiGet(request) } } /** * {@inheritDoc} */ - override fun multiGet(request: MultiGetRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.multiGet(request, listener) } + override fun multiGet( + request: MultiGetRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.multiGet(request, listener) } } /** * {@inheritDoc} */ override fun search(request: SearchRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.search(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.search(request) } } /** * {@inheritDoc} */ - override fun search(request: SearchRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.search(request, listener) } + override fun search( + request: SearchRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.search(request, listener) } } /** * {@inheritDoc} */ override fun searchScroll(request: SearchScrollRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.searchScroll(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.searchScroll(request) } } /** * {@inheritDoc} */ - override fun searchScroll(request: SearchScrollRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.searchScroll(request, listener) } + override fun searchScroll( + request: SearchScrollRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.searchScroll(request, listener) } } /** * {@inheritDoc} */ override fun multiSearch(request: MultiSearchRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.multiSearch(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.multiSearch(request) } } /** * {@inheritDoc} */ - override fun multiSearch(request: MultiSearchRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.multiSearch(request, listener) } + override fun multiSearch( + request: MultiSearchRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.multiSearch(request, listener) } } /** * {@inheritDoc} */ override fun termVectors(request: TermVectorsRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.termVectors(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.termVectors(request) } } /** * {@inheritDoc} */ - override fun termVectors(request: TermVectorsRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.termVectors(request, listener) } + override fun termVectors( + request: TermVectorsRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.termVectors(request, listener) } } /** * {@inheritDoc} */ override fun multiTermVectors(request: MultiTermVectorsRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.multiTermVectors(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.multiTermVectors(request) } } /** @@ -218,51 +342,88 @@ class SecureClientWrapper(private val client: Client) : Client by client { */ override fun multiTermVectors( request: MultiTermVectorsRequest, - listener: ActionListener + listener: ActionListener, ) { - client.threadPool().threadContext.stashContext().use { return client.multiTermVectors(request, listener) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.multiTermVectors(request, listener) } } /** * {@inheritDoc} */ override fun explain(request: ExplainRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.explain(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.explain(request) } } /** * {@inheritDoc} */ - override fun explain(request: ExplainRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.explain(request, listener) } + override fun explain( + request: ExplainRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.explain(request, listener) } } /** * {@inheritDoc} */ override fun clearScroll(request: ClearScrollRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.clearScroll(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.clearScroll(request) } } /** * {@inheritDoc} */ - override fun clearScroll(request: ClearScrollRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.clearScroll(request, listener) } + override fun clearScroll( + request: ClearScrollRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.clearScroll(request, listener) } } /** * {@inheritDoc} */ override fun fieldCaps(request: FieldCapabilitiesRequest): ActionFuture { - client.threadPool().threadContext.stashContext().use { return client.fieldCaps(request) } + client + .threadPool() + .threadContext + .stashContext() + .use { return client.fieldCaps(request) } } /** * {@inheritDoc} */ - override fun fieldCaps(request: FieldCapabilitiesRequest, listener: ActionListener) { - client.threadPool().threadContext.stashContext().use { return client.fieldCaps(request, listener) } + override fun fieldCaps( + request: FieldCapabilitiesRequest, + listener: ActionListener, + ) { + client + .threadPool() + .threadContext + .stashContext() + .use { return client.fieldCaps(request, listener) } } /** @@ -295,12 +456,18 @@ class SecureClientWrapper(private val client: Client) : Client by client { * The suppressed exception is added to the list of suppressed exceptions of [cause] exception. */ @Suppress("TooGenericExceptionCaught") - private fun ThreadContext.StoredContext.closeFinally(cause: Throwable?) = when (cause) { - null -> close() - else -> try { - close() - } catch (closeException: Throwable) { - cause.addSuppressed(closeException) + private fun ThreadContext.StoredContext.closeFinally(cause: Throwable?) = + when (cause) { + null -> { + close() + } + + else -> { + try { + close() + } catch (closeException: Throwable) { + cause.addSuppressed(closeException) + } + } } - } } diff --git a/src/main/kotlin/org/opensearch/commons/utils/TransportHelpers.kt b/src/main/kotlin/org/opensearch/commons/utils/TransportHelpers.kt index 07d1ddb4..f05c9e9b 100644 --- a/src/main/kotlin/org/opensearch/commons/utils/TransportHelpers.kt +++ b/src/main/kotlin/org/opensearch/commons/utils/TransportHelpers.kt @@ -15,20 +15,25 @@ import org.opensearch.core.common.io.stream.Writeable import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream -val STRING_READER = Writeable.Reader { - it.readString() -} +val STRING_READER = + Writeable.Reader { + it.readString() + } -val STRING_WRITER = Writeable.Writer { output: StreamOutput, value: String -> - output.writeString(value) -} +val STRING_WRITER = + Writeable.Writer { output: StreamOutput, value: String -> + output.writeString(value) + } /** * Re create the object from the writeable. * This method needs to be inline and reified so that when this is called from * doExecute() of transport action, the object may be created from other JVM. */ -inline fun recreateObject(writeable: Writeable, block: (StreamInput) -> Request): Request { +inline fun recreateObject( + writeable: Writeable, + block: (StreamInput) -> Request, +): Request { ByteArrayOutputStream().use { byteArrayOutputStream -> OutputStreamStreamOutput(byteArrayOutputStream).use { writeable.writeTo(it) @@ -44,7 +49,11 @@ inline fun recreateObject(writeable: Writeable, block: (Stream * This method needs to be inline and reified so that when this is called from * doExecute() of transport action, the object may be created from other JVM. */ -inline fun recreateObject(writeable: Writeable, namedWriteableRegistry: NamedWriteableRegistry, block: (StreamInput) -> Request): Request { +inline fun recreateObject( + writeable: Writeable, + namedWriteableRegistry: NamedWriteableRegistry, + block: (StreamInput) -> Request, +): Request { ByteArrayOutputStream().use { byteArrayOutputStream -> OutputStreamStreamOutput(byteArrayOutputStream).use { writeable.writeTo(it) diff --git a/src/main/kotlin/org/opensearch/commons/utils/ValidationHelpers.kt b/src/main/kotlin/org/opensearch/commons/utils/ValidationHelpers.kt index 3bca2f9b..1da87aa2 100644 --- a/src/main/kotlin/org/opensearch/commons/utils/ValidationHelpers.kt +++ b/src/main/kotlin/org/opensearch/commons/utils/ValidationHelpers.kt @@ -54,21 +54,20 @@ fun isValidUrl(urlString: String): Boolean { * Regex was based off of this post: https://stackoverflow.com/a/201378 */ fun isValidEmail(email: String): Boolean { - val validEmailPattern = Regex( - "(?:[a-z0-9!#\$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#\$%&'*+\\/=?^_`{|}~-]+)*" + - "|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")" + - "@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" + - "|\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\.){3}" + - "(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:" + - "(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", - RegexOption.IGNORE_CASE - ) + val validEmailPattern = + Regex( + "(?:[a-z0-9!#\$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#\$%&'*+\\/=?^_`{|}~-]+)*" + + "|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")" + + "@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" + + "|\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\.){3}" + + "(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:" + + "(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", + RegexOption.IGNORE_CASE, + ) return validEmailPattern.matches(email) } -fun isValidId(idString: String): Boolean { - return idString.isNotBlank() && idString.all { VALID_ID_CHARS.contains(it) } -} +fun isValidId(idString: String): Boolean = idString.isNotBlank() && idString.all { VALID_ID_CHARS.contains(it) } fun validateIamRoleArn(roleArn: String) { val roleArnRegex = Pattern.compile("^arn:aws(-[^:]+)?:iam::([0-9]{12}):([a-zA-Z_0-9+=,.@\\-_/]+)$") @@ -83,6 +82,4 @@ fun isValidName(name: String): Boolean { return name.matches(regex) } -fun getInvalidNameChars(): String { - return INVALID_NAME_CHARS -} +fun getInvalidNameChars(): String = INVALID_NAME_CHARS diff --git a/src/main/kotlin/org/opensearch/commons/utils/XContentHelpers.kt b/src/main/kotlin/org/opensearch/commons/utils/XContentHelpers.kt index e2fe0ddf..838d2b39 100644 --- a/src/main/kotlin/org/opensearch/commons/utils/XContentHelpers.kt +++ b/src/main/kotlin/org/opensearch/commons/utils/XContentHelpers.kt @@ -16,10 +16,10 @@ import org.opensearch.core.xcontent.XContentParser import org.opensearch.core.xcontent.XContentParserUtils import org.opensearch.rest.RestRequest -fun StreamInput.createJsonParser(): XContentParser { - return XContentType.JSON.xContent() +fun StreamInput.createJsonParser(): XContentParser = + XContentType.JSON + .xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.IGNORE_DEPRECATIONS, this) -} fun RestRequest.contentParserNextToken(): XContentParser { val parser = this.contentParser() @@ -36,14 +36,20 @@ fun XContentParser.stringList(): List { return retList } -fun XContentBuilder.fieldIfNotNull(name: String, value: Any?): XContentBuilder { +fun XContentBuilder.fieldIfNotNull( + name: String, + value: Any?, +): XContentBuilder { if (value != null) { this.field(name, value) } return this } -fun XContentBuilder.objectIfNotNull(name: String, xContentObject: ToXContentObject?): XContentBuilder { +fun XContentBuilder.objectIfNotNull( + name: String, + xContentObject: ToXContentObject?, +): XContentBuilder { if (xContentObject != null) { this.field(name) xContentObject.toXContent(this, ToXContent.EMPTY_PARAMS) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/AlertTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/AlertTests.kt index 4a5f2346..b33fe238 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/AlertTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/AlertTests.kt @@ -45,12 +45,12 @@ class AlertTests { assertEquals( templateArgs[Alert.BUCKET_KEYS], alert.aggregationResultBucket?.bucketKeys?.joinToString(","), - "Template args bucketKeys do not match" + "Template args bucketKeys do not match", ) assertEquals( templateArgs[Alert.PARENTS_BUCKET_PATH], alert.aggregationResultBucket?.parentBucketPath, - "Template args parentBucketPath does not match" + "Template args parentBucketPath does not match", ) } @@ -65,13 +65,14 @@ class AlertTests { @Test fun `test alert in audit state`() { - val auditAlert = Alert( - randomQueryLevelMonitor(), - randomQueryLevelTrigger(), - Instant.now().truncatedTo(ChronoUnit.MILLIS), - null, - actionExecutionResults = listOf(randomActionExecutionResult()) - ) + val auditAlert = + Alert( + randomQueryLevelMonitor(), + randomQueryLevelTrigger(), + Instant.now().truncatedTo(ChronoUnit.MILLIS), + null, + actionExecutionResults = listOf(randomActionExecutionResult()), + ) Assertions.assertFalse(auditAlert.isAcknowledged(), "Alert should not be in acknowledged state") } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/AlertingPluginInterfaceTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/AlertingPluginInterfaceTests.kt index cb526f60..ec267c12 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/AlertingPluginInterfaceTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/AlertingPluginInterfaceTests.kt @@ -50,7 +50,6 @@ import org.opensearch.transport.client.node.NodeClient @Suppress("UNCHECKED_CAST") @ExtendWith(MockitoExtension::class) internal class AlertingPluginInterfaceTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) private lateinit var client: NodeClient @@ -59,21 +58,24 @@ internal class AlertingPluginInterfaceTests { val monitor = randomQueryLevelMonitor() val request = mock(IndexMonitorRequest::class.java) - val response = IndexMonitorResponse( - Monitor.NO_ID, - Monitor.NO_VERSION, - SequenceNumbers.UNASSIGNED_SEQ_NO, - SequenceNumbers.UNASSIGNED_PRIMARY_TERM, - monitor - ) + val response = + IndexMonitorResponse( + Monitor.NO_ID, + Monitor.NO_VERSION, + SequenceNumbers.UNASSIGNED_SEQ_NO, + SequenceNumbers.UNASSIGNED_PRIMARY_TERM, + monitor, + ) val listener: ActionListener = mock(ActionListener::class.java) as ActionListener val namedWriteableRegistry = NamedWriteableRegistry(SearchModule(Settings.EMPTY, emptyList()).namedWriteables) - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.indexMonitor(client, request, namedWriteableRegistry, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) @@ -84,20 +86,23 @@ internal class AlertingPluginInterfaceTests { val workflow = randomWorkflow() val request = mock(IndexWorkflowRequest::class.java) - val response = IndexWorkflowResponse( - Workflow.NO_ID, - Workflow.NO_VERSION, - SequenceNumbers.UNASSIGNED_SEQ_NO, - SequenceNumbers.UNASSIGNED_PRIMARY_TERM, - workflow - ) + val response = + IndexWorkflowResponse( + Workflow.NO_ID, + Workflow.NO_VERSION, + SequenceNumbers.UNASSIGNED_SEQ_NO, + SequenceNumbers.UNASSIGNED_PRIMARY_TERM, + workflow, + ) val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.indexWorkflow(client, request, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) @@ -108,21 +113,24 @@ internal class AlertingPluginInterfaceTests { val monitor = randomBucketLevelMonitor() val request = mock(IndexMonitorRequest::class.java) - val response = IndexMonitorResponse( - Monitor.NO_ID, - Monitor.NO_VERSION, - SequenceNumbers.UNASSIGNED_SEQ_NO, - SequenceNumbers.UNASSIGNED_PRIMARY_TERM, - monitor - ) + val response = + IndexMonitorResponse( + Monitor.NO_ID, + Monitor.NO_VERSION, + SequenceNumbers.UNASSIGNED_SEQ_NO, + SequenceNumbers.UNASSIGNED_PRIMARY_TERM, + monitor, + ) val listener: ActionListener = mock(ActionListener::class.java) as ActionListener val namedWriteableRegistry = NamedWriteableRegistry(SearchModule(Settings.EMPTY, emptyList()).namedWriteables) - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.indexMonitor(client, request, namedWriteableRegistry, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) @@ -135,10 +143,12 @@ internal class AlertingPluginInterfaceTests { val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.deleteMonitor(client, request, listener) } @@ -150,10 +160,12 @@ internal class AlertingPluginInterfaceTests { val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.deleteWorkflow(client, request, listener) } @@ -161,21 +173,24 @@ internal class AlertingPluginInterfaceTests { @Test fun getWorkflow() { val request = mock(GetWorkflowRequest::class.java) - val response = GetWorkflowResponse( - id = "id", - version = 1, - seqNo = 1, - primaryTerm = 1, - status = RestStatus.OK, - workflow = randomWorkflow() - ) + val response = + GetWorkflowResponse( + id = "id", + version = 1, + seqNo = 1, + primaryTerm = 1, + status = RestStatus.OK, + workflow = randomWorkflow(), + ) val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.getWorkflow(client, request, listener) } @@ -189,10 +204,12 @@ internal class AlertingPluginInterfaceTests { val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.getAlerts(client, request, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) } @@ -204,10 +221,12 @@ internal class AlertingPluginInterfaceTests { val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.getWorkflowAlerts(client, request, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) } @@ -228,10 +247,12 @@ internal class AlertingPluginInterfaceTests { val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.getFindings(client, request, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) } @@ -243,10 +264,12 @@ internal class AlertingPluginInterfaceTests { val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.publishFinding(client, request, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) } @@ -257,10 +280,12 @@ internal class AlertingPluginInterfaceTests { val response = AcknowledgeAlertResponse(acknowledged = listOf(), failed = listOf(), missing = listOf()) val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.acknowledgeAlerts(client, request, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) } @@ -271,10 +296,12 @@ internal class AlertingPluginInterfaceTests { val response = AcknowledgeAlertResponse(acknowledged = listOf(), failed = listOf(), missing = listOf()) val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.acknowledgeChainedAlerts(client, request, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) } @@ -285,10 +312,12 @@ internal class AlertingPluginInterfaceTests { val response = GetMonitorResponse("test-id", 1, 1, 1, null, null) val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.getMonitor(client, request, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) } @@ -299,10 +328,12 @@ internal class AlertingPluginInterfaceTests { val response = mock(SearchResponse::class.java) val listener: ActionListener = mock(ActionListener::class.java) as ActionListener - Mockito.doAnswer { - (it.getArgument(2) as ActionListener) - .onResponse(response) - }.whenever(client).execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) + Mockito + .doAnswer { + (it.getArgument(2) as ActionListener) + .onResponse(response) + }.whenever(client) + .execute(Mockito.any(ActionType::class.java), Mockito.any(), Mockito.any()) AlertingPluginInterface.searchMonitors(client, request, listener) Mockito.verify(listener, Mockito.times(1)).onResponse(ArgumentMatchers.eq(response)) } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/CorrelationAlertTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/CorrelationAlertTests.kt index aa315aeb..5e8086fb 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/CorrelationAlertTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/CorrelationAlertTests.kt @@ -9,7 +9,6 @@ import org.opensearch.commons.utils.recreateObject import java.time.temporal.ChronoUnit class CorrelationAlertTests { - @Test fun `test correlation alert as template args`() { // Create sample data for CorrelationAlert @@ -21,17 +20,17 @@ class CorrelationAlertTests { assertEquals( templateArgs["correlated_finding_ids"], correlationAlert.correlatedFindingIds, - "Template args correlatedFindingIds does not match" + "Template args correlatedFindingIds does not match", ) assertEquals( templateArgs["correlation_rule_id"], correlationAlert.correlationRuleId, - "Template args correlationRuleId does not match" + "Template args correlationRuleId does not match", ) assertEquals( templateArgs["correlation_rule_name"], correlationAlert.correlationRuleName, - "Template args correlationRuleName does not match" + "Template args correlationRuleName does not match", ) // Verify inherited properties from BaseAlert @@ -41,7 +40,7 @@ class CorrelationAlertTests { assertEquals( templateArgs["trigger_name"], correlationAlert.triggerName, - "Template args triggerName does not match" + "Template args triggerName does not match", ) assertEquals(templateArgs["state"], correlationAlert.state, "Template args state does not match") assertEquals(templateArgs["start_time"], correlationAlert.startTime, "Template args startTime does not match") @@ -49,18 +48,18 @@ class CorrelationAlertTests { assertEquals( templateArgs["acknowledged_time"], correlationAlert.acknowledgedTime, - "Template args acknowledgedTime does not match" + "Template args acknowledgedTime does not match", ) assertEquals( templateArgs["error_message"], correlationAlert.errorMessage, - "Template args errorMessage does not match" + "Template args errorMessage does not match", ) assertEquals(templateArgs["severity"], correlationAlert.severity, "Template args severity does not match") assertEquals( templateArgs["action_execution_results"], correlationAlert.actionExecutionResults, - "Template args actionExecutionResults does not match" + "Template args actionExecutionResults does not match", ) } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt b/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt index 8177057d..cb067c6e 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt @@ -87,14 +87,20 @@ fun randomQueryLevelMonitor( triggers: List = (1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomQueryLevelTrigger() }, enabledTime: Instant? = if (enabled) Instant.now().truncatedTo(ChronoUnit.MILLIS) else null, lastUpdateTime: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS), - withMetadata: Boolean = false -): Monitor { - return Monitor( - name = name, monitorType = Monitor.MonitorType.QUERY_LEVEL_MONITOR.value, enabled = enabled, inputs = inputs, - schedule = schedule, triggers = triggers, enabledTime = enabledTime, lastUpdateTime = lastUpdateTime, user = user, - uiMetadata = if (withMetadata) mapOf("foo" to "bar") else mapOf() + withMetadata: Boolean = false, +): Monitor = + Monitor( + name = name, + monitorType = Monitor.MonitorType.QUERY_LEVEL_MONITOR.value, + enabled = enabled, + inputs = inputs, + schedule = schedule, + triggers = triggers, + enabledTime = enabledTime, + lastUpdateTime = lastUpdateTime, + user = user, + uiMetadata = if (withMetadata) mapOf("foo" to "bar") else mapOf(), ) -} // Monitor of older versions without security. fun randomQueryLevelMonitorWithoutUser( @@ -105,38 +111,52 @@ fun randomQueryLevelMonitorWithoutUser( triggers: List = (1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomQueryLevelTrigger() }, enabledTime: Instant? = if (enabled) Instant.now().truncatedTo(ChronoUnit.MILLIS) else null, lastUpdateTime: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS), - withMetadata: Boolean = false -): Monitor { - return Monitor( - name = name, monitorType = Monitor.MonitorType.QUERY_LEVEL_MONITOR.value, enabled = enabled, inputs = inputs, - schedule = schedule, triggers = triggers, enabledTime = enabledTime, lastUpdateTime = lastUpdateTime, user = null, - uiMetadata = if (withMetadata) mapOf("foo" to "bar") else mapOf() + withMetadata: Boolean = false, +): Monitor = + Monitor( + name = name, + monitorType = Monitor.MonitorType.QUERY_LEVEL_MONITOR.value, + enabled = enabled, + inputs = inputs, + schedule = schedule, + triggers = triggers, + enabledTime = enabledTime, + lastUpdateTime = lastUpdateTime, + user = null, + uiMetadata = if (withMetadata) mapOf("foo" to "bar") else mapOf(), ) -} fun randomBucketLevelMonitor( name: String = RandomStrings.randomAsciiLettersOfLength(Random(), 10), user: User = randomUser(), - inputs: List = listOf( - SearchInput( - emptyList(), - SearchSourceBuilder().query(QueryBuilders.matchAllQuery()) - .aggregation(TermsAggregationBuilder("test_agg").field("test_field")) - ) - ), + inputs: List = + listOf( + SearchInput( + emptyList(), + SearchSourceBuilder() + .query(QueryBuilders.matchAllQuery()) + .aggregation(TermsAggregationBuilder("test_agg").field("test_field")), + ), + ), schedule: Schedule = IntervalSchedule(interval = 5, unit = ChronoUnit.MINUTES), enabled: Boolean = Random().nextBoolean(), triggers: List = (1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomBucketLevelTrigger() }, enabledTime: Instant? = if (enabled) Instant.now().truncatedTo(ChronoUnit.MILLIS) else null, lastUpdateTime: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS), - withMetadata: Boolean = false -): Monitor { - return Monitor( - name = name, monitorType = Monitor.MonitorType.BUCKET_LEVEL_MONITOR.value, enabled = enabled, inputs = inputs, - schedule = schedule, triggers = triggers, enabledTime = enabledTime, lastUpdateTime = lastUpdateTime, user = user, - uiMetadata = if (withMetadata) mapOf("foo" to "bar") else mapOf() + withMetadata: Boolean = false, +): Monitor = + Monitor( + name = name, + monitorType = Monitor.MonitorType.BUCKET_LEVEL_MONITOR.value, + enabled = enabled, + inputs = inputs, + schedule = schedule, + triggers = triggers, + enabledTime = enabledTime, + lastUpdateTime = lastUpdateTime, + user = user, + uiMetadata = if (withMetadata) mapOf("foo" to "bar") else mapOf(), ) -} fun randomClusterMetricsMonitor( name: String = RandomStrings.randomAsciiLettersOfLength(Random(), 10), @@ -147,14 +167,20 @@ fun randomClusterMetricsMonitor( triggers: List = (1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomQueryLevelTrigger() }, enabledTime: Instant? = if (enabled) Instant.now().truncatedTo(ChronoUnit.MILLIS) else null, lastUpdateTime: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS), - withMetadata: Boolean = false -): Monitor { - return Monitor( - name = name, monitorType = Monitor.MonitorType.CLUSTER_METRICS_MONITOR.value, enabled = enabled, inputs = inputs, - schedule = schedule, triggers = triggers, enabledTime = enabledTime, lastUpdateTime = lastUpdateTime, user = user, - uiMetadata = if (withMetadata) mapOf("foo" to "bar") else mapOf() + withMetadata: Boolean = false, +): Monitor = + Monitor( + name = name, + monitorType = Monitor.MonitorType.CLUSTER_METRICS_MONITOR.value, + enabled = enabled, + inputs = inputs, + schedule = schedule, + triggers = triggers, + enabledTime = enabledTime, + lastUpdateTime = lastUpdateTime, + user = user, + uiMetadata = if (withMetadata) mapOf("foo" to "bar") else mapOf(), ) -} fun randomDocumentLevelMonitor( name: String = RandomStrings.randomAsciiLettersOfLength(Random(), 10), @@ -165,14 +191,20 @@ fun randomDocumentLevelMonitor( triggers: List = (1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomDocumentLevelTrigger() }, enabledTime: Instant? = if (enabled) Instant.now().truncatedTo(ChronoUnit.MILLIS) else null, lastUpdateTime: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS), - withMetadata: Boolean = false -): Monitor { - return Monitor( - name = name, monitorType = Monitor.MonitorType.DOC_LEVEL_MONITOR.value, enabled = enabled, inputs = inputs, - schedule = schedule, triggers = triggers, enabledTime = enabledTime, lastUpdateTime = lastUpdateTime, user = user, - uiMetadata = if (withMetadata) mapOf("foo" to "bar") else mapOf() + withMetadata: Boolean = false, +): Monitor = + Monitor( + name = name, + monitorType = Monitor.MonitorType.DOC_LEVEL_MONITOR.value, + enabled = enabled, + inputs = inputs, + schedule = schedule, + triggers = triggers, + enabledTime = enabledTime, + lastUpdateTime = lastUpdateTime, + user = user, + uiMetadata = if (withMetadata) mapOf("foo" to "bar") else mapOf(), ) -} fun randomWorkflow( name: String = RandomStrings.randomAsciiLettersOfLength(Random(), 10), @@ -183,30 +215,38 @@ fun randomWorkflow( enabledTime: Instant? = if (enabled) Instant.now().truncatedTo(ChronoUnit.MILLIS) else null, lastUpdateTime: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS), triggers: List = listOf(randomChainedAlertTrigger()), - auditDelegateMonitorAlerts: Boolean? = true + auditDelegateMonitorAlerts: Boolean? = true, ): Workflow { val delegates = mutableListOf() if (!monitorIds.isNullOrEmpty()) { delegates.add(Delegate(1, monitorIds[0])) for (i in 1 until monitorIds.size) { // Order of monitors in workflow will be the same like forwarded meaning that the first monitorId will be used as second monitor chained finding - delegates.add(Delegate(i + 1, monitorIds [i], ChainedMonitorFindings(monitorIds[i - 1]))) + delegates.add(Delegate(i + 1, monitorIds[i], ChainedMonitorFindings(monitorIds[i - 1]))) } } var input = listOf(CompositeInput(Sequence(delegates))) if (input == null) { - input = listOf( - CompositeInput( - Sequence( - listOf(Delegate(1, "delegate1")) - ) + input = + listOf( + CompositeInput( + Sequence( + listOf(Delegate(1, "delegate1")), + ), + ), ) - ) } return Workflow( - name = name, workflowType = Workflow.WorkflowType.COMPOSITE, enabled = enabled, inputs = input, - schedule = schedule, enabledTime = enabledTime, lastUpdateTime = lastUpdateTime, user = user, - triggers = triggers, auditDelegateMonitorAlerts = auditDelegateMonitorAlerts + name = name, + workflowType = Workflow.WorkflowType.COMPOSITE, + enabled = enabled, + inputs = input, + schedule = schedule, + enabledTime = enabledTime, + lastUpdateTime = lastUpdateTime, + user = user, + triggers = triggers, + auditDelegateMonitorAlerts = auditDelegateMonitorAlerts, ) } @@ -218,33 +258,32 @@ fun randomWorkflowWithDelegates( enabled: Boolean = Random().nextBoolean(), enabledTime: Instant? = if (enabled) Instant.now().truncatedTo(ChronoUnit.MILLIS) else null, lastUpdateTime: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS), - triggers: List = (1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomChainedAlertTrigger() } -): Workflow { - return Workflow( - name = name, workflowType = Workflow.WorkflowType.COMPOSITE, enabled = enabled, inputs = input, - schedule = schedule, enabledTime = enabledTime, lastUpdateTime = lastUpdateTime, user = user, - triggers = triggers + triggers: List = (1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomChainedAlertTrigger() }, +): Workflow = + Workflow( + name = name, + workflowType = Workflow.WorkflowType.COMPOSITE, + enabled = enabled, + inputs = input, + schedule = schedule, + enabledTime = enabledTime, + lastUpdateTime = lastUpdateTime, + user = user, + triggers = triggers, ) -} fun Workflow.toJsonStringWithUser(): String { val builder = XContentFactory.jsonBuilder() return this.toXContentWithUser(builder, ToXContent.EMPTY_PARAMS).string() } -fun randomSequence( - delegates: List = listOf(randomDelegate()) -): Sequence { - return Sequence(delegates) -} +fun randomSequence(delegates: List = listOf(randomDelegate())): Sequence = Sequence(delegates) fun randomDelegate( order: Int = 1, monitorId: String = RandomStrings.randomAsciiLettersOfLength(Random(), 10), - chainedMonitorFindings: ChainedMonitorFindings? = null -): Delegate { - return Delegate(order, monitorId, chainedMonitorFindings) -} + chainedMonitorFindings: ChainedMonitorFindings? = null, +): Delegate = Delegate(order, monitorId, chainedMonitorFindings) fun randomQueryLevelTrigger( id: String = UUIDs.base64UUID(), @@ -252,16 +291,22 @@ fun randomQueryLevelTrigger( severity: String = "1", condition: Script = randomScript(), actions: List = mutableListOf(), - destinationId: String = "" -): QueryLevelTrigger { - return QueryLevelTrigger( + destinationId: String = "", +): QueryLevelTrigger = + QueryLevelTrigger( id = id, name = name, severity = severity, condition = condition, - actions = if (actions.isEmpty()) (0..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomAction(destinationId = destinationId) } else actions + actions = + if (actions.isEmpty()) { + (0..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { + randomAction(destinationId = destinationId) + } + } else { + actions + }, ) -} fun randomBucketLevelTrigger( id: String = UUIDs.base64UUID(), @@ -269,19 +314,21 @@ fun randomBucketLevelTrigger( severity: String = "1", bucketSelector: BucketSelectorExtAggregationBuilder = randomBucketSelectorExtAggregationBuilder(name = id), actions: List = mutableListOf(), - destinationId: String = "" -): BucketLevelTrigger { - return BucketLevelTrigger( + destinationId: String = "", +): BucketLevelTrigger = + BucketLevelTrigger( id = id, name = name, severity = severity, bucketSelector = bucketSelector, - actions = if (actions.isEmpty()) randomActionsForBucketLevelTrigger(destinationId = destinationId) else actions + actions = if (actions.isEmpty()) randomActionsForBucketLevelTrigger(destinationId = destinationId) else actions, ) -} -fun randomActionsForBucketLevelTrigger(min: Int = 0, max: Int = 10, destinationId: String = ""): List = - (min..RandomNumbers.randomIntBetween(Random(), 0, max)).map { randomActionWithPolicy(destinationId = destinationId) } +fun randomActionsForBucketLevelTrigger( + min: Int = 0, + max: Int = 10, + destinationId: String = "", +): List = (min..RandomNumbers.randomIntBetween(Random(), 0, max)).map { randomActionWithPolicy(destinationId = destinationId) } fun randomDocumentLevelTrigger( id: String = UUIDs.base64UUID(), @@ -289,20 +336,20 @@ fun randomDocumentLevelTrigger( severity: String = "1", condition: Script = randomScript(), actions: List = mutableListOf(), - destinationId: String = "" -): DocumentLevelTrigger { - return DocumentLevelTrigger( + destinationId: String = "", +): DocumentLevelTrigger = + DocumentLevelTrigger( id = id, name = name, severity = severity, condition = condition, - actions = if (actions.isEmpty() && destinationId.isNotBlank()) { - (0..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomAction(destinationId = destinationId) } - } else { - actions - } + actions = + if (actions.isEmpty() && destinationId.isNotBlank()) { + (0..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomAction(destinationId = destinationId) } + } else { + actions + }, ) -} fun randomChainedAlertTrigger( id: String = UUIDs.base64UUID(), @@ -310,43 +357,39 @@ fun randomChainedAlertTrigger( severity: String = "1", condition: Script = randomScript(), actions: List = mutableListOf(), - destinationId: String = "" -): ChainedAlertTrigger { - return ChainedAlertTrigger( + destinationId: String = "", +): ChainedAlertTrigger = + ChainedAlertTrigger( id = id, name = name, severity = severity, condition = condition, - actions = if (actions.isEmpty() && destinationId.isNotBlank()) { - (0..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomAction(destinationId = destinationId) } - } else { - actions - } + actions = + if (actions.isEmpty() && destinationId.isNotBlank()) { + (0..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomAction(destinationId = destinationId) } + } else { + actions + }, ) -} fun randomBucketSelectorExtAggregationBuilder( name: String = RandomStrings.randomAsciiLettersOfLength(Random(), 10), bucketsPathsMap: MutableMap = mutableMapOf("avg" to "10"), script: Script = randomBucketSelectorScript(params = bucketsPathsMap), parentBucketPath: String = "testPath", - filter: BucketSelectorExtFilter = BucketSelectorExtFilter(IncludeExclude("foo*", "bar*")) -): BucketSelectorExtAggregationBuilder { - return BucketSelectorExtAggregationBuilder(name, bucketsPathsMap, script, parentBucketPath, filter) -} + filter: BucketSelectorExtFilter = BucketSelectorExtFilter(IncludeExclude("foo*", "bar*")), +): BucketSelectorExtAggregationBuilder = BucketSelectorExtAggregationBuilder(name, bucketsPathsMap, script, parentBucketPath, filter) fun randomBucketSelectorScript( idOrCode: String = "params.avg >= 0", - params: Map = mutableMapOf("avg" to "10") -): Script { - return Script(Script.DEFAULT_SCRIPT_TYPE, Script.DEFAULT_SCRIPT_LANG, idOrCode, emptyMap(), params) -} + params: Map = mutableMapOf("avg" to "10"), +): Script = Script(Script.DEFAULT_SCRIPT_TYPE, Script.DEFAULT_SCRIPT_LANG, idOrCode, emptyMap(), params) fun randomScript(source: String = "return " + Random().nextBoolean().toString()): Script = Script(source) fun randomTemplateScript( source: String, - params: Map = emptyMap() + params: Map = emptyMap(), ): Script = Script(ScriptType.INLINE, Script.DEFAULT_TEMPLATE_LANG, source, params) fun randomAction( @@ -354,7 +397,7 @@ fun randomAction( template: Script = randomTemplateScript("Hello World"), destinationId: String = "", throttleEnabled: Boolean = false, - throttle: Throttle = randomThrottle() + throttle: Throttle = randomThrottle(), ) = Action(name, destinationId, template, template, throttleEnabled, throttle, actionExecutionPolicy = null) fun randomActionWithPolicy( @@ -363,68 +406,77 @@ fun randomActionWithPolicy( destinationId: String = "", throttleEnabled: Boolean = false, throttle: Throttle = randomThrottle(), - actionExecutionPolicy: ActionExecutionPolicy? = randomActionExecutionPolicy() -): Action { - return if (actionExecutionPolicy?.actionExecutionScope is PerExecutionActionScope) { + actionExecutionPolicy: ActionExecutionPolicy? = randomActionExecutionPolicy(), +): Action = + if (actionExecutionPolicy?.actionExecutionScope is PerExecutionActionScope) { // Return null for throttle when using PerExecutionActionScope since throttling is currently not supported for it Action(name, destinationId, template, template, throttleEnabled, null, actionExecutionPolicy = actionExecutionPolicy) } else { Action(name, destinationId, template, template, throttleEnabled, throttle, actionExecutionPolicy = actionExecutionPolicy) } -} fun randomThrottle( value: Int = RandomNumbers.randomIntBetween(Random(), 60, 120), - unit: ChronoUnit = ChronoUnit.MINUTES + unit: ChronoUnit = ChronoUnit.MINUTES, ) = Throttle(value, unit) -fun randomActionExecutionPolicy( - actionExecutionScope: ActionExecutionScope = randomActionExecutionScope() -) = ActionExecutionPolicy(actionExecutionScope) +fun randomActionExecutionPolicy(actionExecutionScope: ActionExecutionScope = randomActionExecutionScope()) = + ActionExecutionPolicy(actionExecutionScope) -fun randomActionExecutionScope(): ActionExecutionScope { - return if (Random().nextBoolean()) { +fun randomActionExecutionScope(): ActionExecutionScope = + if (Random().nextBoolean()) { val alertCategories = AlertCategory.values() - PerAlertActionScope(actionableAlerts = (1..RandomNumbers.randomIntBetween(Random(), 0, alertCategories.size)).map { alertCategories[it - 1] }.toSet()) + PerAlertActionScope( + actionableAlerts = + (1..RandomNumbers.randomIntBetween(Random(), 0, alertCategories.size)) + .map { + alertCategories[ + it - + 1, + ] + }.toSet(), + ) } else { PerExecutionActionScope() } -} fun randomDocLevelQuery( id: String = RandomStrings.randomAsciiLettersOfLength(Random(), 10), query: String = RandomStrings.randomAsciiLettersOfLength(Random(), 10), name: String = "${RandomNumbers.randomIntBetween(Random(), 0, 5)}", - tags: List = mutableListOf(0..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { RandomStrings.randomAsciiLettersOfLength(Random(), 10) } -): DocLevelQuery { - return DocLevelQuery(id = id, query = query, name = name, tags = tags, fields = listOf("*")) -} + tags: List = + mutableListOf(0..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { + RandomStrings.randomAsciiLettersOfLength(Random(), 10) + }, +): DocLevelQuery = DocLevelQuery(id = id, query = query, name = name, tags = tags, fields = listOf("*")) fun randomDocLevelMonitorInput( description: String = RandomStrings.randomAsciiLettersOfLength(Random(), RandomNumbers.randomIntBetween(Random(), 0, 10)), - indices: List = listOf(1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { RandomStrings.randomAsciiLettersOfLength(Random(), 10) }, - queries: List = listOf(1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomDocLevelQuery() } -): DocLevelMonitorInput { - return DocLevelMonitorInput(description = description, indices = indices, queries = queries) -} + indices: List = + listOf(1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { + RandomStrings.randomAsciiLettersOfLength(Random(), 10) + }, + queries: List = listOf(1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomDocLevelQuery() }, +): DocLevelMonitorInput = DocLevelMonitorInput(description = description, indices = indices, queries = queries) fun randomSearchInput( - indices: List = listOf(1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { RandomStrings.randomAsciiLettersOfLength(Random(), 10) }, - query: SearchSourceBuilder = SearchSourceBuilder().query(QueryBuilders.matchAllQuery()) -): SearchInput { - return SearchInput(indices, query) -} + indices: List = + listOf(1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { + RandomStrings.randomAsciiLettersOfLength(Random(), 10) + }, + query: SearchSourceBuilder = SearchSourceBuilder().query(QueryBuilders.matchAllQuery()), +): SearchInput = SearchInput(indices, query) fun randomClusterMetricsInput( - path: String = ClusterMetricsInput.ClusterMetricType.values() - .filter { it.defaultPath.isNotBlank() && !it.requiresPathParams } - .random() - .defaultPath, + path: String = + ClusterMetricsInput.ClusterMetricType + .values() + .filter { it.defaultPath.isNotBlank() && !it.requiresPathParams } + .random() + .defaultPath, pathParams: String = "", - url: String = "" -): ClusterMetricsInput { - return ClusterMetricsInput(path, pathParams, url) -} + url: String = "", +): ClusterMetricsInput = ClusterMetricsInput(path, pathParams, url) fun ChainedMonitorFindings.toJsonString(): String { val builder = XContentFactory.jsonBuilder() @@ -446,21 +498,18 @@ fun Monitor.toJsonStringWithUser(): String { return this.toXContentWithUser(builder, ToXContent.EMPTY_PARAMS).string() } -fun randomUser(): User { - return User( +fun randomUser(): User = + User( RandomStrings.randomAsciiLettersOfLength(Random(), 10), listOf( RandomStrings.randomAsciiLettersOfLength(Random(), 10), - RandomStrings.randomAsciiLettersOfLength(Random(), 10) + RandomStrings.randomAsciiLettersOfLength(Random(), 10), ), listOf(RandomStrings.randomAsciiLettersOfLength(Random(), 10), ALL_ACCESS_ROLE), - mapOf("test_attr" to "test") + mapOf("test_attr" to "test"), ) -} -fun randomUserEmpty(): User { - return User("", listOf(), listOf(), mapOf()) -} +fun randomUserEmpty(): User = User("", listOf(), listOf(), mapOf()) /** * Wrapper for [RestClient.performRequest] which was deprecated in ES 6.5 and is used in tests. This provides @@ -473,7 +522,7 @@ fun RestClient.makeRequest( endpoint: String, params: Map = emptyMap(), entity: HttpEntity? = null, - vararg headers: Header + vararg headers: Header, ): Response { val request = Request(method, endpoint) // TODO: remove PERMISSIVE option after moving system index access to REST API call @@ -498,7 +547,7 @@ fun RestClient.makeRequest( method: String, endpoint: String, entity: HttpEntity? = null, - vararg headers: Header + vararg headers: Header, ): Response { val request = Request(method, endpoint) val options = RequestOptions.DEFAULT.toBuilder() @@ -512,9 +561,7 @@ fun RestClient.makeRequest( return performRequest(request) } -fun builder(): XContentBuilder { - return XContentBuilder.builder(XContentType.JSON.xContent()) -} +fun builder(): XContentBuilder = XContentBuilder.builder(XContentType.JSON.xContent()) fun parser(xc: String): XContentParser { val parser = XContentType.JSON.xContent().createParser(xContentRegistry(), LoggingDeprecationHandler.INSTANCE, xc) @@ -528,8 +575,8 @@ fun parser(xc: ByteArray): XContentParser { return parser } -fun xContentRegistry(): NamedXContentRegistry { - return NamedXContentRegistry( +fun xContentRegistry(): NamedXContentRegistry = + NamedXContentRegistry( listOf( SearchInput.XCONTENT_REGISTRY, DocLevelMonitorInput.XCONTENT_REGISTRY, @@ -538,10 +585,9 @@ fun xContentRegistry(): NamedXContentRegistry { DocumentLevelTrigger.XCONTENT_REGISTRY, ChainedAlertTrigger.XCONTENT_REGISTRY, NoOpTrigger.XCONTENT_REGISTRY, - RemoteMonitorTrigger.XCONTENT_REGISTRY - ) + SearchModule(Settings.EMPTY, emptyList()).namedXContents + RemoteMonitorTrigger.XCONTENT_REGISTRY, + ) + SearchModule(Settings.EMPTY, emptyList()).namedXContents, ) -} fun assertUserNull(map: Map) { val user = map["user"] @@ -563,15 +609,15 @@ fun randomAlert(monitor: Monitor = randomQueryLevelMonitor()): Alert { Instant.now().truncatedTo(ChronoUnit.MILLIS), null, actionExecutionResults = actionExecutionResults, - clusters = clusters + clusters = clusters, ) } fun randomChainedAlert( workflow: Workflow = randomWorkflow(), - trigger: ChainedAlertTrigger = randomChainedAlertTrigger() -): Alert { - return Alert( + trigger: ChainedAlertTrigger = randomChainedAlertTrigger(), +): Alert = + Alert( startTime = Instant.now(), lastNotificationTime = Instant.now(), state = Alert.State.ACTIVE, @@ -579,14 +625,13 @@ fun randomChainedAlert( executionId = UUID.randomUUID().toString(), chainedAlertTrigger = trigger, workflow = workflow, - associatedAlertIds = listOf("a1") + associatedAlertIds = listOf("a1"), ) -} fun randomActionExecutionResult( actionId: String = UUIDs.base64UUID(), lastExecutionTime: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS), - throttledCount: Int = 0 + throttledCount: Int = 0, ) = ActionExecutionResult(actionId, lastExecutionTime, throttledCount) fun randomAlertWithAggregationResultBucket(monitor: Monitor = randomBucketLevelMonitor()): Alert { @@ -598,11 +643,12 @@ fun randomAlertWithAggregationResultBucket(monitor: Monitor = randomBucketLevelM Instant.now().truncatedTo(ChronoUnit.MILLIS), null, actionExecutionResults = actionExecutionResults, - aggregationResultBucket = AggregationResultBucket( - "parent_bucket_path_1", - listOf("bucket_key_1"), - mapOf("k1" to "val1", "k2" to "val2") - ) + aggregationResultBucket = + AggregationResultBucket( + "parent_bucket_path_1", + listOf("bucket_key_1"), + mapOf("k1" to "val1", "k2" to "val2"), + ), ) } @@ -613,22 +659,21 @@ fun randomFinding( monitorName: String = UUIDs.base64UUID(), index: String = UUIDs.base64UUID(), docLevelQueries: List = listOf(randomDocLevelQuery()), - timestamp: Instant = Instant.now() -): Finding { - return Finding( + timestamp: Instant = Instant.now(), +): Finding = + Finding( id = id, relatedDocIds = relatedDocIds, monitorId = monitorId, monitorName = monitorName, index = index, docLevelQueries = docLevelQueries, - timestamp = timestamp + timestamp = timestamp, ) -} fun randomCorrelationAlert( id: String, - state: Alert.State + state: Alert.State, ): CorrelationAlert { val correlatedFindingIds = listOf("finding1", "finding2") val correlationRuleId = "rule1" @@ -647,15 +692,26 @@ fun randomCorrelationAlert( val actionExecutionResults = listOf(randomActionExecutionResult()) return CorrelationAlert( - correlatedFindingIds, correlationRuleId, correlationRuleName, - id, version, schemaVersion, user, triggerName, state, - startTime, endTime, acknowledgedTime, errorMessage, severity, - actionExecutionResults + correlatedFindingIds, + correlationRuleId, + correlationRuleName, + id, + version, + schemaVersion, + user, + triggerName, + state, + startTime, + endTime, + acknowledgedTime, + errorMessage, + severity, + actionExecutionResults, ) } -fun createUnifiedAlertTemplateArgs(unifiedAlert: BaseAlert): Map { - return mapOf( +fun createUnifiedAlertTemplateArgs(unifiedAlert: BaseAlert): Map = + mapOf( BaseAlert.ALERT_ID_FIELD to unifiedAlert.id, BaseAlert.ALERT_VERSION_FIELD to unifiedAlert.version, BaseAlert.SCHEMA_VERSION_FIELD to unifiedAlert.schemaVersion, @@ -667,22 +723,20 @@ fun createUnifiedAlertTemplateArgs(unifiedAlert: BaseAlert): Map { BaseAlert.ACKNOWLEDGED_TIME_FIELD to unifiedAlert.acknowledgedTime, BaseAlert.ERROR_MESSAGE_FIELD to unifiedAlert.errorMessage, BaseAlert.SEVERITY_FIELD to unifiedAlert.severity, - BaseAlert.ACTION_EXECUTION_RESULTS_FIELD to unifiedAlert.actionExecutionResults + BaseAlert.ACTION_EXECUTION_RESULTS_FIELD to unifiedAlert.actionExecutionResults, ) -} fun createCorrelationAlertTemplateArgs(correlationAlert: CorrelationAlert): Map { val unifiedAlertTemplateArgs = createUnifiedAlertTemplateArgs(correlationAlert) - return unifiedAlertTemplateArgs + mapOf( - CorrelationAlert.CORRELATED_FINDING_IDS to correlationAlert.correlatedFindingIds, - CorrelationAlert.CORRELATION_RULE_ID to correlationAlert.correlationRuleId, - CorrelationAlert.CORRELATION_RULE_NAME to correlationAlert.correlationRuleName - ) + return unifiedAlertTemplateArgs + + mapOf( + CorrelationAlert.CORRELATED_FINDING_IDS to correlationAlert.correlatedFindingIds, + CorrelationAlert.CORRELATION_RULE_ID to correlationAlert.correlationRuleId, + CorrelationAlert.CORRELATION_RULE_NAME to correlationAlert.correlationRuleName, + ) } -fun randomInputRunResults(): InputRunResults { - return InputRunResults(listOf(), null) -} +fun randomInputRunResults(): InputRunResults = InputRunResults(listOf(), null) fun randomActionRunResult(): ActionRunResult { val map = mutableMapOf() @@ -694,7 +748,7 @@ fun randomActionRunResult(): ActionRunResult { map, false, Instant.now(), - null + null, ) } @@ -706,9 +760,10 @@ fun randomDocumentLevelTriggerRunResult(): DocumentLevelTriggerRunResult { "trigger-name", mutableListOf(UUIDs.randomBase64UUID().toString()), null, - mutableMapOf(Pair("alertId", map)) + mutableMapOf(Pair("alertId", map)), ) } + fun randomDocumentLevelMonitorRunResult(): MonitorRunResult { val triggerResults = mutableMapOf() val triggerRunResult = randomDocumentLevelTriggerRunResult() @@ -720,7 +775,7 @@ fun randomDocumentLevelMonitorRunResult(): MonitorRunResult> = mutableMapOf() actionResultsMap[aggBucket1.getBucketKeysHash()] = map @@ -749,9 +806,9 @@ fun randomBucketLevelTriggerRunResult(): BucketLevelTriggerRunResult { null, mapOf( aggBucket1.getBucketKeysHash() to aggBucket1, - aggBucket2.getBucketKeysHash() to aggBucket2 + aggBucket2.getBucketKeysHash() to aggBucket2, ), - actionResultsMap + actionResultsMap, ) } @@ -766,7 +823,7 @@ fun randomBucketLevelMonitorRunResult(): MonitorRunResult, - InputRunResults(), - mapOf("1" to randomDocumentLevelTriggerRunResult(), "2" to randomDocumentLevelTriggerRunResult()) - ) + val workflow = + DocLevelMonitorFanOutResponse( + "nodeid", + "eid", + "monitorId", + mapOf("index" to mapOf("1" to "1")) as MutableMap, + InputRunResults(), + mapOf("1" to randomDocumentLevelTriggerRunResult(), "2" to randomDocumentLevelTriggerRunResult()), + ) val out = BytesStreamOutput() workflow.writeTo(out) val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequestTests.kt index 58f61550..fa231911 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequestTests.kt @@ -10,21 +10,21 @@ import org.opensearch.commons.alerting.model.Table import org.opensearch.core.common.io.stream.StreamInput internal class GetAlertsRequestTests { - @Test fun `test get alerts request`() { val table = Table("asc", "sortString", null, 1, 0, "") - val req = GetAlertsRequest( - table = table, - severityLevel = "1", - alertState = "active", - monitorId = null, - alertIndex = null, - monitorIds = listOf("1", "2"), - alertIds = listOf("alert1", "alert2"), - workflowIds = listOf("w1", "w2") - ) + val req = + GetAlertsRequest( + table = table, + severityLevel = "1", + alertState = "active", + monitorId = null, + alertIndex = null, + monitorIds = listOf("1", "2"), + alertIds = listOf("alert1", "alert2"), + workflowIds = listOf("w1", "w2"), + ) assertNotNull(req) val out = BytesStreamOutput() diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsResponseTests.kt index 6a1cb877..8c0eca06 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsResponseTests.kt @@ -15,7 +15,6 @@ import java.time.Instant import java.util.Collections class GetAlertsResponseTests { - @Test fun `test get alerts response with no alerts`() { val req = GetAlertsResponse(Collections.emptyList(), 0) @@ -31,29 +30,30 @@ class GetAlertsResponseTests { @Test fun `test get alerts response with alerts`() { - val alert = Alert( - monitorId = "id", - monitorName = "name", - monitorVersion = Alert.NO_VERSION, - monitorUser = randomUser(), - triggerId = "triggerId", - triggerName = "triggerNamer", - state = Alert.State.ACKNOWLEDGED, - startTime = Instant.now(), - lastNotificationTime = null, - errorMessage = null, - errorHistory = emptyList(), - severity = "high", - actionExecutionResults = emptyList(), - schemaVersion = 0, - aggregationResultBucket = null, - findingIds = emptyList(), - relatedDocIds = emptyList(), - executionId = "executionId", - workflowId = "workflowId", - workflowName = "", - associatedAlertIds = emptyList() - ) + val alert = + Alert( + monitorId = "id", + monitorName = "name", + monitorVersion = Alert.NO_VERSION, + monitorUser = randomUser(), + triggerId = "triggerId", + triggerName = "triggerNamer", + state = Alert.State.ACKNOWLEDGED, + startTime = Instant.now(), + lastNotificationTime = null, + errorMessage = null, + errorHistory = emptyList(), + severity = "high", + actionExecutionResults = emptyList(), + schemaVersion = 0, + aggregationResultBucket = null, + findingIds = emptyList(), + relatedDocIds = emptyList(), + executionId = "executionId", + workflowId = "workflowId", + workflowName = "", + associatedAlertIds = emptyList(), + ) val req = GetAlertsResponse(listOf(alert), 1) assertNotNull(req) @@ -70,39 +70,41 @@ class GetAlertsResponseTests { @Test fun `test toXContent for get alerts response`() { val now = Instant.now() - val alert = Alert( - monitorId = "id", - monitorName = "name", - monitorVersion = Alert.NO_VERSION, - monitorUser = randomUser(), - triggerId = "triggerId", - triggerName = "triggerNamer", - state = Alert.State.ACKNOWLEDGED, - startTime = now, - lastNotificationTime = null, - errorMessage = null, - errorHistory = emptyList(), - severity = "high", - actionExecutionResults = emptyList(), - schemaVersion = 0, - aggregationResultBucket = null, - findingIds = emptyList(), - relatedDocIds = emptyList(), - executionId = "executionId", - workflowId = "wid", - workflowName = "", - associatedAlertIds = emptyList() - ) + val alert = + Alert( + monitorId = "id", + monitorName = "name", + monitorVersion = Alert.NO_VERSION, + monitorUser = randomUser(), + triggerId = "triggerId", + triggerName = "triggerNamer", + state = Alert.State.ACKNOWLEDGED, + startTime = now, + lastNotificationTime = null, + errorMessage = null, + errorHistory = emptyList(), + severity = "high", + actionExecutionResults = emptyList(), + schemaVersion = 0, + aggregationResultBucket = null, + findingIds = emptyList(), + relatedDocIds = emptyList(), + executionId = "executionId", + workflowId = "wid", + workflowName = "", + associatedAlertIds = emptyList(), + ) val req = GetAlertsResponse(listOf(alert), 1) var actualXContentString = req.toXContent(builder(), ToXContent.EMPTY_PARAMS).string() - val expectedXContentString = "{\"alerts\":[{\"id\":\"\",\"version\":-1,\"monitor_id\":\"id\",\"workflow_id\":\"wid\"," + - "\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":0,\"monitor_version\":-1," + - "\"monitor_name\":\"name\",\"execution_id\":\"executionId\",\"trigger_id\":\"triggerId\"," + - "\"trigger_name\":\"triggerNamer\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACKNOWLEDGED\"," + - "\"error_message\":null,\"alert_history\":[],\"severity\":\"high\",\"action_execution_results\":[]," + - "\"start_time\":${now.toEpochMilli()},\"last_notification_time\":null,\"end_time\":null," + - "\"acknowledged_time\":null}],\"totalAlerts\":1}" + val expectedXContentString = + "{\"alerts\":[{\"id\":\"\",\"version\":-1,\"monitor_id\":\"id\",\"workflow_id\":\"wid\"," + + "\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":0,\"monitor_version\":-1," + + "\"monitor_name\":\"name\",\"execution_id\":\"executionId\",\"trigger_id\":\"triggerId\"," + + "\"trigger_name\":\"triggerNamer\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACKNOWLEDGED\"," + + "\"error_message\":null,\"alert_history\":[],\"severity\":\"high\",\"action_execution_results\":[]," + + "\"start_time\":${now.toEpochMilli()},\"last_notification_time\":null,\"end_time\":null," + + "\"acknowledged_time\":null}],\"totalAlerts\":1}" assertEquals(expectedXContentString, actualXContentString) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequestTests.kt index 238837cc..c6d66161 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequestTests.kt @@ -11,7 +11,6 @@ import org.opensearch.core.common.io.stream.StreamInput import org.opensearch.index.query.QueryBuilders internal class GetFindingsRequestTests { - @Test fun `test get findings request`() { val table = Table("asc", "sortString", null, 1, 0, "") diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponseTests.kt index 0c30b640..b1c196d5 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponseTests.kt @@ -12,20 +12,20 @@ import org.opensearch.core.rest.RestStatus import java.time.Instant internal class GetFindingsResponseTests { - @Test fun `test get findings response`() { // Alerting GetFindingsResponse mock #1 - val finding1 = Finding( - "1", - listOf("doc1", "doc2", "doc3"), - listOf("doc1", "doc2", "doc3"), - "monitor_id1", - "monitor_name1", - "test_index1", - listOf(DocLevelQuery("1", "myQuery", listOf(), "fieldA:valABC", listOf())), - Instant.now() - ) + val finding1 = + Finding( + "1", + listOf("doc1", "doc2", "doc3"), + listOf("doc1", "doc2", "doc3"), + "monitor_id1", + "monitor_name1", + "test_index1", + listOf(DocLevelQuery("1", "myQuery", listOf(), "fieldA:valABC", listOf())), + Instant.now(), + ) val findingDocument1 = FindingDocument("test_index1", "doc1", true, "document 1 payload") val findingDocument2 = FindingDocument("test_index1", "doc2", true, "document 2 payload") val findingDocument3 = FindingDocument("test_index1", "doc3", true, "document 3 payload") @@ -35,16 +35,17 @@ internal class GetFindingsResponseTests { // Alerting GetFindingsResponse mock #2 // Alerting GetFindingsResponse mock #2 - val finding2 = Finding( - "1", - listOf("doc21", "doc22"), - listOf("doc21", "doc22"), - "monitor_id2", - "monitor_name2", - "test_index2", - listOf(DocLevelQuery("1", "myQuery", listOf(), "fieldA:valABC", listOf())), - Instant.now() - ) + val finding2 = + Finding( + "1", + listOf("doc21", "doc22"), + listOf("doc21", "doc22"), + "monitor_id2", + "monitor_name2", + "test_index2", + listOf(DocLevelQuery("1", "myQuery", listOf(), "fieldA:valABC", listOf())), + Instant.now(), + ) val findingDocument21 = FindingDocument("test_index2", "doc21", true, "document 21 payload") val findingDocument22 = FindingDocument("test_index2", "doc22", true, "document 22 payload") diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequestTests.kt index 7670650e..9567c439 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequestTests.kt @@ -10,9 +10,10 @@ import org.opensearch.core.common.io.stream.StreamInput import org.opensearch.rest.RestRequest import org.opensearch.search.fetch.subphase.FetchSourceContext import org.opensearch.test.OpenSearchTestCase +import kotlin.test.Test class GetMonitorRequestTests : OpenSearchTestCase() { - + @Test fun `test get monitor request`() { val req = GetMonitorRequest("1234", 1L, RestRequest.Method.GET, FetchSourceContext.FETCH_SOURCE) assertNotNull(req) @@ -27,6 +28,7 @@ class GetMonitorRequestTests : OpenSearchTestCase() { assertEquals(FetchSourceContext.FETCH_SOURCE, newReq.srcContext) } + @Test fun `test get monitor request without src context`() { val req = GetMonitorRequest("1234", 1L, RestRequest.Method.GET, null) assertNotNull(req) @@ -41,6 +43,7 @@ class GetMonitorRequestTests : OpenSearchTestCase() { assertEquals(null, newReq.srcContext) } + @Test fun `test head monitor request`() { val req = GetMonitorRequest("1234", 2L, RestRequest.Method.HEAD, FetchSourceContext.FETCH_SOURCE) assertNotNull(req) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponseTests.kt index eb3f08e4..338ec986 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponseTests.kt @@ -13,9 +13,10 @@ import org.opensearch.core.common.io.stream.StreamInput import org.opensearch.test.OpenSearchTestCase import java.time.Instant import java.time.ZoneId +import kotlin.test.Test class GetMonitorResponseTests : OpenSearchTestCase() { - + @Test fun `test get monitor response`() { val req = GetMonitorResponse("1234", 1L, 2L, 0L, null, null) assertNotNull(req) @@ -29,26 +30,28 @@ class GetMonitorResponseTests : OpenSearchTestCase() { assertEquals(null, newReq.monitor) } + @Test fun `test get monitor response with monitor`() { val cronExpression = "31 * * * *" // Run at minute 31. val testInstance = Instant.ofEpochSecond(1538164858L) val cronSchedule = CronSchedule(cronExpression, ZoneId.of("Asia/Kolkata"), testInstance) - val monitor = Monitor( - id = "123", - version = 0L, - name = "test-monitor", - enabled = true, - schedule = cronSchedule, - lastUpdateTime = Instant.now(), - enabledTime = Instant.now(), - monitorType = Monitor.MonitorType.QUERY_LEVEL_MONITOR.value, - user = randomUser(), - schemaVersion = 0, - inputs = mutableListOf(), - triggers = mutableListOf(), - uiMetadata = mutableMapOf() - ) + val monitor = + Monitor( + id = "123", + version = 0L, + name = "test-monitor", + enabled = true, + schedule = cronSchedule, + lastUpdateTime = Instant.now(), + enabledTime = Instant.now(), + monitorType = Monitor.MonitorType.QUERY_LEVEL_MONITOR.value, + user = randomUser(), + schemaVersion = 0, + inputs = mutableListOf(), + triggers = mutableListOf(), + uiMetadata = mutableMapOf(), + ) val req = GetMonitorResponse("1234", 1L, 2L, 0L, monitor, null) assertNotNull(req) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequestTests.kt index 425151cd..baae5540 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequestTests.kt @@ -10,22 +10,22 @@ import org.opensearch.commons.alerting.model.Table import org.opensearch.core.common.io.stream.StreamInput internal class GetWorkflowAlertsRequestTests { - @Test fun `test get alerts request`() { val table = Table("asc", "sortString", null, 1, 0, "") - val req = GetWorkflowAlertsRequest( - table = table, - severityLevel = "1", - alertState = "active", - getAssociatedAlerts = true, - workflowIds = listOf("w1", "w2"), - alertIds = emptyList(), - alertIndex = null, - associatedAlertsIndex = null, - monitorIds = emptyList() - ) + val req = + GetWorkflowAlertsRequest( + table = table, + severityLevel = "1", + alertState = "active", + getAssociatedAlerts = true, + workflowIds = listOf("w1", "w2"), + alertIds = emptyList(), + alertIndex = null, + associatedAlertsIndex = null, + monitorIds = emptyList(), + ) assertNotNull(req) val out = BytesStreamOutput() @@ -49,17 +49,18 @@ internal class GetWorkflowAlertsRequestTests { fun `test get alerts request with custom alerts and associated alerts indices`() { val table = Table("asc", "sortString", null, 1, 0, "") - val req = GetWorkflowAlertsRequest( - table = table, - severityLevel = "1", - alertState = "active", - getAssociatedAlerts = true, - workflowIds = listOf("w1", "w2"), - alertIds = emptyList(), - alertIndex = "alertIndex", - associatedAlertsIndex = "associatedAlertsIndex", - monitorIds = emptyList() - ) + val req = + GetWorkflowAlertsRequest( + table = table, + severityLevel = "1", + alertState = "active", + getAssociatedAlerts = true, + workflowIds = listOf("w1", "w2"), + alertIds = emptyList(), + alertIndex = "alertIndex", + associatedAlertsIndex = "associatedAlertsIndex", + monitorIds = emptyList(), + ) assertNotNull(req) val out = BytesStreamOutput() @@ -83,16 +84,17 @@ internal class GetWorkflowAlertsRequestTests { fun `test validate returns null`() { val table = Table("asc", "sortString", null, 1, 0, "") - val req = GetWorkflowAlertsRequest( - table = table, - severityLevel = "1", - alertState = "active", - getAssociatedAlerts = true, - workflowIds = listOf("w1, w2"), - alertIds = emptyList(), - alertIndex = null, - associatedAlertsIndex = null - ) + val req = + GetWorkflowAlertsRequest( + table = table, + severityLevel = "1", + alertState = "active", + getAssociatedAlerts = true, + workflowIds = listOf("w1, w2"), + alertIds = emptyList(), + alertIndex = null, + associatedAlertsIndex = null, + ) assertNotNull(req) assertNull(req.validate()) } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponseTests.kt index 947fead8..af0cc514 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponseTests.kt @@ -17,7 +17,6 @@ import java.time.Instant import java.util.Collections class GetWorkflowAlertsResponseTests { - @Test fun `test get alerts response with no alerts`() { val req = GetWorkflowAlertsResponse(Collections.emptyList(), emptyList(), 0) @@ -56,29 +55,30 @@ class GetWorkflowAlertsResponseTests { @Test fun `test toXContent for get alerts response`() { - val alert = Alert( - monitorId = "id", - monitorName = "name", - monitorVersion = Alert.NO_VERSION, - monitorUser = randomUser(), - triggerId = "triggerId", - triggerName = "triggerNamer", - state = Alert.State.ACKNOWLEDGED, - startTime = Instant.ofEpochMilli(1688591410974), - lastNotificationTime = null, - errorMessage = null, - errorHistory = emptyList(), - severity = "high", - actionExecutionResults = emptyList(), - schemaVersion = 0, - aggregationResultBucket = null, - findingIds = emptyList(), - relatedDocIds = emptyList(), - executionId = "executionId", - workflowId = "wid", - workflowName = "", - associatedAlertIds = emptyList() - ) + val alert = + Alert( + monitorId = "id", + monitorName = "name", + monitorVersion = Alert.NO_VERSION, + monitorUser = randomUser(), + triggerId = "triggerId", + triggerName = "triggerNamer", + state = Alert.State.ACKNOWLEDGED, + startTime = Instant.ofEpochMilli(1688591410974), + lastNotificationTime = null, + errorMessage = null, + errorHistory = emptyList(), + severity = "high", + actionExecutionResults = emptyList(), + schemaVersion = 0, + aggregationResultBucket = null, + findingIds = emptyList(), + relatedDocIds = emptyList(), + executionId = "executionId", + workflowId = "wid", + workflowName = "", + associatedAlertIds = emptyList(), + ) val req = GetWorkflowAlertsResponse(listOf(alert), emptyList(), 1) var actualXContentString = req.toXContent(builder(), ToXContent.EMPTY_PARAMS).string() diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowRequestTests.kt index e7c4be06..3998ee4a 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowRequestTests.kt @@ -7,7 +7,6 @@ import org.opensearch.core.common.io.stream.StreamInput import org.opensearch.rest.RestRequest class GetWorkflowRequestTests { - @Test fun testGetWorkflowRequest() { val request = GetWorkflowRequest("w1", RestRequest.Method.GET) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponseTests.kt index e21bb430..a2874ff7 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponseTests.kt @@ -15,18 +15,18 @@ import java.time.Instant import java.time.temporal.ChronoUnit class GetWorkflowResponseTests { - @Test fun testGetWorkflowResponse() { val workflow = randomWorkflow(auditDelegateMonitorAlerts = false) - val response = GetWorkflowResponse( - id = "id", - version = 1, - seqNo = 1, - primaryTerm = 1, - status = RestStatus.OK, - workflow = workflow - ) + val response = + GetWorkflowResponse( + id = "id", + version = 1, + seqNo = 1, + primaryTerm = 1, + status = RestStatus.OK, + workflow = workflow, + ) val out = BytesStreamOutput() response.writeTo(out) val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes) @@ -39,29 +39,37 @@ class GetWorkflowResponseTests { @Test fun testGetWorkflowResponseWhereAuditDelegateMonitorAlertsFlagIsNotSet() { - val workflow = Workflow( - id = "", - version = Workflow.NO_VERSION, - name = "test", - enabled = true, - schemaVersion = 2, - schedule = IntervalSchedule(1, ChronoUnit.MINUTES), - lastUpdateTime = Instant.now(), - enabledTime = Instant.now(), - workflowType = Workflow.WorkflowType.COMPOSITE, - user = randomUser(), - inputs = listOf(CompositeInput(org.opensearch.commons.alerting.model.Sequence(listOf(randomDelegate())))), - owner = "", - triggers = listOf() - ) - val response = GetWorkflowResponse( - id = "id", - version = 1, - seqNo = 1, - primaryTerm = 1, - status = RestStatus.OK, - workflow = workflow - ) + val workflow = + Workflow( + id = "", + version = Workflow.NO_VERSION, + name = "test", + enabled = true, + schemaVersion = 2, + schedule = IntervalSchedule(1, ChronoUnit.MINUTES), + lastUpdateTime = Instant.now(), + enabledTime = Instant.now(), + workflowType = Workflow.WorkflowType.COMPOSITE, + user = randomUser(), + inputs = + listOf( + CompositeInput( + org.opensearch.commons.alerting.model + .Sequence(listOf(randomDelegate())), + ), + ), + owner = "", + triggers = listOf(), + ) + val response = + GetWorkflowResponse( + id = "id", + version = 1, + seqNo = 1, + primaryTerm = 1, + status = RestStatus.OK, + workflow = workflow, + ) val out = BytesStreamOutput() response.writeTo(out) val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexCommentResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexCommentResponseTests.kt index 57e4801b..bd4425e1 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexCommentResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexCommentResponseTests.kt @@ -11,15 +11,16 @@ import java.time.Instant class IndexCommentResponseTests { @Test fun `test index comment response with comment`() { - val comment = Comment( - "123", - "alert", - "456", - "comment", - Instant.now(), - Instant.now(), - randomUser() - ) + val comment = + Comment( + "123", + "alert", + "456", + "comment", + Instant.now(), + Instant.now(), + randomUser(), + ) val req = IndexCommentResponse("1234", 1L, 2L, comment) Assertions.assertNotNull(req) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequestTests.kt index f3f54e10..e7f0391e 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequestTests.kt @@ -21,17 +21,17 @@ import org.opensearch.search.SearchModule import org.opensearch.search.builder.SearchSourceBuilder class IndexMonitorRequestTests { - @Test fun `test index monitor post request`() { - val req = IndexMonitorRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - randomQueryLevelMonitor().copy(inputs = listOf(SearchInput(emptyList(), SearchSourceBuilder()))) - ) + val req = + IndexMonitorRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + randomQueryLevelMonitor().copy(inputs = listOf(SearchInput(emptyList(), SearchSourceBuilder()))), + ) Assertions.assertNotNull(req) val out = BytesStreamOutput() @@ -47,14 +47,15 @@ class IndexMonitorRequestTests { @Test fun `test index bucket monitor post request`() { - val req = IndexMonitorRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - randomBucketLevelMonitor() - ) + val req = + IndexMonitorRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + randomBucketLevelMonitor(), + ) Assertions.assertNotNull(req) val out = BytesStreamOutput() @@ -71,23 +72,25 @@ class IndexMonitorRequestTests { @Test fun `Index bucket monitor serialize and deserialize transport object should be equal`() { - val bucketLevelMonitorRequest = IndexMonitorRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - randomBucketLevelMonitor() - ) + val bucketLevelMonitorRequest = + IndexMonitorRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + randomBucketLevelMonitor(), + ) Assertions.assertThrows(UnsupportedOperationException::class.java) { recreateObject(bucketLevelMonitorRequest) { IndexMonitorRequest(it) } } - val recreatedObject = recreateObject( - bucketLevelMonitorRequest, - NamedWriteableRegistry(SearchModule(Settings.EMPTY, emptyList()).namedWriteables) - ) { IndexMonitorRequest(it) } + val recreatedObject = + recreateObject( + bucketLevelMonitorRequest, + NamedWriteableRegistry(SearchModule(Settings.EMPTY, emptyList()).namedWriteables), + ) { IndexMonitorRequest(it) } Assertions.assertEquals(bucketLevelMonitorRequest.monitorId, recreatedObject.monitorId) Assertions.assertEquals(bucketLevelMonitorRequest.seqNo, recreatedObject.seqNo) Assertions.assertEquals(bucketLevelMonitorRequest.primaryTerm, recreatedObject.primaryTerm) @@ -98,14 +101,15 @@ class IndexMonitorRequestTests { @Test fun `test index monitor put request`() { - val req = IndexMonitorRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomQueryLevelMonitor().copy(inputs = listOf(SearchInput(emptyList(), SearchSourceBuilder()))) - ) + val req = + IndexMonitorRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomQueryLevelMonitor().copy(inputs = listOf(SearchInput(emptyList(), SearchSourceBuilder()))), + ) Assertions.assertNotNull(req) val out = BytesStreamOutput() @@ -121,18 +125,20 @@ class IndexMonitorRequestTests { @Test fun `test doc level monitor with valid index name`() { - val monitor = randomDocumentLevelMonitor().copy( - inputs = listOf(DocLevelMonitorInput(indices = listOf("valid-index"), queries = emptyList())), - triggers = emptyList() - ) - val req = IndexMonitorRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - monitor - ) + val monitor = + randomDocumentLevelMonitor().copy( + inputs = listOf(DocLevelMonitorInput(indices = listOf("valid-index"), queries = emptyList())), + triggers = emptyList(), + ) + val req = + IndexMonitorRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + monitor, + ) val validationException = req.validate() Assertions.assertNull(validationException) @@ -140,41 +146,45 @@ class IndexMonitorRequestTests { @Test fun `test doc level monitor with wildcard index pattern`() { - val monitor = randomDocumentLevelMonitor().copy( - inputs = listOf(DocLevelMonitorInput(indices = listOf("valid, test*", "test*"), queries = emptyList())) - ) - val req = IndexMonitorRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - monitor - ) + val monitor = + randomDocumentLevelMonitor().copy( + inputs = listOf(DocLevelMonitorInput(indices = listOf("valid, test*", "test*"), queries = emptyList())), + ) + val req = + IndexMonitorRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + monitor, + ) val validationException = req.validate() Assertions.assertNotNull(validationException) Assertions.assertTrue(validationException is ActionRequestValidationException) Assertions.assertTrue( validationException!!.validationErrors().contains("Index patterns are not supported for doc level monitors.") - ?: false + ?: false, ) } @Test fun `test remote monitor with wildcard index pattern`() { - val monitor = randomDocumentLevelMonitor().copy( - monitorType = "ti_doc_level_monitor", - inputs = listOf(DocLevelMonitorInput(indices = listOf("valid, test*", "test*"), queries = emptyList())) - ) - val req = IndexMonitorRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - monitor - ) + val monitor = + randomDocumentLevelMonitor().copy( + monitorType = "ti_doc_level_monitor", + inputs = listOf(DocLevelMonitorInput(indices = listOf("valid, test*", "test*"), queries = emptyList())), + ) + val req = + IndexMonitorRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + monitor, + ) val validationException = req.validate() Assertions.assertNull(validationException) @@ -182,64 +192,70 @@ class IndexMonitorRequestTests { @Test fun `test doc level monitor with regex index pattern`() { - val monitor = randomDocumentLevelMonitor().copy( - inputs = listOf(DocLevelMonitorInput(indices = listOf("test[0-9]+"), queries = emptyList())), - triggers = emptyList() - ) - val req = IndexMonitorRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - monitor - ) + val monitor = + randomDocumentLevelMonitor().copy( + inputs = listOf(DocLevelMonitorInput(indices = listOf("test[0-9]+"), queries = emptyList())), + triggers = emptyList(), + ) + val req = + IndexMonitorRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + monitor, + ) val validationException = req.validate() Assertions.assertNotNull(validationException) Assertions.assertTrue(validationException is ActionRequestValidationException) Assertions.assertTrue( - validationException!!.validationErrors().contains("Index patterns are not supported for doc level monitors.") + validationException!!.validationErrors().contains("Index patterns are not supported for doc level monitors."), ) } @Test fun `test doc level monitor with date math index pattern`() { - val monitor = randomDocumentLevelMonitor().copy( - inputs = listOf(DocLevelMonitorInput(indices = listOf(""), queries = emptyList())), - triggers = emptyList() - ) - val req = IndexMonitorRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - monitor - ) + val monitor = + randomDocumentLevelMonitor().copy( + inputs = listOf(DocLevelMonitorInput(indices = listOf(""), queries = emptyList())), + triggers = emptyList(), + ) + val req = + IndexMonitorRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + monitor, + ) val validationException = req.validate() Assertions.assertNotNull(validationException) Assertions.assertTrue(validationException is ActionRequestValidationException) Assertions.assertTrue( - validationException!!.validationErrors().contains("Index patterns are not supported for doc level monitors.") + validationException!!.validationErrors().contains("Index patterns are not supported for doc level monitors."), ) } @Test fun `test non-doc level monitor with index pattern`() { - val monitor = randomQueryLevelMonitor().copy( - inputs = listOf(SearchInput(listOf("test*"), SearchSourceBuilder())), - monitorType = Monitor.MonitorType.QUERY_LEVEL_MONITOR.name - ) - val req = IndexMonitorRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - monitor - ) + val monitor = + randomQueryLevelMonitor().copy( + inputs = listOf(SearchInput(listOf("test*"), SearchSourceBuilder())), + monitorType = Monitor.MonitorType.QUERY_LEVEL_MONITOR.name, + ) + val req = + IndexMonitorRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + monitor, + ) val validationException = req.validate() Assertions.assertNull(validationException) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorResponseTests.kt index ca3afa3e..75d600cd 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorResponseTests.kt @@ -11,28 +11,28 @@ import java.time.Instant import java.time.ZoneId class IndexMonitorResponseTests { - @Test fun `test index monitor response with monitor`() { val cronExpression = "31 * * * *" // Run at minute 31. val testInstance = Instant.ofEpochSecond(1538164858L) val cronSchedule = CronSchedule(cronExpression, ZoneId.of("Asia/Kolkata"), testInstance) - val monitor = Monitor( - id = "123", - version = 0L, - name = "test-monitor", - enabled = true, - schedule = cronSchedule, - lastUpdateTime = Instant.now(), - enabledTime = Instant.now(), - monitorType = Monitor.MonitorType.QUERY_LEVEL_MONITOR.value, - user = randomUser(), - schemaVersion = 0, - inputs = mutableListOf(), - triggers = mutableListOf(), - uiMetadata = mutableMapOf() - ) + val monitor = + Monitor( + id = "123", + version = 0L, + name = "test-monitor", + enabled = true, + schedule = cronSchedule, + lastUpdateTime = Instant.now(), + enabledTime = Instant.now(), + monitorType = Monitor.MonitorType.QUERY_LEVEL_MONITOR.value, + user = randomUser(), + schemaVersion = 0, + inputs = mutableListOf(), + triggers = mutableListOf(), + uiMetadata = mutableMapOf(), + ) val req = IndexMonitorResponse("1234", 1L, 2L, 0L, monitor) Assertions.assertNotNull(req) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequestTests.kt index 600ac506..78ea1b12 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequestTests.kt @@ -26,17 +26,17 @@ import kotlin.test.assertNull import kotlin.test.assertTrue class IndexWorkflowRequestTests { - @Test fun `test index workflow post request`() { - val req = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - randomWorkflow(auditDelegateMonitorAlerts = false) - ) + val req = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + randomWorkflow(auditDelegateMonitorAlerts = false), + ) Assertions.assertNotNull(req) val out = BytesStreamOutput() @@ -53,14 +53,15 @@ class IndexWorkflowRequestTests { @Test fun `test index composite workflow post request`() { - val req = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - randomWorkflow() - ) + val req = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + randomWorkflow(), + ) Assertions.assertNotNull(req) val out = BytesStreamOutput() @@ -77,19 +78,21 @@ class IndexWorkflowRequestTests { @Test fun `Index composite workflow serialize and deserialize transport object should be equal`() { - val compositeWorkflowRequest = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.POST, - randomWorkflow() - ) + val compositeWorkflowRequest = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, + randomWorkflow(), + ) - val recreatedObject = recreateObject( - compositeWorkflowRequest, - NamedWriteableRegistry(SearchModule(Settings.EMPTY, emptyList()).namedWriteables) - ) { IndexWorkflowRequest(it) } + val recreatedObject = + recreateObject( + compositeWorkflowRequest, + NamedWriteableRegistry(SearchModule(Settings.EMPTY, emptyList()).namedWriteables), + ) { IndexWorkflowRequest(it) } Assertions.assertEquals(compositeWorkflowRequest.workflowId, recreatedObject.workflowId) Assertions.assertEquals(compositeWorkflowRequest.seqNo, recreatedObject.seqNo) Assertions.assertEquals(compositeWorkflowRequest.primaryTerm, recreatedObject.primaryTerm) @@ -100,14 +103,15 @@ class IndexWorkflowRequestTests { @Test fun `test index workflow put request`() { - val req = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomWorkflow() - ) + val req = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomWorkflow(), + ) Assertions.assertNotNull(req) val out = BytesStreamOutput() @@ -123,85 +127,93 @@ class IndexWorkflowRequestTests { @Test fun `test validate`() { - val req = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomWorkflow(monitorIds = emptyList()) - ) + val req = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomWorkflow(monitorIds = emptyList()), + ) Assertions.assertNotNull(req) // Empty input list var validate = req.validate() Assert.assertTrue(validate != null) Assert.assertTrue(validate!!.message!!.contains("Delegates list can not be empty.;")) // Duplicate delegate - val req1 = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomWorkflow(monitorIds = listOf("1L", "1L", "2L")) - ) + val req1 = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomWorkflow(monitorIds = listOf("1L", "1L", "2L")), + ) validate = req1.validate() Assert.assertTrue(validate != null) Assert.assertTrue(validate!!.message!!.contains("Duplicate delegates not allowed")) // Sequence not correct - var delegates = listOf( - Delegate(1, "monitor-1"), - Delegate(1, "monitor-2"), - Delegate(2, "monitor-3") - ) - val req2 = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomWorkflowWithDelegates( - input = listOf(CompositeInput(Sequence(delegates = delegates))) + var delegates = + listOf( + Delegate(1, "monitor-1"), + Delegate(1, "monitor-2"), + Delegate(2, "monitor-3"), + ) + val req2 = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomWorkflowWithDelegates( + input = listOf(CompositeInput(Sequence(delegates = delegates))), + ), ) - ) validate = req2.validate() Assert.assertTrue(validate != null) Assert.assertTrue(validate!!.message!!.contains("Sequence ordering of delegate monitor shouldn't contain duplicate order values")) // Chained finding sequence not correct - delegates = listOf( - Delegate(1, "monitor-1"), - Delegate(2, "monitor-2", ChainedMonitorFindings("monitor-1")), - Delegate(3, "monitor-3", ChainedMonitorFindings("monitor-x")) - ) - val req3 = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomWorkflowWithDelegates( - input = listOf(CompositeInput(Sequence(delegates = delegates))) + delegates = + listOf( + Delegate(1, "monitor-1"), + Delegate(2, "monitor-2", ChainedMonitorFindings("monitor-1")), + Delegate(3, "monitor-3", ChainedMonitorFindings("monitor-x")), + ) + val req3 = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomWorkflowWithDelegates( + input = listOf(CompositeInput(Sequence(delegates = delegates))), + ), ) - ) validate = req3.validate() Assert.assertTrue(validate != null) Assert.assertTrue(validate!!.message!!.contains("Chained Findings Monitor monitor-x doesn't exist in sequence")) // Order not correct - delegates = listOf( - Delegate(1, "monitor-1"), - Delegate(3, "monitor-2", ChainedMonitorFindings("monitor-1")), - Delegate(2, "monitor-3", ChainedMonitorFindings("monitor-2")) - ) - val req4 = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomWorkflowWithDelegates( - input = listOf(CompositeInput(Sequence(delegates = delegates))) + delegates = + listOf( + Delegate(1, "monitor-1"), + Delegate(3, "monitor-2", ChainedMonitorFindings("monitor-1")), + Delegate(2, "monitor-3", ChainedMonitorFindings("monitor-2")), + ) + val req4 = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomWorkflowWithDelegates( + input = listOf(CompositeInput(Sequence(delegates = delegates))), + ), ) - ) validate = req4.validate() Assert.assertTrue(validate != null) Assert.assertTrue(validate!!.message!!.contains("Chained Findings Monitor monitor-2 should be executed before monitor monitor-3")) @@ -210,55 +222,59 @@ class IndexWorkflowRequestTests { for (i in 0..25) { monitorsIds.add(UUID.randomUUID().toString()) } - val req5 = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomWorkflow( - monitorIds = monitorsIds + val req5 = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomWorkflow( + monitorIds = monitorsIds, + ), ) - ) validate = req5.validate() Assert.assertTrue(validate != null) Assert.assertTrue(validate!!.message!!.contains("Delegates list can not be larger then 25.")) // Input list empty - val req6 = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomWorkflowWithDelegates( - input = emptyList() + val req6 = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomWorkflowWithDelegates( + input = emptyList(), + ), ) - ) validate = req6.validate() Assert.assertTrue(validate != null) Assert.assertTrue(validate!!.message!!.contains("Input list can not be empty.")) // Input list multiple elements - delegates = listOf( - Delegate(1, "monitor-1") - ) + delegates = + listOf( + Delegate(1, "monitor-1"), + ) // Chained finding list of monitors valid - delegates = listOf( - Delegate(1, "monitor-1"), - Delegate(2, "monitor-2"), - Delegate(3, "monitor-3", ChainedMonitorFindings(null, listOf("monitor-1", "monitor-2"))) - - ) - val req7 = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomWorkflowWithDelegates( - input = listOf(CompositeInput(Sequence(delegates = delegates))) + delegates = + listOf( + Delegate(1, "monitor-1"), + Delegate(2, "monitor-2"), + Delegate(3, "monitor-3", ChainedMonitorFindings(null, listOf("monitor-1", "monitor-2"))), + ) + val req7 = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomWorkflowWithDelegates( + input = listOf(CompositeInput(Sequence(delegates = delegates))), + ), ) - ) assertNull(req7.validate()) try { IndexWorkflowRequest( @@ -268,8 +284,8 @@ class IndexWorkflowRequestTests { WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, randomWorkflowWithDelegates( - input = listOf(CompositeInput(Sequence(delegates = delegates)), CompositeInput(Sequence(delegates = delegates))) - ) + input = listOf(CompositeInput(Sequence(delegates = delegates)), CompositeInput(Sequence(delegates = delegates))), + ), ) } catch (ex: Exception) { Assert.assertTrue(ex is IllegalArgumentException) @@ -277,22 +293,23 @@ class IndexWorkflowRequestTests { } // Chained finding list of monitors invalid order and old field null - delegates = listOf( - Delegate(1, "monitor-1"), - Delegate(3, "monitor-2"), - Delegate(2, "monitor-3", ChainedMonitorFindings(null, listOf("monitor-1", "monitor-2"))) - - ) - val req8 = IndexWorkflowRequest( - "1234", - 1L, - 2L, - WriteRequest.RefreshPolicy.IMMEDIATE, - RestRequest.Method.PUT, - randomWorkflowWithDelegates( - input = listOf(CompositeInput(Sequence(delegates = delegates))) + delegates = + listOf( + Delegate(1, "monitor-1"), + Delegate(3, "monitor-2"), + Delegate(2, "monitor-3", ChainedMonitorFindings(null, listOf("monitor-1", "monitor-2"))), + ) + val req8 = + IndexWorkflowRequest( + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, + randomWorkflowWithDelegates( + input = listOf(CompositeInput(Sequence(delegates = delegates))), + ), ) - ) assertNotNull(req8.validate()) assertTrue(req8.validate()!!.message!!.contains("should be executed before monitor")) } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowResponseTests.kt index 6594010e..b7208db4 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowResponseTests.kt @@ -13,27 +13,27 @@ import java.time.Instant import java.time.ZoneId class IndexWorkflowResponseTests { - @Test fun `test index workflow response with workflow`() { val cronExpression = "31 * * * *" // Run at minute 31. val testInstance = Instant.ofEpochSecond(1538164858L) val cronSchedule = CronSchedule(cronExpression, ZoneId.of("Asia/Kolkata"), testInstance) - val workflow = Workflow( - id = "123", - version = 0L, - name = "test-workflow", - enabled = true, - schedule = cronSchedule, - lastUpdateTime = Instant.now(), - enabledTime = Instant.now(), - workflowType = Workflow.WorkflowType.COMPOSITE, - user = randomUser(), - schemaVersion = 0, - inputs = mutableListOf(), - triggers = listOf(randomChainedAlertTrigger()) - ) + val workflow = + Workflow( + id = "123", + version = 0L, + name = "test-workflow", + enabled = true, + schedule = cronSchedule, + lastUpdateTime = Instant.now(), + enabledTime = Instant.now(), + workflowType = Workflow.WorkflowType.COMPOSITE, + user = randomUser(), + schemaVersion = 0, + inputs = mutableListOf(), + triggers = listOf(randomChainedAlertTrigger()), + ) val req = IndexWorkflowResponse("1234", 1L, 2L, 0L, workflow) Assertions.assertNotNull(req) @@ -45,17 +45,38 @@ class IndexWorkflowResponseTests { Assertions.assertEquals(1L, newReq.version) Assertions.assertNotNull(newReq.workflow) Assertions.assertEquals(newReq.workflow.triggers.size, 1) - Assertions.assertEquals(newReq.workflow.triggers.get(0).name, req.workflow.triggers.get(0).name) - Assertions.assertEquals(newReq.workflow.triggers.get(0).id, req.workflow.triggers.get(0).id) - Assertions.assertEquals(newReq.workflow.triggers.get(0).severity, req.workflow.triggers.get(0).severity) + Assertions.assertEquals( + newReq.workflow.triggers + .get(0) + .name, + req.workflow.triggers + .get(0) + .name, + ) + Assertions.assertEquals( + newReq.workflow.triggers + .get(0) + .id, + req.workflow.triggers + .get(0) + .id, + ) + Assertions.assertEquals( + newReq.workflow.triggers + .get(0) + .severity, + req.workflow.triggers + .get(0) + .severity, + ) Assertions.assertEquals( (newReq.workflow.triggers.get(0) as ChainedAlertTrigger).condition.idOrCode, - (req.workflow.triggers.get(0) as ChainedAlertTrigger).condition.idOrCode + (req.workflow.triggers.get(0) as ChainedAlertTrigger).condition.idOrCode, ) Assertions.assertEquals( (newReq.workflow.triggers.get(0) as ChainedAlertTrigger).condition.lang, - (req.workflow.triggers.get(0) as ChainedAlertTrigger).condition.lang + (req.workflow.triggers.get(0) as ChainedAlertTrigger).condition.lang, ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequestTests.kt index bbfc7793..dd16a011 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequestTests.kt @@ -8,7 +8,6 @@ import org.opensearch.commons.alerting.randomFinding import org.opensearch.core.common.io.stream.StreamInput class PublishFindingsRequestTests { - @Test fun `test delete monitor request`() { val finding = randomFinding() diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequestTests.kt index 596d16c4..babcc67c 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequestTests.kt @@ -8,8 +8,10 @@ import org.opensearch.search.builder.SearchSourceBuilder import org.opensearch.test.OpenSearchTestCase import org.opensearch.test.rest.OpenSearchRestTestCase import java.util.concurrent.TimeUnit +import kotlin.test.Test class SearchCommentRequestTests : OpenSearchTestCase() { + @Test fun `test search comments request`() { val searchSourceBuilder = SearchSourceBuilder().from(0).size(100).timeout(TimeValue(60, TimeUnit.SECONDS)) val searchRequest = SearchRequest().indices(OpenSearchRestTestCase.randomAlphaOfLength(10)).source(searchSourceBuilder) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt index 169814ea..0ff1d23c 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt @@ -13,9 +13,10 @@ import org.opensearch.search.builder.SearchSourceBuilder import org.opensearch.test.OpenSearchTestCase import org.opensearch.test.rest.OpenSearchRestTestCase import java.util.concurrent.TimeUnit +import kotlin.test.Test class SearchMonitorRequestTests : OpenSearchTestCase() { - + @Test fun `test search monitors request`() { val searchSourceBuilder = SearchSourceBuilder().from(0).size(100).timeout(TimeValue(60, TimeUnit.SECONDS)) val searchRequest = SearchRequest().indices(OpenSearchRestTestCase.randomAlphaOfLength(10)).source(searchSourceBuilder) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/alerts/AlertErrorTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/alerts/AlertErrorTests.kt index c5c6d439..1e52f997 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/alerts/AlertErrorTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/alerts/AlertErrorTests.kt @@ -5,21 +5,24 @@ import org.junit.jupiter.api.Test import java.time.Instant class AlertErrorTests { - @Test fun `test alertError obfuscates IP addresses in message`() { val message = "AlertingException[[5f32db4e2a4fa94f6778cb895dae7a24][10.212.77.91:9300][indices:admin/create]]; " + - "nested: Exception[org.opensearch.transport.RemoteTransportException: [5f32db4e2a4fa94f6778cb895dae7a24][10.212.77.91:9300]" + - "[indices:admin/create]];; java.lang.Exception: org.opensearch.transport.RemoteTransportException: [5f32db4e2a4fa94f6778cb895" + - "dae7a24][10.212.77.91:9300][indices:admin/create]" + "nested: Exception[org.opensearch.transport.RemoteTransportException: " + + "[5f32db4e2a4fa94f6778cb895dae7a24][10.212.77.91:9300][indices:admin/create]];; " + + "java.lang.Exception: org.opensearch.transport.RemoteTransportException: " + + "[5f32db4e2a4fa94f6778cb895dae7a24][10.212.77.91:9300][indices:admin/create]" + val alertError = AlertError(Instant.now(), message = message) + Assert.assertEquals( alertError.message, "AlertingException[[5f32db4e2a4fa94f6778cb895dae7a24][x.x.x.x:9300][indices:admin/create]]; " + - "nested: Exception[org.opensearch.transport.RemoteTransportException: [5f32db4e2a4fa94f6778cb895dae7a24][x.x.x.x:9300]" + - "[indices:admin/create]];; java.lang.Exception: org.opensearch.transport.RemoteTransportException: " + - "[5f32db4e2a4fa94f6778cb895dae7a24][x.x.x.x:9300][indices:admin/create]" + "nested: Exception[org.opensearch.transport.RemoteTransportException: " + + "[5f32db4e2a4fa94f6778cb895dae7a24][x.x.x.x:9300][indices:admin/create]];; " + + "java.lang.Exception: org.opensearch.transport.RemoteTransportException: " + + "[5f32db4e2a4fa94f6778cb895dae7a24][x.x.x.x:9300][indices:admin/create]", ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/bucketselectorext/BucketSelectorExtAggregatorTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/bucketselectorext/BucketSelectorExtAggregatorTests.kt index 8d1c04e5..5a65f36b 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/bucketselectorext/BucketSelectorExtAggregatorTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/bucketselectorext/BucketSelectorExtAggregatorTests.kt @@ -45,47 +45,50 @@ import java.io.IOException import java.util.Collections import java.util.function.Consumer import java.util.function.Function +import kotlin.test.Test class BucketSelectorExtAggregatorTests : AggregatorTestCase() { - - private var SCRIPTNAME = "bucket_selector_script" + private var scriptName = "bucket_selector_script" private var paramName = "the_avg" private var paramValue = 19.0 override fun getMockScriptService(): ScriptService { - val scriptEngine = MockScriptEngine( - MockScriptEngine.NAME, - Collections.singletonMap( - SCRIPTNAME, - Function, Any> { script: Map -> - script[paramName].toString().toDouble() == paramValue - } - ), - emptyMap() - ) + val scriptEngine = + MockScriptEngine( + MockScriptEngine.NAME, + Collections.singletonMap( + scriptName, + Function, Any> { script: Map -> + script[paramName].toString().toDouble() == paramValue + }, + ), + emptyMap(), + ) val engines: Map = Collections.singletonMap(scriptEngine.type, scriptEngine) return ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS) } + @Test @Throws(Exception::class) fun `test bucket selector script`() { val fieldType: MappedFieldType = NumberFieldType("number_field", NumberFieldMapper.NumberType.INTEGER) val fieldType1: MappedFieldType = KeywordFieldType("the_field") - val filters: FiltersAggregationBuilder = FiltersAggregationBuilder("placeholder", MatchAllQueryBuilder()) - .subAggregation( - TermsAggregationBuilder("the_terms").field("the_field") - .subAggregation(AvgAggregationBuilder("the_avg").field("number_field")) - ) - .subAggregation( - BucketSelectorExtAggregationBuilder( - "test_bucket_selector_ext", - Collections.singletonMap("the_avg", "the_avg.value"), - Script(ScriptType.INLINE, MockScriptEngine.NAME, SCRIPTNAME, emptyMap()), - "the_terms", - null + val filters: FiltersAggregationBuilder = + FiltersAggregationBuilder("placeholder", MatchAllQueryBuilder()) + .subAggregation( + TermsAggregationBuilder("the_terms") + .field("the_field") + .subAggregation(AvgAggregationBuilder("the_avg").field("number_field")), + ).subAggregation( + BucketSelectorExtAggregationBuilder( + "test_bucket_selector_ext", + Collections.singletonMap("the_avg", "the_avg.value"), + Script(ScriptType.INLINE, MockScriptEngine.NAME, scriptName, emptyMap()), + "the_terms", + null, + ), ) - ) paramName = "the_avg" paramValue = 19.0 testCase( @@ -105,49 +108,52 @@ class BucketSelectorExtAggregatorTests : AggregatorTestCase() { val bucketSelectorIndices = f.buckets[0].aggregations.get("test_bucket_selector_ext") as BucketSelectorIndices assertThat( bucketSelectorIndices.bucketIndices[0], - CoreMatchers.equalTo(1) + CoreMatchers.equalTo(1), ) assertEquals(BucketSelectorExtAggregationBuilder.NAME.preferredName, bucketSelectorIndices.writeableName) }, fieldType, - fieldType1 + fieldType1, ) } + @Test @Throws(Exception::class) fun `test bucket selector filter include`() { val fieldType: MappedFieldType = NumberFieldType("number_field", NumberFieldMapper.NumberType.INTEGER) val fieldType1: MappedFieldType = KeywordFieldType("the_field") - val selectorAgg1: FiltersAggregationBuilder = FiltersAggregationBuilder("placeholder", MatchAllQueryBuilder()) - .subAggregation( - TermsAggregationBuilder("the_terms").field("the_field") - .subAggregation(AvgAggregationBuilder("the_avg").field("number_field")) - ) - .subAggregation( - BucketSelectorExtAggregationBuilder( - "test_bucket_selector_ext", - Collections.singletonMap("the_avg", "the_avg.value"), - Script(ScriptType.INLINE, MockScriptEngine.NAME, SCRIPTNAME, emptyMap()), - "the_terms", - BucketSelectorExtFilter(IncludeExclude(arrayOf("test1"), arrayOf())) + val selectorAgg1: FiltersAggregationBuilder = + FiltersAggregationBuilder("placeholder", MatchAllQueryBuilder()) + .subAggregation( + TermsAggregationBuilder("the_terms") + .field("the_field") + .subAggregation(AvgAggregationBuilder("the_avg").field("number_field")), + ).subAggregation( + BucketSelectorExtAggregationBuilder( + "test_bucket_selector_ext", + Collections.singletonMap("the_avg", "the_avg.value"), + Script(ScriptType.INLINE, MockScriptEngine.NAME, scriptName, emptyMap()), + "the_terms", + BucketSelectorExtFilter(IncludeExclude(arrayOf("test1"), arrayOf())), + ), ) - ) - val selectorAgg2: FiltersAggregationBuilder = FiltersAggregationBuilder("placeholder", MatchAllQueryBuilder()) - .subAggregation( - TermsAggregationBuilder("the_terms").field("the_field") - .subAggregation(AvgAggregationBuilder("the_avg").field("number_field")) - ) - .subAggregation( - BucketSelectorExtAggregationBuilder( - "test_bucket_selector_ext", - Collections.singletonMap("the_avg", "the_avg.value"), - Script(ScriptType.INLINE, MockScriptEngine.NAME, SCRIPTNAME, emptyMap()), - "the_terms", - BucketSelectorExtFilter(IncludeExclude(arrayOf("test2"), arrayOf())) + val selectorAgg2: FiltersAggregationBuilder = + FiltersAggregationBuilder("placeholder", MatchAllQueryBuilder()) + .subAggregation( + TermsAggregationBuilder("the_terms") + .field("the_field") + .subAggregation(AvgAggregationBuilder("the_avg").field("number_field")), + ).subAggregation( + BucketSelectorExtAggregationBuilder( + "test_bucket_selector_ext", + Collections.singletonMap("the_avg", "the_avg.value"), + Script(ScriptType.INLINE, MockScriptEngine.NAME, scriptName, emptyMap()), + "the_terms", + BucketSelectorExtFilter(IncludeExclude(arrayOf("test2"), arrayOf())), + ), ) - ) paramName = "the_avg" paramValue = 19.0 @@ -169,12 +175,12 @@ class BucketSelectorExtAggregatorTests : AggregatorTestCase() { val bucketSelectorIndices = f.buckets[0].aggregations.get("test_bucket_selector_ext") as BucketSelectorIndices assertThat( bucketSelectorIndices.bucketIndices.size, - CoreMatchers.equalTo(0) + CoreMatchers.equalTo(0), ) assertEquals(BucketSelectorExtAggregationBuilder.NAME.preferredName, bucketSelectorIndices.writeableName) }, fieldType, - fieldType1 + fieldType1, ) testCase( @@ -194,34 +200,36 @@ class BucketSelectorExtAggregatorTests : AggregatorTestCase() { val bucketSelectorIndices = f.buckets[0].aggregations.get("test_bucket_selector_ext") as BucketSelectorIndices assertThat( bucketSelectorIndices.bucketIndices[0], - CoreMatchers.equalTo(1) + CoreMatchers.equalTo(1), ) assertEquals(BucketSelectorExtAggregationBuilder.NAME.preferredName, bucketSelectorIndices.writeableName) }, fieldType, - fieldType1 + fieldType1, ) } + @Test @Throws(Exception::class) fun `test bucket selector filter exclude`() { val fieldType: MappedFieldType = NumberFieldType("number_field", NumberFieldMapper.NumberType.INTEGER) val fieldType1: MappedFieldType = KeywordFieldType("the_field") - val selectorAgg1: FiltersAggregationBuilder = FiltersAggregationBuilder("placeholder", MatchAllQueryBuilder()) - .subAggregation( - TermsAggregationBuilder("the_terms").field("the_field") - .subAggregation(AvgAggregationBuilder("the_avg").field("number_field")) - ) - .subAggregation( - BucketSelectorExtAggregationBuilder( - "test_bucket_selector_ext", - Collections.singletonMap("the_avg", "the_avg.value"), - Script(ScriptType.INLINE, MockScriptEngine.NAME, SCRIPTNAME, emptyMap()), - "the_terms", - BucketSelectorExtFilter(IncludeExclude(arrayOf(), arrayOf("test2"))) + val selectorAgg1: FiltersAggregationBuilder = + FiltersAggregationBuilder("placeholder", MatchAllQueryBuilder()) + .subAggregation( + TermsAggregationBuilder("the_terms") + .field("the_field") + .subAggregation(AvgAggregationBuilder("the_avg").field("number_field")), + ).subAggregation( + BucketSelectorExtAggregationBuilder( + "test_bucket_selector_ext", + Collections.singletonMap("the_avg", "the_avg.value"), + Script(ScriptType.INLINE, MockScriptEngine.NAME, scriptName, emptyMap()), + "the_terms", + BucketSelectorExtFilter(IncludeExclude(arrayOf(), arrayOf("test2"))), + ), ) - ) paramName = "the_avg" paramValue = 19.0 testCase( @@ -241,34 +249,36 @@ class BucketSelectorExtAggregatorTests : AggregatorTestCase() { val bucketSelectorIndices = f.buckets[0].aggregations.get("test_bucket_selector_ext") as BucketSelectorIndices assertThat( bucketSelectorIndices.bucketIndices.size, - CoreMatchers.equalTo(0) + CoreMatchers.equalTo(0), ) assertEquals(BucketSelectorExtAggregationBuilder.NAME.preferredName, bucketSelectorIndices.writeableName) }, fieldType, - fieldType1 + fieldType1, ) } + @Test @Throws(Exception::class) fun `test bucket selector filter numeric key`() { val fieldType: MappedFieldType = NumberFieldType("number_field", NumberFieldMapper.NumberType.INTEGER) val fieldType1: MappedFieldType = KeywordFieldType("the_field") - val selectorAgg1: FiltersAggregationBuilder = FiltersAggregationBuilder("placeholder", MatchAllQueryBuilder()) - .subAggregation( - TermsAggregationBuilder("number_agg").field("number_field") - .subAggregation(ValueCountAggregationBuilder("count").field("number_field")) - ) - .subAggregation( - BucketSelectorExtAggregationBuilder( - "test_bucket_selector_ext", - Collections.singletonMap("count", "count"), - Script(ScriptType.INLINE, MockScriptEngine.NAME, SCRIPTNAME, emptyMap()), - "number_agg", - BucketSelectorExtFilter(IncludeExclude(doubleArrayOf(19.0), doubleArrayOf())) + val selectorAgg1: FiltersAggregationBuilder = + FiltersAggregationBuilder("placeholder", MatchAllQueryBuilder()) + .subAggregation( + TermsAggregationBuilder("number_agg") + .field("number_field") + .subAggregation(ValueCountAggregationBuilder("count").field("number_field")), + ).subAggregation( + BucketSelectorExtAggregationBuilder( + "test_bucket_selector_ext", + Collections.singletonMap("count", "count"), + Script(ScriptType.INLINE, MockScriptEngine.NAME, scriptName, emptyMap()), + "number_agg", + BucketSelectorExtFilter(IncludeExclude(doubleArrayOf(19.0), doubleArrayOf())), + ), ) - ) paramName = "count" paramValue = 1.0 @@ -289,37 +299,39 @@ class BucketSelectorExtAggregatorTests : AggregatorTestCase() { val bucketSelectorIndices = f.buckets[0].aggregations.get("test_bucket_selector_ext") as BucketSelectorIndices assertThat( bucketSelectorIndices.bucketIndices[0], - CoreMatchers.equalTo(0) + CoreMatchers.equalTo(0), ) assertEquals(BucketSelectorExtAggregationBuilder.NAME.preferredName, bucketSelectorIndices.writeableName) }, fieldType, - fieldType1 + fieldType1, ) } + @Test @Throws(Exception::class) fun `test bucket selector nested parent path`() { val fieldType: MappedFieldType = NumberFieldType("number_field", NumberFieldMapper.NumberType.INTEGER) val fieldType1: MappedFieldType = KeywordFieldType("the_field") - val selectorAgg1: FilterAggregationBuilder = FilterAggregationBuilder("placeholder", MatchAllQueryBuilder()) - .subAggregation( - FilterAggregationBuilder("parent_agg", MatchAllQueryBuilder()) - .subAggregation( - TermsAggregationBuilder("term_agg").field("the_field") - .subAggregation(AvgAggregationBuilder("the_avg").field("number_field")) - ) - ) - .subAggregation( - BucketSelectorExtAggregationBuilder( - "test_bucket_selector_ext", - Collections.singletonMap("the_avg", "the_avg.value"), - Script(ScriptType.INLINE, MockScriptEngine.NAME, SCRIPTNAME, emptyMap()), - "parent_agg>term_agg", - null + val selectorAgg1: FilterAggregationBuilder = + FilterAggregationBuilder("placeholder", MatchAllQueryBuilder()) + .subAggregation( + FilterAggregationBuilder("parent_agg", MatchAllQueryBuilder()) + .subAggregation( + TermsAggregationBuilder("term_agg") + .field("the_field") + .subAggregation(AvgAggregationBuilder("the_avg").field("number_field")), + ), + ).subAggregation( + BucketSelectorExtAggregationBuilder( + "test_bucket_selector_ext", + Collections.singletonMap("the_avg", "the_avg.value"), + Script(ScriptType.INLINE, MockScriptEngine.NAME, scriptName, emptyMap()), + "parent_agg>term_agg", + null, + ), ) - ) paramName = "the_avg" paramValue = 19.0 testCaseInternalFilter( @@ -341,12 +353,12 @@ class BucketSelectorExtAggregatorTests : AggregatorTestCase() { val bucketSelectorIndices = f.aggregations.get("test_bucket_selector_ext") as BucketSelectorIndices assertThat( bucketSelectorIndices.bucketIndices[0], - CoreMatchers.equalTo(1) + CoreMatchers.equalTo(1), ) assertEquals(BucketSelectorExtAggregationBuilder.NAME.preferredName, bucketSelectorIndices.writeableName) }, fieldType, - fieldType1 + fieldType1, ) } @@ -356,7 +368,7 @@ class BucketSelectorExtAggregatorTests : AggregatorTestCase() { query: Query, buildIndex: CheckedConsumer, verify: Consumer, - vararg fieldType: MappedFieldType + vararg fieldType: MappedFieldType, ) { newDirectory().use { directory -> val indexWriter = RandomIndexWriter(random(), directory) @@ -377,7 +389,7 @@ class BucketSelectorExtAggregatorTests : AggregatorTestCase() { query: Query, buildIndex: CheckedConsumer, verify: Consumer, - vararg fieldType: MappedFieldType + vararg fieldType: MappedFieldType, ) { newDirectory().use { directory -> val indexWriter = RandomIndexWriter(random(), directory) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/BucketLevelTriggerTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/BucketLevelTriggerTests.kt index 1a9e3cbe..15da7e5e 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/BucketLevelTriggerTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/BucketLevelTriggerTests.kt @@ -15,7 +15,6 @@ import kotlin.test.assertEquals import kotlin.test.assertNotNull class BucketLevelTriggerTests { - @Test fun `test BucketLevelTrigger asTemplateArgs`() { val trigger = randomBucketLevelTrigger() @@ -29,12 +28,12 @@ class BucketLevelTriggerTests { assertEquals( trigger.actions.size, actions.size, - "Template arg field 'actions' doesn't match" + "Template arg field 'actions' doesn't match", ) assertEquals( trigger.getParentBucketPath(), templateArgs[PARENT_BUCKET_PATH], - "Template arg field 'parentBucketPath' doesn't match" + "Template arg field 'parentBucketPath' doesn't match", ) val condition = templateArgs[CONDITION_FIELD] as? Map<*, *> assertNotNull(condition, "Template arg field 'condition' is empty") @@ -43,12 +42,12 @@ class BucketLevelTriggerTests { assertEquals( trigger.bucketSelector.script.idOrCode, script[SOURCE_FIELD], - "Template arg field 'script.source' doesn't match" + "Template arg field 'script.source' doesn't match", ) assertEquals( trigger.bucketSelector.script.lang, script[LANG_FIELD], - "Template arg field 'script.lang' doesn't match" + "Template arg field 'script.lang' doesn't match", ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInputTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInputTests.kt index 6d1c1055..dff00d77 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInputTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInputTests.kt @@ -9,25 +9,24 @@ class ClusterMetricsInputTests { private var pathParams = "" private var url = "" - private val validClusters = listOf( - "cluster-name", - "cluster:name" - ) - - private val invalidClusters = listOf( - // Character length less than 1 should return FALSE - "", - - // Character length greater than 255 should return FALSE - (0..255).joinToString(separator = "") { "a" }, - - // Invalid characters should return FALSE - "cluster-#name", - "cluster:#name", + private val validClusters = + listOf( + "cluster-name", + "cluster:name", + ) - // More than 1 `:` character should return FALSE - "bad:cluster:name" - ) + private val invalidClusters = + listOf( + // Character length less than 1 should return FALSE + "", + // Character length greater than 255 should return FALSE + (0..255).joinToString(separator = "") { "a" }, + // Invalid characters should return FALSE + "cluster-#name", + "cluster:#name", + // More than 1 `:` character should return FALSE + "bad:cluster:name", + ) @Test fun `test valid ClusterMetricsInput creation using HTTP URI component fields`() { @@ -296,7 +295,8 @@ class ClusterMetricsInputTests { // WHEN + THEN assertFailsWith( - "The provided path parameters contain invalid characters or spaces. Please omit: " + ILLEGAL_PATH_PARAMETER_CHARACTERS.joinToString(" ") + "The provided path parameters contain invalid characters or spaces. Please omit: " + + ILLEGAL_PATH_PARAMETER_CHARACTERS.joinToString(" "), ) { clusterMetricsInput.parsePathParams() } @@ -308,7 +308,8 @@ class ClusterMetricsInputTests { @Test fun `test ClusterMetricsInput correctly determines ApiType when path is provided as URI component`() { var testCount = 1 // Start off with count of 1 to account for ApiType.BLANK - ClusterMetricsInput.ClusterMetricType.values() + ClusterMetricsInput.ClusterMetricType + .values() .filter { enum -> enum != ClusterMetricsInput.ClusterMetricType.BLANK } .forEach { testApiType -> // GIVEN @@ -328,7 +329,8 @@ class ClusterMetricsInputTests { @Test fun `test ClusterMetricsInput correctly determines ApiType when path and path params are provided as URI components`() { var testCount = 1 // Start off with count of 1 to account for ApiType.BLANK - ClusterMetricsInput.ClusterMetricType.values() + ClusterMetricsInput.ClusterMetricType + .values() .filter { enum -> enum != ClusterMetricsInput.ClusterMetricType.BLANK } .forEach { testApiType -> // GIVEN @@ -348,7 +350,8 @@ class ClusterMetricsInputTests { @Test fun `test ClusterMetricsInput correctly determines ApiType when path is provided in URL field`() { var testCount = 1 // Start off with count of 1 to account for ApiType.BLANK - ClusterMetricsInput.ClusterMetricType.values() + ClusterMetricsInput.ClusterMetricType + .values() .filter { enum -> enum != ClusterMetricsInput.ClusterMetricType.BLANK } .forEach { testApiType -> // GIVEN @@ -369,7 +372,8 @@ class ClusterMetricsInputTests { @Test fun `test ClusterMetricsInput correctly determines ApiType when path and path params are provided in URL field`() { var testCount = 1 // Start off with count of 1 to account for ApiType.BLANK - ClusterMetricsInput.ClusterMetricType.values() + ClusterMetricsInput.ClusterMetricType + .values() .filter { enum -> enum != ClusterMetricsInput.ClusterMetricType.BLANK } .forEach { testApiType -> // GIVEN @@ -480,12 +484,13 @@ class ClusterMetricsInputTests { val clusters = listOf(it) // WHEN - val clusterMetricsInput = ClusterMetricsInput( - path = path, - pathParams = pathParams, - url = url, - clusters = clusters - ) + val clusterMetricsInput = + ClusterMetricsInput( + path = path, + pathParams = pathParams, + url = url, + clusters = clusters, + ) // THEN assertEquals(path, clusterMetricsInput.path) @@ -503,12 +508,13 @@ class ClusterMetricsInputTests { val clusters = validClusters // WHEN - val clusterMetricsInput = ClusterMetricsInput( - path = path, - pathParams = pathParams, - url = url, - clusters = clusters - ) + val clusterMetricsInput = + ClusterMetricsInput( + path = path, + pathParams = pathParams, + url = url, + clusters = clusters, + ) // THEN assertEquals(path, clusterMetricsInput.path) @@ -531,7 +537,7 @@ class ClusterMetricsInputTests { path = path, pathParams = pathParams, url = url, - clusters = clusters + clusters = clusters, ) } } @@ -551,7 +557,7 @@ class ClusterMetricsInputTests { path = path, pathParams = pathParams, url = url, - clusters = clusters + clusters = clusters, ) } } @@ -569,7 +575,7 @@ class ClusterMetricsInputTests { path = path, pathParams = pathParams, url = url, - clusters = listOf() + clusters = listOf(), ) } } @@ -587,7 +593,7 @@ class ClusterMetricsInputTests { path = path, pathParams = pathParams, url = url, - clusters = listOf() + clusters = listOf(), ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/CompositeInputTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/CompositeInputTests.kt index ad0d2b24..4168be96 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/CompositeInputTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/CompositeInputTests.kt @@ -17,7 +17,7 @@ class CompositeInputTests { Assertions.assertEquals( templateDelegates[Sequence.DELEGATES_FIELD], sequence.delegates, - "Template args 'id' field does not match:" + "Template args 'id' field does not match:", ) } @@ -32,12 +32,12 @@ class CompositeInputTests { Assertions.assertEquals( templateDelegates[Delegate.ORDER_FIELD], delegate.order, - "Template args 'id' field does not match:" + "Template args 'id' field does not match:", ) Assertions.assertEquals( templateDelegates[Delegate.MONITOR_ID_FIELD], delegate.monitorId, - "Template args 'id' field does not match:" + "Template args 'id' field does not match:", ) } @@ -49,7 +49,7 @@ class CompositeInputTests { } catch (e: IllegalArgumentException) { Assertions.assertEquals( "Invalid delgate order", - e.message + e.message, ) } } @@ -62,8 +62,7 @@ class CompositeInputTests { } catch (e: IllegalArgumentException) { e.message?.let { Assertions.assertTrue( - it.contains("Invalid characters in id") - + it.contains("Invalid characters in id"), ) } } @@ -77,8 +76,7 @@ class CompositeInputTests { } catch (e: IllegalArgumentException) { e.message?.let { Assertions.assertTrue( - it.contains("at least one of fields, 'monitorIds' and 'monitorId' should be provided") - + it.contains("at least one of fields, 'monitorIds' and 'monitorId' should be provided"), ) } } @@ -92,8 +90,7 @@ class CompositeInputTests { } catch (e: IllegalArgumentException) { e.message?.let { Assertions.assertTrue( - it.contains("Invalid characters in id") - + it.contains("Invalid characters in id"), ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/DataSourcesTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/DataSourcesTests.kt index 5f67f2a3..297e1bc0 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/DataSourcesTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/DataSourcesTests.kt @@ -8,16 +8,17 @@ import org.opensearch.core.common.io.stream.StreamInput class DataSourcesTests { @Test fun `Test DataSources construction with no comments indices`() { - val dataSources = DataSources( - ScheduledJob.DOC_LEVEL_QUERIES_INDEX, - ".opensearch-alerting-finding-history-write", - "<.opensearch-alerting-finding-history-{now/d}-1>", - ".opendistro-alerting-alerts", - ".opendistro-alerting-alert-history-write", - "<.opendistro-alerting-alert-history-{now/d}-1>", - mapOf(), - false - ) + val dataSources = + DataSources( + ScheduledJob.DOC_LEVEL_QUERIES_INDEX, + ".opensearch-alerting-finding-history-write", + "<.opensearch-alerting-finding-history-{now/d}-1>", + ".opendistro-alerting-alerts", + ".opendistro-alerting-alert-history-write", + "<.opendistro-alerting-alert-history-{now/d}-1>", + mapOf(), + false, + ) Assertions.assertNotNull(dataSources) val out = BytesStreamOutput() diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInputTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInputTests.kt index b102b28e..8f6a7c6a 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInputTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInputTests.kt @@ -22,22 +22,22 @@ class DocLevelMonitorInputTests { Assertions.assertEquals( templateArgs[DocLevelQuery.QUERY_ID_FIELD], query.id, - "Template args 'id' field does not match:" + "Template args 'id' field does not match:", ) Assertions.assertEquals( templateArgs[DocLevelQuery.QUERY_FIELD], query.query, - "Template args 'query' field does not match:" + "Template args 'query' field does not match:", ) Assertions.assertEquals( templateArgs[DocLevelQuery.NAME_FIELD], query.name, - "Template args 'name' field does not match:" + "Template args 'name' field does not match:", ) Assertions.assertEquals( templateArgs[DocLevelQuery.TAGS_FIELD], query.tags, - "Template args 'tags' field does not match:" + "Template args 'tags' field does not match:", ) } @@ -53,7 +53,7 @@ class DocLevelMonitorInputTests { } catch (e: IllegalArgumentException) { Assertions.assertEquals( "The query name, $emptyString, should be between 1 - 256 characters.", - e.message + e.message, ) } @@ -69,7 +69,7 @@ class DocLevelMonitorInputTests { } catch (e: IllegalArgumentException) { Assertions.assertEquals( "The query name, $badString, should be between 1 - 256 characters.", - e.message + e.message, ) } } @@ -84,7 +84,7 @@ class DocLevelMonitorInputTests { } catch (e: IllegalArgumentException) { Assertions.assertEquals( "The query tag, $badString, contains an invalid character: [' ','[',']','{','}','(',')']", - e.message + e.message, ) } } @@ -105,22 +105,22 @@ class DocLevelMonitorInputTests { Assertions.assertEquals( templateArgs[DocLevelMonitorInput.DESCRIPTION_FIELD], input.description, - "Template args 'description' field does not match:" + "Template args 'description' field does not match:", ) Assertions.assertEquals( templateArgs[DocLevelMonitorInput.INDICES_FIELD], input.indices, - "Template args 'indices' field does not match:" + "Template args 'indices' field does not match:", ) Assertions.assertEquals( input.queries.size, (templateArgs[DocLevelMonitorInput.QUERIES_FIELD] as List<*>).size, - "Template args 'queries' field does not contain the expected number of queries:" + "Template args 'queries' field does not contain the expected number of queries:", ) input.queries.forEach { Assertions.assertTrue( (templateArgs[DocLevelMonitorInput.QUERIES_FIELD] as List<*>).contains(it.asTemplateArg()), - "Template args 'queries' field does not match:" + "Template args 'queries' field does not match:", ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTriggerTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTriggerTests.kt index 7375223c..d8b45225 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTriggerTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTriggerTests.kt @@ -14,7 +14,6 @@ import kotlin.test.assertEquals import kotlin.test.assertNotNull class DocumentLevelTriggerTests { - @Test fun `test DocumentLevelTrigger asTemplateArgs`() { val trigger = randomDocumentLevelTrigger() @@ -28,7 +27,7 @@ class DocumentLevelTriggerTests { assertEquals( trigger.actions.size, actions.size, - "Template arg field 'actions' doesn't match" + "Template arg field 'actions' doesn't match", ) val condition = templateArgs[CONDITION_FIELD] as? Map<*, *> assertNotNull(condition, "Template arg field 'condition' is empty") @@ -37,12 +36,12 @@ class DocumentLevelTriggerTests { assertEquals( trigger.condition.idOrCode, script[SOURCE_FIELD], - "Template arg field 'script.source' doesn't match" + "Template arg field 'script.source' doesn't match", ) assertEquals( trigger.condition.lang, script[LANG_FIELD], - "Template arg field 'script.lang' doesn't match" + "Template arg field 'script.lang' doesn't match", ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/FindingTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/FindingTests.kt index 10579a41..832bb799 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/FindingTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/FindingTests.kt @@ -18,23 +18,23 @@ internal class FindingTests { assertEquals( templateArgs[Finding.RELATED_DOC_IDS_FIELD], finding.relatedDocIds, - "Template args 'relatedDocIds' field does not match:" + "Template args 'relatedDocIds' field does not match:", ) assertEquals(templateArgs[Finding.MONITOR_ID_FIELD], finding.monitorId, "Template args 'monitorId' field does not match:") assertEquals( templateArgs[Finding.MONITOR_NAME_FIELD], finding.monitorName, - "Template args 'monitorName' field does not match:" + "Template args 'monitorName' field does not match:", ) assertEquals( templateArgs[Finding.QUERIES_FIELD], finding.docLevelQueries, - "Template args 'queries' field does not match:" + "Template args 'queries' field does not match:", ) assertEquals( templateArgs[Finding.TIMESTAMP_FIELD], finding.timestamp.toEpochMilli(), - "Template args 'timestamp' field does not match:" + "Template args 'timestamp' field does not match:", ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/MockScheduledJob.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/MockScheduledJob.kt index 59f3771b..3dc7ed34 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/MockScheduledJob.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/MockScheduledJob.kt @@ -14,13 +14,19 @@ class MockScheduledJob( override val enabled: Boolean, override val schedule: Schedule, override var lastUpdateTime: Instant, - override val enabledTime: Instant? + override val enabledTime: Instant?, ) : ScheduledJob { - override fun fromDocument(id: String, version: Long): ScheduledJob { + override fun fromDocument( + id: String, + version: Long, + ): ScheduledJob { TODO("not implemented") } - override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder { + override fun toXContent( + builder: XContentBuilder?, + params: ToXContent.Params?, + ): XContentBuilder { TODO("not implemented") } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/MonitorsTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/MonitorsTests.kt index 9529e44d..f7c15d13 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/MonitorsTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/MonitorsTests.kt @@ -7,7 +7,6 @@ import kotlin.test.assertEquals import kotlin.test.assertNotNull class MonitorsTests { - @Test fun `test monitor asTemplateArgs`() { val monitor = randomQueryLevelMonitor(enabled = true) @@ -18,28 +17,28 @@ class MonitorsTests { assertEquals( monitor.version, templateArgs[IndexUtils._VERSION], - "Template arg field 'version' doesn't match" + "Template arg field 'version' doesn't match", ) assertEquals(monitor.name, templateArgs[Monitor.NAME_FIELD], "Template arg field 'name' doesn't match") assertEquals( monitor.enabled, templateArgs[Monitor.ENABLED_FIELD], - "Template arg field 'enabled' doesn't match" + "Template arg field 'enabled' doesn't match", ) assertEquals( monitor.monitorType.toString(), templateArgs[Monitor.MONITOR_TYPE_FIELD], - "Template arg field 'monitoryType' doesn't match" + "Template arg field 'monitoryType' doesn't match", ) assertEquals( monitor.enabledTime?.toEpochMilli(), templateArgs[Monitor.ENABLED_TIME_FIELD], - "Template arg field 'enabledTime' doesn't match" + "Template arg field 'enabledTime' doesn't match", ) assertEquals( monitor.lastUpdateTime.toEpochMilli(), templateArgs[Monitor.LAST_UPDATE_TIME_FIELD], - "Template arg field 'lastUpdateTime' doesn't match" + "Template arg field 'lastUpdateTime' doesn't match", ) assertNotNull(templateArgs[Monitor.SCHEDULE_FIELD], "Template arg field 'schedule' not set") val inputs = templateArgs[Monitor.INPUTS_FIELD] as? List<*> diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/QueryLevelTriggerTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/QueryLevelTriggerTests.kt index 824e1b1e..1b961cea 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/QueryLevelTriggerTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/QueryLevelTriggerTests.kt @@ -14,7 +14,6 @@ import kotlin.test.assertEquals import kotlin.test.assertNotNull class QueryLevelTriggerTests { - @Test fun `test QueryLevelTrigger asTemplateArgs`() { val trigger = randomQueryLevelTrigger() @@ -28,7 +27,7 @@ class QueryLevelTriggerTests { assertEquals( trigger.actions.size, actions.size, - "Template arg field 'actions' doesn't match" + "Template arg field 'actions' doesn't match", ) val condition = templateArgs[CONDITION_FIELD] as? Map<*, *> assertNotNull(condition, "Template arg field 'condition' is empty") @@ -37,12 +36,12 @@ class QueryLevelTriggerTests { assertEquals( trigger.condition.idOrCode, script[SOURCE_FIELD], - "Template arg field 'script.source' doesn't match" + "Template arg field 'script.source' doesn't match", ) assertEquals( trigger.condition.lang, script[LANG_FIELD], - "Template arg field 'script.lang' doesn't match" + "Template arg field 'script.lang' doesn't match", ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/ScheduleTest.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/ScheduleTest.kt index d2024b67..1de6e128 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/ScheduleTest.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/ScheduleTest.kt @@ -59,7 +59,7 @@ class ScheduleTest : XContentTestBase { assertEquals( testInstance.plusSeconds(2L), nextTimeToExecute, - "nextTimeToExecute should be 2 seconds after test instance" + "nextTimeToExecute should be 2 seconds after test instance", ) } @@ -79,7 +79,7 @@ class ScheduleTest : XContentTestBase { assertEquals( previousExecutionTimeInstance.plusSeconds(2L), nextTimeToExecute, - "nextTimeToExecute should be 2 seconds after test instance" + "nextTimeToExecute should be 2 seconds after test instance", ) } @@ -98,7 +98,7 @@ class ScheduleTest : XContentTestBase { assertEquals( enabledTimeInstance.plusSeconds(120L), nextTimeToExecute, - "nextTimeToExecute should be 120 seconds seconds after enabled time" + "nextTimeToExecute should be 120 seconds seconds after enabled time", ) } @@ -120,7 +120,7 @@ class ScheduleTest : XContentTestBase { assertEquals( previousExecutionTimeInstance.plusSeconds(60L), nextTimeToExecute, - "nextTimeToExecute should be 60 seconds after previous execution time" + "nextTimeToExecute should be 60 seconds after previous execution time", ) } @@ -176,8 +176,8 @@ class ScheduleTest : XContentTestBase { assertFailsWith(IllegalArgumentException::class, "Expected IllegalArgumentException") { Schedule.parse( parser( - scheduleString - ) + scheduleString, + ), ) } } @@ -362,12 +362,12 @@ class ScheduleTest : XContentTestBase { assertEquals( schedule.interval, period[INTERVAL_FIELD], - "Template arg field 'interval' doesn't match" + "Template arg field 'interval' doesn't match", ) assertEquals( schedule.unit.toString(), period[UNIT_FIELD], - "Template arg field 'unit' doesn't match" + "Template arg field 'unit' doesn't match", ) } @@ -382,12 +382,12 @@ class ScheduleTest : XContentTestBase { assertEquals( schedule.expression, cron[EXPRESSION_FIELD], - "Template arg field 'expression' doesn't match" + "Template arg field 'expression' doesn't match", ) assertEquals( schedule.timezone.toString(), cron[TIMEZONE_FIELD], - "Template arg field 'timezone' doesn't match" + "Template arg field 'timezone' doesn't match", ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/SearchInputTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/SearchInputTests.kt index 0fc0f656..0806ba83 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/SearchInputTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/SearchInputTests.kt @@ -9,7 +9,6 @@ import kotlin.test.assertEquals import kotlin.test.assertNotNull class SearchInputTests { - @Test fun `test SearchInput asTemplateArgs`() { val searchInput = randomSearchInput() @@ -21,12 +20,12 @@ class SearchInputTests { assertEquals( searchInput.indices, search[INDICES_FIELD], - "Template arg field 'indices' doesn't match" + "Template arg field 'indices' doesn't match", ) assertEquals( searchInput.query.toString(), search[QUERY_FIELD], - "Template arg field 'query' doesn't match" + "Template arg field 'query' doesn't match", ) } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/WriteableTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/WriteableTests.kt index 6aecb888..35a1613a 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/WriteableTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/WriteableTests.kt @@ -42,7 +42,6 @@ import java.time.temporal.ChronoUnit import kotlin.test.assertTrue class WriteableTests { - @Test fun `test throttle as stream`() { val throttle = randomThrottle() @@ -216,7 +215,7 @@ class WriteableTests { Assertions.assertEquals( actionExecutionPolicy, newActionExecutionPolicy, - "Round tripping ActionExecutionPolicy doesn't work" + "Round tripping ActionExecutionPolicy doesn't work", ) } @@ -230,7 +229,7 @@ class WriteableTests { OpenSearchTestCase.assertEquals( "Round tripping ActionRunResult doesn't work", actionRunResult, - newActionRunResult + newActionRunResult, ) } @@ -354,11 +353,12 @@ class WriteableTests { val myMonitorInput = MyMonitorInput(1, "hello", MyMonitorInput(2, "world", null)) val myObjOut = BytesStreamOutput() myMonitorInput.writeTo(myObjOut) - val docLevelMonitorInput = DocLevelMonitorInput( - "test", - listOf("test"), - listOf(randomDocLevelQuery()) - ) + val docLevelMonitorInput = + DocLevelMonitorInput( + "test", + listOf("test"), + listOf(randomDocLevelQuery()), + ) val remoteDocLevelMonitorInput = RemoteDocLevelMonitorInput(myObjOut.bytes(), docLevelMonitorInput) val out = BytesStreamOutput() @@ -377,11 +377,12 @@ class WriteableTests { val myMonitorInput = MyMonitorInput(1, "hello", MyMonitorInput(2, "world", null)) var myObjOut = BytesStreamOutput() myMonitorInput.writeTo(myObjOut) - val docLevelMonitorInput = DocLevelMonitorInput( - "test", - listOf("test"), - listOf(randomDocLevelQuery()) - ) + val docLevelMonitorInput = + DocLevelMonitorInput( + "test", + listOf("test"), + listOf(randomDocLevelQuery()), + ) val remoteDocLevelMonitorInput = RemoteDocLevelMonitorInput(myObjOut.bytes(), docLevelMonitorInput) val myMonitorTrigger = MyMonitorTrigger(1, "hello", MyMonitorTrigger(2, "world", null)) @@ -389,21 +390,22 @@ class WriteableTests { myMonitorTrigger.writeTo(myObjOut) val remoteMonitorTrigger = RemoteMonitorTrigger("id", "name", "1", listOf(), myObjOut.bytes()) - val monitor = Monitor( - Monitor.NO_ID, - Monitor.NO_VERSION, - "hello", - true, - IntervalSchedule(1, ChronoUnit.MINUTES), - Instant.now(), - Instant.now(), - "remote_doc_level_monitor", - null, - IndexUtils.NO_SCHEMA_VERSION, - listOf(remoteDocLevelMonitorInput), - listOf(remoteMonitorTrigger), - mapOf() - ) + val monitor = + Monitor( + Monitor.NO_ID, + Monitor.NO_VERSION, + "hello", + true, + IntervalSchedule(1, ChronoUnit.MINUTES), + Instant.now(), + Instant.now(), + "remote_doc_level_monitor", + null, + IndexUtils.NO_SCHEMA_VERSION, + listOf(remoteDocLevelMonitorInput), + listOf(remoteMonitorTrigger), + mapOf(), + ) val out = BytesStreamOutput() monitor.writeTo(out) @@ -417,15 +419,16 @@ class WriteableTests { fun `test Comment object`() { val user = randomUser() val createdTime = Instant.now() - val comment = Comment( - "123", - "456", - "alert", - "content", - createdTime, - null, - user - ) + val comment = + Comment( + "123", + "456", + "alert", + "content", + createdTime, + null, + user, + ) Assertions.assertNotNull(comment) val out = BytesStreamOutput() comment.writeTo(out) @@ -447,7 +450,7 @@ class WriteableTests { "trigger-name", mutableListOf(UUIDs.randomBase64UUID().toString()), null, - mutableMapOf(Pair("alertId", map)) + mutableMapOf(Pair("alertId", map)), ) } @@ -461,18 +464,21 @@ class WriteableTests { map, false, Instant.now(), - null + null, ) } } -data class MyMonitorInput(val a: Int, val b: String, val c: MyMonitorInput?) : Writeable { - +data class MyMonitorInput( + val a: Int, + val b: String, + val c: MyMonitorInput?, +) : Writeable { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readInt(), sin.readString(), - sin.readOptionalWriteable { MyMonitorInput(it) } + sin.readOptionalWriteable { MyMonitorInput(it) }, ) override fun writeTo(out: StreamOutput) { @@ -482,13 +488,16 @@ data class MyMonitorInput(val a: Int, val b: String, val c: MyMonitorInput?) : W } } -data class MyMonitorTrigger(val a: Int, val b: String, val c: MyMonitorTrigger?) : Writeable { - +data class MyMonitorTrigger( + val a: Int, + val b: String, + val c: MyMonitorTrigger?, +) : Writeable { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readInt(), sin.readString(), - sin.readOptionalWriteable { MyMonitorTrigger(it) } + sin.readOptionalWriteable { MyMonitorTrigger(it) }, ) override fun writeTo(out: StreamOutput) { diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTestBase.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTestBase.kt index 9a42c780..4fd83aca 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTestBase.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTestBase.kt @@ -9,9 +9,7 @@ import org.opensearch.core.xcontent.XContentParser import org.opensearch.search.SearchModule interface XContentTestBase { - fun builder(): XContentBuilder { - return XContentBuilder.builder(XContentType.JSON.xContent()) - } + fun builder(): XContentBuilder = XContentBuilder.builder(XContentType.JSON.xContent()) fun parser(xc: String): XContentParser { val parser = XContentType.JSON.xContent().createParser(xContentRegistry(), LoggingDeprecationHandler.INSTANCE, xc) @@ -19,9 +17,8 @@ interface XContentTestBase { return parser } - fun xContentRegistry(): NamedXContentRegistry { - return NamedXContentRegistry( - listOf(SearchInput.XCONTENT_REGISTRY) + SearchModule(Settings.EMPTY, emptyList()).namedXContents + fun xContentRegistry(): NamedXContentRegistry = + NamedXContentRegistry( + listOf(SearchInput.XCONTENT_REGISTRY) + SearchModule(Settings.EMPTY, emptyList()).namedXContents, ) - } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTests.kt index 252be78f..43a6bf22 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTests.kt @@ -44,7 +44,6 @@ import java.time.temporal.ChronoUnit import kotlin.test.assertFailsWith class XContentTests { - @Test fun `test action parsing`() { val action = randomAction() @@ -69,6 +68,7 @@ class XContentTests { Assertions.assertEquals(action, parsedAction, "Round tripping Action doesn't work") } + @Test fun `test action parsing with throttled enabled and null throttle`() { val action = randomAction().copy(throttle = null).copy(throttleEnabled = true) val actionString = action.toXContent(builder(), ToXContent.EMPTY_PARAMS).string() @@ -83,7 +83,7 @@ class XContentTests { randomActionWithPolicy().copy( throttleEnabled = true, throttle = Throttle(value = 5, unit = ChronoUnit.MINUTES), - actionExecutionPolicy = ActionExecutionPolicy(PerExecutionActionScope()) + actionExecutionPolicy = ActionExecutionPolicy(PerExecutionActionScope()), ) Assertions.fail("Creating an action with per execution scope and throttle enabled did not fail.") } catch (ignored: IllegalArgumentException) { @@ -107,8 +107,8 @@ class XContentTests { assertFailsWith("Only support MINUTES throttle unit") { Throttle.parse( parser( - wrongThrottleString - ) + wrongThrottleString, + ), ) } } @@ -121,8 +121,8 @@ class XContentTests { assertFailsWith("Can only set positive throttle period") { Throttle.parse( parser( - throttleString - ) + throttleString, + ), ) } } @@ -137,7 +137,8 @@ class XContentTests { @Test fun `test monitor parsing with no name`() { - val monitorStringWithoutName = """ + val monitorStringWithoutName = + """ { "type": "monitor", "enabled": false, @@ -150,20 +151,21 @@ class XContentTests { "inputs": [], "triggers": [] } - """.trimIndent() + """.trimIndent() assertFailsWith("Monitor name is null") { Monitor.parse( parser( - monitorStringWithoutName - ) + monitorStringWithoutName, + ), ) } } @Test fun `test monitor parsing with no schedule`() { - val monitorStringWithoutSchedule = """ + val monitorStringWithoutSchedule = + """ { "type": "monitor", "name": "asdf", @@ -171,7 +173,7 @@ class XContentTests { "inputs": [], "triggers": [] } - """.trimIndent() + """.trimIndent() assertFailsWith("Monitor schedule is null") { Monitor.parse(parser(monitorStringWithoutSchedule)) @@ -287,20 +289,21 @@ class XContentTests { Assertions.assertEquals( ChainedMonitorFindings.parse(parser(cmf1String)), cmf1, - "Round tripping chained monitor findings failed" + "Round tripping chained monitor findings failed", ) val cmf2 = ChainedMonitorFindings(monitorIds = listOf("m1", "m2")) val cmf2String = cmf2.toJsonString() Assertions.assertEquals( ChainedMonitorFindings.parse(parser(cmf2String)), cmf2, - "Round tripping chained monitor findings failed" + "Round tripping chained monitor findings failed", ) } @Test fun `test old monitor format parsing`() { - val monitorString = """ + val monitorString = + """ { "type": "monitor", "schema_version": 3, @@ -372,12 +375,12 @@ class XContentTests { ], "last_update_time": 1614121489719 } - """.trimIndent() + """.trimIndent() val parsedMonitor = Monitor.parse(parser(monitorString)) Assertions.assertEquals( Monitor.MonitorType.QUERY_LEVEL_MONITOR.value, parsedMonitor.monitorType, - "Incorrect monitor type" + "Incorrect monitor type", ) Assertions.assertEquals(1, parsedMonitor.triggers.size, "Incorrect trigger count") val trigger = parsedMonitor.triggers.first() @@ -423,7 +426,7 @@ class XContentTests { Assertions.assertEquals( actionExecutionPolicy, parsedActionExecutionPolicy, - "Round tripping ActionExecutionPolicy doesn't work" + "Round tripping ActionExecutionPolicy doesn't work", ) } @@ -435,7 +438,7 @@ class XContentTests { Assertions.assertEquals( dlq, parsedDlq, - "Round tripping Doc level query doesn't work" + "Round tripping Doc level query doesn't work", ) } @@ -447,7 +450,7 @@ class XContentTests { Assertions.assertEquals( dlq, parsedDlq, - "Round tripping Doc level query doesn't work" + "Round tripping Doc level query doesn't work", ) } @@ -464,29 +467,31 @@ class XContentTests { @Test fun `test alert parsing with noop trigger`() { val monitor = randomQueryLevelMonitor() - val alert = Alert( - id = "", - monitor = monitor, - trigger = NoOpTrigger(), - startTime = Instant.now().truncatedTo(ChronoUnit.MILLIS), - errorMessage = "some error", - lastNotificationTime = Instant.now(), - workflowId = "", - executionId = "", - clusters = listOf() - ) + val alert = + Alert( + id = "", + monitor = monitor, + trigger = NoOpTrigger(), + startTime = Instant.now().truncatedTo(ChronoUnit.MILLIS), + errorMessage = "some error", + lastNotificationTime = Instant.now(), + workflowId = "", + executionId = "", + clusters = listOf(), + ) assertEquals("Round tripping alert doesn't work", alert.triggerName, "NoOp trigger") } @Test fun `test alert parsing without user`() { - val alertStr = "{\"id\":\"\",\"version\":-1,\"monitor_id\":\"\",\"schema_version\":0,\"monitor_version\":1," + - "\"monitor_name\":\"ARahqfRaJG\",\"trigger_id\":\"fhe1-XQBySl0wQKDBkOG\",\"trigger_name\":\"ffELMuhlro\"," + - "\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\"" + - ":[{\"action_id\":\"ghe1-XQBySl0wQKDBkOG\",\"last_execution_time\":1601917224583,\"throttled_count\":-1478015168}," + - "{\"action_id\":\"gxe1-XQBySl0wQKDBkOH\",\"last_execution_time\":1601917224583,\"throttled_count\":-768533744}]," + - "\"start_time\":1601917224599,\"last_notification_time\":null,\"end_time\":null,\"acknowledged_time\":null," + - "\"clusters\":[\"cluster-1\",\"cluster-2\"]}" + val alertStr = + "{\"id\":\"\",\"version\":-1,\"monitor_id\":\"\",\"schema_version\":0,\"monitor_version\":1," + + "\"monitor_name\":\"ARahqfRaJG\",\"trigger_id\":\"fhe1-XQBySl0wQKDBkOG\",\"trigger_name\":\"ffELMuhlro\"," + + "\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\"" + + ":[{\"action_id\":\"ghe1-XQBySl0wQKDBkOG\",\"last_execution_time\":1601917224583,\"throttled_count\":-1478015168}," + + "{\"action_id\":\"gxe1-XQBySl0wQKDBkOH\",\"last_execution_time\":1601917224583,\"throttled_count\":-768533744}]," + + "\"start_time\":1601917224599,\"last_notification_time\":null,\"end_time\":null,\"acknowledged_time\":null," + + "\"clusters\":[\"cluster-1\",\"cluster-2\"]}" val parsedAlert = Alert.parse(parser(alertStr)) OpenSearchTestCase.assertNull(parsedAlert.monitorUser) } @@ -517,13 +522,14 @@ class XContentTests { @Test fun `test MonitorMetadata`() { - val monitorMetadata = MonitorMetadata( - id = "monitorId-metadata", - monitorId = "monitorId", - lastActionExecutionTimes = emptyList(), - lastRunContext = emptyMap(), - sourceToQueryIndexMapping = mutableMapOf() - ) + val monitorMetadata = + MonitorMetadata( + id = "monitorId-metadata", + monitorId = "monitorId", + lastActionExecutionTimes = emptyList(), + lastRunContext = emptyMap(), + sourceToQueryIndexMapping = mutableMapOf(), + ) val monitorMetadataString = monitorMetadata.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS).string() val parsedMonitorMetadata = MonitorMetadata.parse(parser(monitorMetadataString)) assertEquals("Round tripping MonitorMetadata doesn't work", monitorMetadata, parsedMonitorMetadata) @@ -560,11 +566,12 @@ class XContentTests { val myMonitorInput = MyMonitorInput(1, "hello", MyMonitorInput(2, "world", null)) val myObjOut = BytesStreamOutput() myMonitorInput.writeTo(myObjOut) - val docLevelMonitorInput = DocLevelMonitorInput( - "test", - listOf("test"), - listOf(randomDocLevelQuery()) - ) + val docLevelMonitorInput = + DocLevelMonitorInput( + "test", + listOf("test"), + listOf(randomDocLevelQuery()), + ) val remoteDocLevelMonitorInput = RemoteDocLevelMonitorInput(myObjOut.bytes(), docLevelMonitorInput) val xContent = remoteDocLevelMonitorInput.toXContent(JsonXContent.contentBuilder(), ToXContent.EMPTY_PARAMS).string() @@ -577,16 +584,17 @@ class XContentTests { @Test fun `test DataSources parsing`() { - val dataSources = DataSources( - ScheduledJob.DOC_LEVEL_QUERIES_INDEX, - ".opensearch-alerting-finding-history-write", - "<.opensearch-alerting-finding-history-{now/d}-1>", - ".opendistro-alerting-alerts", - ".opendistro-alerting-alert-history-write", - "<.opendistro-alerting-alert-history-{now/d}-1>", - mapOf(), - false - ) + val dataSources = + DataSources( + ScheduledJob.DOC_LEVEL_QUERIES_INDEX, + ".opensearch-alerting-finding-history-write", + "<.opensearch-alerting-finding-history-{now/d}-1>", + ".opendistro-alerting-alerts", + ".opendistro-alerting-alert-history-write", + "<.opendistro-alerting-alert-history-{now/d}-1>", + mapOf(), + false, + ) Assertions.assertNotNull(dataSources) val dataSourcesString = dataSources.toXContent(builder(), ToXContent.EMPTY_PARAMS).string() @@ -596,15 +604,16 @@ class XContentTests { @Test fun `test Comment parsing`() { - val comment = Comment( - "123", - "456", - "alert", - "content", - Instant.now().truncatedTo(ChronoUnit.MILLIS), - null, - randomUser() - ) + val comment = + Comment( + "123", + "456", + "alert", + "content", + Instant.now().truncatedTo(ChronoUnit.MILLIS), + null, + randomUser(), + ) Assertions.assertNotNull(comment) val commentString = comment.toXContentWithUser(builder()).string() diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/action/ActionTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/action/ActionTests.kt index dcbf8998..de22fe0b 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/action/ActionTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/action/ActionTests.kt @@ -9,7 +9,6 @@ import org.opensearch.commons.alerting.model.action.Action.Companion.THROTTLE_EN import org.opensearch.commons.alerting.randomAction class ActionTests { - @Test fun `test action asTemplateArgs`() { val action = randomAction() @@ -19,22 +18,22 @@ class ActionTests { assertEquals( action.id, templateArgs[ID_FIELD], - "Template arg field 'id' doesn't match" + "Template arg field 'id' doesn't match", ) assertEquals( action.name, templateArgs[NAME_FIELD], - "Template arg field 'name' doesn't match" + "Template arg field 'name' doesn't match", ) assertEquals( action.destinationId, templateArgs[DESTINATION_ID_FIELD], - "Template arg field 'destinationId' doesn't match" + "Template arg field 'destinationId' doesn't match", ) assertEquals( action.throttleEnabled, templateArgs[THROTTLE_ENABLED_FIELD], - "Template arg field 'throttleEnabled' doesn't match" + "Template arg field 'throttleEnabled' doesn't match", ) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterfaceTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterfaceTests.kt index eeecb7f9..398a663d 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterfaceTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterfaceTests.kt @@ -55,7 +55,6 @@ import java.time.Instant @Suppress("UNCHECKED_CAST") @ExtendWith(MockitoExtension::class) internal class NotificationsPluginInterfaceTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) private lateinit var client: NodeClient @@ -126,14 +125,15 @@ internal class NotificationsPluginInterfaceTests { @Test fun getPluginFeatures() { val request = mock(GetPluginFeaturesRequest::class.java) - val response = GetPluginFeaturesResponse( - listOf("config_type_1", "config_type_2", "config_type_3"), - mapOf( - Pair("FeatureKey1", "FeatureValue1"), - Pair("FeatureKey2", "FeatureValue2"), - Pair("FeatureKey3", "FeatureValue3") + val response = + GetPluginFeaturesResponse( + listOf("config_type_1", "config_type_2", "config_type_3"), + mapOf( + Pair("FeatureKey1", "FeatureValue1"), + Pair("FeatureKey2", "FeatureValue2"), + Pair("FeatureKey3", "FeatureValue3"), + ), ) - ) val listener: ActionListener = mock(ActionListener::class.java) as ActionListener @@ -148,12 +148,13 @@ internal class NotificationsPluginInterfaceTests { @Test fun getChannelList() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.SLACK - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.SLACK, + ) val request = mock(GetChannelListRequest::class.java) val response = GetChannelListResponse(ChannelList(sampleConfig)) @@ -171,24 +172,27 @@ internal class NotificationsPluginInterfaceTests { @Test fun sendNotification() { - val notificationInfo = EventSource( - "title", - "reference_id", - SeverityType.HIGH, - listOf("tag1", "tag2") - ) - val channelMessage = ChannelMessage( - "text_description", - "htmlDescription", - null - ) + val notificationInfo = + EventSource( + "title", + "reference_id", + SeverityType.HIGH, + listOf("tag1", "tag2"), + ) + val channelMessage = + ChannelMessage( + "text_description", + "htmlDescription", + null, + ) - val sampleStatus = EventStatus( - "config_id", - "name", - ConfigType.SLACK, - deliveryStatus = DeliveryStatus("404", "invalid recipient") - ) + val sampleStatus = + EventStatus( + "config_id", + "name", + ConfigType.SLACK, + deliveryStatus = DeliveryStatus("404", "invalid recipient"), + ) val sampleEvent = NotificationEvent(notificationInfo, listOf(sampleStatus)) @@ -206,7 +210,7 @@ internal class NotificationsPluginInterfaceTests { notificationInfo, channelMessage, listOf("channelId1", "channelId2"), - listener + listener, ) verify(listener, times(1)).onResponse(eq(response)) } @@ -214,7 +218,14 @@ internal class NotificationsPluginInterfaceTests { @Test fun publishLegacyNotification() { val request = mock(LegacyPublishNotificationRequest::class.java) - val res = LegacyPublishNotificationResponse(LegacyDestinationResponse.Builder().withStatusCode(200).withResponseContent("Nice!").build()) + val res = + LegacyPublishNotificationResponse( + LegacyDestinationResponse + .Builder() + .withStatusCode(200) + .withResponseContent("Nice!") + .build(), + ) val l: ActionListener = mock(ActionListener::class.java) as ActionListener @@ -229,18 +240,20 @@ internal class NotificationsPluginInterfaceTests { private fun mockGetNotificationConfigResponse(): GetNotificationConfigResponse { val sampleSlack = Slack("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack - ) - val configInfo = NotificationConfigInfo( - "config_id", - Instant.now(), - Instant.now(), - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + ) + val configInfo = + NotificationConfigInfo( + "config_id", + Instant.now(), + Instant.now(), + sampleConfig, + ) return GetNotificationConfigResponse(NotificationConfigSearchResult(configInfo)) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequestTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequestTests.kt index 73c446ac..3e9c07b3 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequestTests.kt @@ -25,7 +25,6 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class CreateNotificationConfigRequestTests { - private fun createWebhookContentConfigObject(): NotificationConfig { val sampleWebhook = Webhook("https://domain.com/sample_webhook_url#1234567890") return NotificationConfig( @@ -33,7 +32,7 @@ internal class CreateNotificationConfigRequestTests { "description", ConfigType.WEBHOOK, configData = sampleWebhook, - isEnabled = true + isEnabled = true, ) } @@ -44,7 +43,7 @@ internal class CreateNotificationConfigRequestTests { "description", ConfigType.SLACK, configData = sampleSlack, - isEnabled = true + isEnabled = true, ) } @@ -55,9 +54,10 @@ internal class CreateNotificationConfigRequestTests { "description", ConfigType.CHIME, configData = sampleChime, - isEnabled = true + isEnabled = true, ) } + private fun createMicrosoftTeamsContentConfigObject(): NotificationConfig { val sampleMicrosoftTeams = MicrosoftTeams("https://domain.com/sample_microsoft_teams_url#1234567890") return NotificationConfig( @@ -65,7 +65,7 @@ internal class CreateNotificationConfigRequestTests { "description", ConfigType.MICROSOFT_TEAMS, configData = sampleMicrosoftTeams, - isEnabled = true + isEnabled = true, ) } @@ -76,50 +76,53 @@ internal class CreateNotificationConfigRequestTests { "description", ConfigType.EMAIL_GROUP, configData = sampleEmailGroup, - isEnabled = true + isEnabled = true, ) } private fun createEmailContentConfigObject(): NotificationConfig { - val sampleEmail = Email( - emailAccountID = "sample_1@dummy.com", - recipients = listOf(EmailRecipient("sample_2@dummy.com")), - emailGroupIds = listOf("sample_3@dummy.com") - ) + val sampleEmail = + Email( + emailAccountID = "sample_1@dummy.com", + recipients = listOf(EmailRecipient("sample_2@dummy.com")), + emailGroupIds = listOf("sample_3@dummy.com"), + ) return NotificationConfig( "name", "description", ConfigType.EMAIL, configData = sampleEmail, - isEnabled = true + isEnabled = true, ) } private fun createSmtpAccountContentConfigObject(): NotificationConfig { - val sampleSmtpAccount = SmtpAccount( - host = "http://dummy.com", - port = 11, - method = MethodType.SSL, - fromAddress = "sample@dummy.com" - ) + val sampleSmtpAccount = + SmtpAccount( + host = "http://dummy.com", + port = 11, + method = MethodType.SSL, + fromAddress = "sample@dummy.com", + ) return NotificationConfig( "name", "description", ConfigType.SMTP_ACCOUNT, configData = sampleSmtpAccount, - isEnabled = true + isEnabled = true, ) } @Test fun `Create config serialize and deserialize transport object should be equal webhook`() { - val configRequest = CreateNotificationConfigRequest( - createWebhookContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createWebhookContentConfigObject(), + ) val recreatedObject = recreateObject(configRequest) { CreateNotificationConfigRequest( - it + it, ) } assertNull(recreatedObject.validate()) @@ -128,13 +131,14 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize transport object should be equal microsoft teams`() { - val configRequest = CreateNotificationConfigRequest( - createMicrosoftTeamsContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createMicrosoftTeamsContentConfigObject(), + ) val recreatedObject = recreateObject(configRequest) { CreateNotificationConfigRequest( - it + it, ) } assertNull(recreatedObject.validate()) @@ -143,13 +147,14 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize transport object should be equal slack`() { - val configRequest = CreateNotificationConfigRequest( - createSlackContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createSlackContentConfigObject(), + ) val recreatedObject = recreateObject(configRequest) { CreateNotificationConfigRequest( - it + it, ) } assertNull(recreatedObject.validate()) @@ -158,13 +163,14 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize transport object should be equal chime`() { - val configRequest = CreateNotificationConfigRequest( - createChimeContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createChimeContentConfigObject(), + ) val recreatedObject = recreateObject(configRequest) { CreateNotificationConfigRequest( - it + it, ) } assertNull(recreatedObject.validate()) @@ -173,13 +179,14 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize transport object should be equal email`() { - val configRequest = CreateNotificationConfigRequest( - createEmailContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createEmailContentConfigObject(), + ) val recreatedObject = recreateObject(configRequest) { CreateNotificationConfigRequest( - it + it, ) } assertNull(recreatedObject.validate()) @@ -188,13 +195,14 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize transport object should be equal emailGroup`() { - val configRequest = CreateNotificationConfigRequest( - createEmailGroupContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createEmailGroupContentConfigObject(), + ) val recreatedObject = recreateObject(configRequest) { CreateNotificationConfigRequest( - it + it, ) } assertNull(recreatedObject.validate()) @@ -203,13 +211,14 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize transport object should be equal SmtpAccount`() { - val configRequest = CreateNotificationConfigRequest( - createSmtpAccountContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createSmtpAccountContentConfigObject(), + ) val recreatedObject = recreateObject(configRequest) { CreateNotificationConfigRequest( - it + it, ) } assertNull(recreatedObject.validate()) @@ -218,9 +227,10 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize using json object should be equal microsoft teams`() { - val configRequest = CreateNotificationConfigRequest( - createMicrosoftTeamsContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createMicrosoftTeamsContentConfigObject(), + ) val jsonString = getJsonString(configRequest) val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) @@ -228,9 +238,10 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize using json object should be equal`() { - val configRequest = CreateNotificationConfigRequest( - createWebhookContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createWebhookContentConfigObject(), + ) val jsonString = getJsonString(configRequest) val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) @@ -238,9 +249,10 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize using json object should be equal slack`() { - val configRequest = CreateNotificationConfigRequest( - createSlackContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createSlackContentConfigObject(), + ) val jsonString = getJsonString(configRequest) val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) @@ -248,9 +260,10 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize using json object should be equal chime`() { - val configRequest = CreateNotificationConfigRequest( - createChimeContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createChimeContentConfigObject(), + ) val jsonString = getJsonString(configRequest) val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) @@ -258,9 +271,10 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize using json object should be equal email`() { - val configRequest = CreateNotificationConfigRequest( - createEmailContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createEmailContentConfigObject(), + ) val jsonString = getJsonString(configRequest) val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) @@ -268,9 +282,10 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize using json object should be equal EmailGroup`() { - val configRequest = CreateNotificationConfigRequest( - createEmailGroupContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createEmailGroupContentConfigObject(), + ) val jsonString = getJsonString(configRequest) val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) @@ -278,9 +293,10 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config serialize and deserialize using json object should be equal SmtpAccount`() { - val configRequest = CreateNotificationConfigRequest( - createSmtpAccountContentConfigObject() - ) + val configRequest = + CreateNotificationConfigRequest( + createSmtpAccountContentConfigObject(), + ) val jsonString = getJsonString(configRequest) val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) @@ -289,25 +305,27 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config should deserialize json object using parser slack`() { val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") - val config = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack, - isEnabled = true - ) - - val jsonString = """ - { - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + val config = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + isEnabled = true, + ) + + val jsonString = + """ + { + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) } @@ -315,26 +333,28 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config should deserialize json object using parser microsoft teams`() { val sampleMicrosoftTeams = MicrosoftTeams("https://domain.com/sample_microsoft_teams_url#1234567890") - val config = NotificationConfig( - "name", - "description", - ConfigType.MICROSOFT_TEAMS, - configData = sampleMicrosoftTeams, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"microsoft_teams", - "is_enabled":true, - "microsoft_teams":{"url":"https://domain.com/sample_microsoft_teams_url#1234567890"} + val config = + NotificationConfig( + "name", + "description", + ConfigType.MICROSOFT_TEAMS, + configData = sampleMicrosoftTeams, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"microsoft_teams", + "is_enabled":true, + "microsoft_teams":{"url":"https://domain.com/sample_microsoft_teams_url#1234567890"} + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) } @@ -342,25 +362,27 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config should deserialize json object using parser webhook`() { val sampleWebhook = Webhook("https://domain.com/sample_webhook_url#1234567890") - val config = NotificationConfig( - "name", - "description", - ConfigType.WEBHOOK, - configData = sampleWebhook, - isEnabled = true - ) - - val jsonString = """ - { - "config":{ - "name":"name", - "description":"description", - "config_type":"webhook", - "is_enabled":true, - "webhook":{"url":"https://domain.com/sample_webhook_url#1234567890"} + val config = + NotificationConfig( + "name", + "description", + ConfigType.WEBHOOK, + configData = sampleWebhook, + isEnabled = true, + ) + + val jsonString = + """ + { + "config":{ + "name":"name", + "description":"description", + "config_type":"webhook", + "is_enabled":true, + "webhook":{"url":"https://domain.com/sample_webhook_url#1234567890"} + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) } @@ -368,26 +390,28 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config should deserialize json object using parser Chime`() { val sampleChime = Chime("https://domain.com/sample_chime_url#1234567890") - val config = NotificationConfig( - "name", - "description", - ConfigType.CHIME, - configData = sampleChime, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"chime", - "is_enabled":true, - "chime":{"url":"https://domain.com/sample_chime_url#1234567890"} + val config = + NotificationConfig( + "name", + "description", + ConfigType.CHIME, + configData = sampleChime, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"chime", + "is_enabled":true, + "chime":{"url":"https://domain.com/sample_chime_url#1234567890"} + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) } @@ -395,93 +419,101 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config should deserialize json object using parser Email Group`() { val sampleEmailGroup = EmailGroup(listOf(EmailRecipient("dummy@company.com"))) - val config = NotificationConfig( - "name", - "description", - ConfigType.EMAIL_GROUP, - configData = sampleEmailGroup, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"email_group", - "is_enabled":true, - "email_group":{"recipient_list":[{"recipient":"dummy@company.com"}]} + val config = + NotificationConfig( + "name", + "description", + ConfigType.EMAIL_GROUP, + configData = sampleEmailGroup, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"email_group", + "is_enabled":true, + "email_group":{"recipient_list":[{"recipient":"dummy@company.com"}]} + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) } @Test fun `Update config should deserialize json object using parser Email`() { - val sampleEmail = Email( - emailAccountID = "sample_1@dummy.com", - recipients = listOf(EmailRecipient("sample_2@dummy.com")), - emailGroupIds = listOf("sample_3@dummy.com") - ) - val config = NotificationConfig( - "name", - "description", - ConfigType.EMAIL, - configData = sampleEmail, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"email", - "is_enabled":true, - "email":{ - "email_account_id":"sample_1@dummy.com", - "recipient_list":[{"recipient":"sample_2@dummy.com"}], - "email_group_id_list":["sample_3@dummy.com"] + val sampleEmail = + Email( + emailAccountID = "sample_1@dummy.com", + recipients = listOf(EmailRecipient("sample_2@dummy.com")), + emailGroupIds = listOf("sample_3@dummy.com"), + ) + val config = + NotificationConfig( + "name", + "description", + ConfigType.EMAIL, + configData = sampleEmail, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"email", + "is_enabled":true, + "email":{ + "email_account_id":"sample_1@dummy.com", + "recipient_list":[{"recipient":"sample_2@dummy.com"}], + "email_group_id_list":["sample_3@dummy.com"] + } } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) } @Test fun `Update config should deserialize json object using parser SmtpAccount`() { - val sampleSmtpAccount = SmtpAccount( - host = "http://dummy.com", - port = 11, - method = MethodType.SSL, - fromAddress = "sample@dummy.com" - ) - val config = NotificationConfig( - "name", - "description", - ConfigType.SMTP_ACCOUNT, - configData = sampleSmtpAccount, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"smtp_account", - "is_enabled":true, - "smtp_account":{"host":"http://dummy.com", "port":11,"method": "ssl", "from_address": "sample@dummy.com" } + val sampleSmtpAccount = + SmtpAccount( + host = "http://dummy.com", + port = 11, + method = MethodType.SSL, + fromAddress = "sample@dummy.com", + ) + val config = + NotificationConfig( + "name", + "description", + ConfigType.SMTP_ACCOUNT, + configData = sampleSmtpAccount, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"smtp_account", + "is_enabled":true, + "smtp_account":{"host":"http://dummy.com", "port":11,"method": "ssl", "from_address": "sample@dummy.com" } + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) } @@ -495,23 +527,25 @@ internal class CreateNotificationConfigRequestTests { } private fun validateSpecialCharsInIdFails(char: Char) { - val str = when (char) { - '"' -> "\\\"" - '\\' -> "\\\\" - else -> "$char" - } - val jsonString = """ - { - "config_id":"config_id1$str", - "config":{ - "name":"name", - "description":"description", - "config_type":"chime", - "is_enabled":true, - "chime":{"url":"https://domain.com/sample_chime_url#1234567890"} + val str = + when (char) { + '"' -> "\\\"" + '\\' -> "\\\\" + else -> "$char" } - } - """.trimIndent() + val jsonString = + """ + { + "config_id":"config_id1$str", + "config":{ + "name":"name", + "description":"description", + "config_type":"chime", + "is_enabled":true, + "chime":{"url":"https://domain.com/sample_chime_url#1234567890"} + } + } + """.trimIndent() assertThrows("Should not accept char:$char") { createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } } @@ -527,28 +561,30 @@ internal class CreateNotificationConfigRequestTests { @Test fun `Create config should safely ignore extra field in json object`() { val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") - val config = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack, - isEnabled = true - ) - - val jsonString = """ - { - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"}, - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" + val config = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + isEnabled = true, + ) + + val jsonString = + """ + { + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"}, + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigResponseTests.kt index 0f580fcd..9518aa86 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigResponseTests.kt @@ -13,7 +13,6 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class CreateNotificationConfigResponseTests { - @Test fun `Create response serialize and deserialize transport object should be equal`() { val configResponse = CreateNotificationConfigResponse("sample_config_id") @@ -56,14 +55,15 @@ internal class CreateNotificationConfigResponseTests { @Test fun `Create response should safely ignore extra field in json object`() { val configId = "sample_config_id" - val jsonString = """ - { - "config_id":"$configId", - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "config_id":"$configId", + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigResponse.parse(it) } assertEquals(configId, recreatedObject.configId) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigRequestTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigRequestTests.kt index c44d1458..329f858d 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigRequestTests.kt @@ -13,7 +13,6 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class DeleteNotificationConfigRequestTests { - @Test fun `Delete request serialize and deserialize transport object should be equal`() { val deleteRequest = DeleteNotificationConfigRequest(setOf("sample_config_id")) @@ -33,11 +32,12 @@ internal class DeleteNotificationConfigRequestTests { fun `Delete request should deserialize json object using parser`() { val configId = "sample_config_id" val configIds = setOf(configId) - val jsonString = """ - { - "config_id_list":["$configId"] - } - """.trimIndent() + val jsonString = + """ + { + "config_id_list":["$configId"] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { DeleteNotificationConfigRequest.parse(it) } assertEquals(configIds, recreatedObject.configIds) } @@ -52,11 +52,12 @@ internal class DeleteNotificationConfigRequestTests { @Test fun `Delete request should throw exception when config_id_lists is replace with config_id_lists2 in json object`() { - val jsonString = """ - { - "config_id_lists":["sample_config_id"] - } - """.trimIndent() + val jsonString = + """ + { + "config_id_lists":["sample_config_id"] + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { DeleteNotificationConfigRequest.parse(it) } } @@ -66,14 +67,15 @@ internal class DeleteNotificationConfigRequestTests { fun `Delete request should safely ignore extra field in json object`() { val configId = "sample_config_id" val configIds = setOf(configId) - val jsonString = """ - { - "config_id_list":["$configId"], - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "config_id_list":["$configId"], + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { DeleteNotificationConfigRequest.parse(it) } assertEquals(configIds, recreatedObject.configIds) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigResponseTests.kt index a05fbca5..693b4bc5 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/DeleteNotificationConfigResponseTests.kt @@ -14,7 +14,6 @@ import org.opensearch.commons.utils.recreateObject import org.opensearch.core.rest.RestStatus internal class DeleteNotificationConfigResponseTests { - @Test fun `Delete response serialize and deserialize transport object should be equal`() { val configResponse = DeleteNotificationConfigResponse(mapOf(Pair("sample_config_id", RestStatus.OK))) @@ -34,13 +33,14 @@ internal class DeleteNotificationConfigResponseTests { fun `Delete response should deserialize json object using parser`() { val configId = "sample_config_id" val configResponse = DeleteNotificationConfigResponse(mapOf(Pair(configId, RestStatus.OK))) - val jsonString = """ - { - "delete_response_list":{ - "$configId":"OK" + val jsonString = + """ + { + "delete_response_list":{ + "$configId":"OK" + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { DeleteNotificationConfigResponse.parse(it) } assertEquals(configResponse.configIdToStatus, recreatedObject.configIdToStatus) } @@ -65,16 +65,17 @@ internal class DeleteNotificationConfigResponseTests { fun `Delete response should safely ignore extra field in json object`() { val configId = "sample_config_id" val configResponse = DeleteNotificationConfigResponse(mapOf(Pair(configId, RestStatus.OK))) - val jsonString = """ - { - "delete_response_list":{ - "$configId":"OK" - }, - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "delete_response_list":{ + "$configId":"OK" + }, + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { DeleteNotificationConfigResponse.parse(it) } assertEquals(configResponse.configIdToStatus, recreatedObject.configIdToStatus) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/GetChannelListRequestTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/GetChannelListRequestTests.kt index aaa29e21..50f3fcca 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/GetChannelListRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/GetChannelListRequestTests.kt @@ -13,10 +13,9 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class GetChannelListRequestTests { - private fun assertGetRequestEquals( expected: GetChannelListRequest, - actual: GetChannelListRequest + actual: GetChannelListRequest, ) { assertEquals(expected.compact, actual.compact) } @@ -47,13 +46,14 @@ internal class GetChannelListRequestTests { @Test fun `Get request should safely ignore extra field in json object`() { val configRequest = GetChannelListRequest() - val jsonString = """ - { - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetChannelListRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/GetChannelListResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/GetChannelListResponseTests.kt index 4f19ab4b..f6f8019f 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/GetChannelListResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/GetChannelListResponseTests.kt @@ -16,10 +16,9 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class GetChannelListResponseTests { - private fun assertSearchResultEquals( expected: ChannelList, - actual: ChannelList + actual: ChannelList, ) { assertEquals(expected.startIndex, actual.startIndex) assertEquals(expected.totalHits, actual.totalHits) @@ -30,12 +29,13 @@ internal class GetChannelListResponseTests { @Test fun `Get Response serialize and deserialize with config object should be equal`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.SLACK - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.SLACK, + ) val searchResult = ChannelList(sampleConfig) val getResponse = GetChannelListResponse(searchResult) val recreatedObject = recreateObject(getResponse) { GetChannelListResponse(it) } @@ -44,36 +44,41 @@ internal class GetChannelListResponseTests { @Test fun `Get Response serialize and deserialize with multiple config object should be equal`() { - val sampleConfig1 = Channel( - "config_id1", - "name1", - "description1", - ConfigType.SLACK - ) - val sampleConfig2 = Channel( - "config_id2", - "name2", - "description2", - ConfigType.CHIME - ) - val sampleConfig3 = Channel( - "config_id3", - "name3", - "description3", - ConfigType.WEBHOOK - ) - val sampleConfig4 = Channel( - "config_id5", - "name4", - "description4", - ConfigType.MICROSOFT_TEAMS - ) - val searchResult = ChannelList( - 100, - 1000, - TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, - listOf(sampleConfig1, sampleConfig2, sampleConfig3, sampleConfig4) - ) + val sampleConfig1 = + Channel( + "config_id1", + "name1", + "description1", + ConfigType.SLACK, + ) + val sampleConfig2 = + Channel( + "config_id2", + "name2", + "description2", + ConfigType.CHIME, + ) + val sampleConfig3 = + Channel( + "config_id3", + "name3", + "description3", + ConfigType.WEBHOOK, + ) + val sampleConfig4 = + Channel( + "config_id5", + "name4", + "description4", + ConfigType.MICROSOFT_TEAMS, + ) + val searchResult = + ChannelList( + 100, + 1000, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, + listOf(sampleConfig1, sampleConfig2, sampleConfig3, sampleConfig4), + ) val getResponse = GetChannelListResponse(searchResult) val recreatedObject = recreateObject(getResponse) { GetChannelListResponse(it) } assertSearchResultEquals(searchResult, recreatedObject.searchResult) @@ -81,12 +86,13 @@ internal class GetChannelListResponseTests { @Test fun `Get Response serialize and deserialize using json config object should be equal`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.EMAIL_GROUP - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.EMAIL_GROUP, + ) val searchResult = ChannelList(sampleConfig) val getResponse = GetChannelListResponse(searchResult) val jsonString = getJsonString(getResponse) @@ -96,36 +102,41 @@ internal class GetChannelListResponseTests { @Test fun `Get Response serialize and deserialize using json with multiple config object should be equal`() { - val sampleConfig1 = Channel( - "config_id1", - "name1", - "description1", - ConfigType.SLACK - ) - val sampleConfig2 = Channel( - "config_id2", - "name2", - "description2", - ConfigType.CHIME - ) - val sampleConfig3 = Channel( - "config_id3", - "name3", - "description3", - ConfigType.WEBHOOK - ) - val sampleConfig4 = Channel( - "config_id5", - "name4", - "description4", - ConfigType.MICROSOFT_TEAMS - ) - val searchResult = ChannelList( - 100, - 1000, - TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, - listOf(sampleConfig1, sampleConfig2, sampleConfig3, sampleConfig4) - ) + val sampleConfig1 = + Channel( + "config_id1", + "name1", + "description1", + ConfigType.SLACK, + ) + val sampleConfig2 = + Channel( + "config_id2", + "name2", + "description2", + ConfigType.CHIME, + ) + val sampleConfig3 = + Channel( + "config_id3", + "name3", + "description3", + ConfigType.WEBHOOK, + ) + val sampleConfig4 = + Channel( + "config_id5", + "name4", + "description4", + ConfigType.MICROSOFT_TEAMS, + ) + val searchResult = + ChannelList( + 100, + 1000, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, + listOf(sampleConfig1, sampleConfig2, sampleConfig3, sampleConfig4), + ) val getResponse = GetChannelListResponse(searchResult) val jsonString = getJsonString(getResponse) val recreatedObject = createObjectFromJsonString(jsonString) { GetChannelListResponse.parse(it) } @@ -134,100 +145,107 @@ internal class GetChannelListResponseTests { @Test fun `Get Response should use isEnabled=true if absent in json object`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.EMAIL, - true - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.EMAIL, + true, + ) val searchResult = ChannelList(sampleConfig) - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq", - "channel_list":[ - { - "config_id":"config_id", - "name":"name", - "description":"description", - "config_type":"email" - } - ] - } - """.trimIndent() + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq", + "channel_list":[ + { + "config_id":"config_id", + "name":"name", + "description":"description", + "config_type":"email" + } + ] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetChannelListResponse.parse(it) } assertSearchResultEquals(searchResult, recreatedObject.searchResult) } @Test fun `Get Response should safely ignore extra field in json object`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.EMAIL - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.EMAIL, + ) val searchResult = ChannelList(sampleConfig) - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq", - "channel_list":[ - { - "config_id":"config_id", - "name":"name", - "description":"description", - "config_type":"email", - "is_enabled":true - } - ], - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq", + "channel_list":[ + { + "config_id":"config_id", + "name":"name", + "description":"description", + "config_type":"email", + "is_enabled":true + } + ], + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetChannelListResponse.parse(it) } assertSearchResultEquals(searchResult, recreatedObject.searchResult) } @Test fun `Get Response should safely fallback to default if startIndex, totalHits or totalHitRelation field absent in json object`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.EMAIL - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.EMAIL, + ) val searchResult = ChannelList(sampleConfig) - val jsonString = """ - { - "channel_list":[ - { - "config_id":"config_id", - "name":"name", - "description":"description", - "config_type":"email", - "is_enabled":true - } - ] - } - """.trimIndent() + val jsonString = + """ + { + "channel_list":[ + { + "config_id":"config_id", + "name":"name", + "description":"description", + "config_type":"email", + "is_enabled":true + } + ] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetChannelListResponse.parse(it) } assertSearchResultEquals(searchResult, recreatedObject.searchResult) } @Test fun `Get Response should throw exception if channelList is absent in json`() { - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq" - } - """.trimIndent() + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq" + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { GetChannelListResponse.parse(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigRequestTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigRequestTests.kt index 8873202d..cbe30b06 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigRequestTests.kt @@ -14,10 +14,9 @@ import org.opensearch.commons.utils.recreateObject import org.opensearch.search.sort.SortOrder internal class GetNotificationConfigRequestTests { - private fun assertGetRequestEquals( expected: GetNotificationConfigRequest, - actual: GetNotificationConfigRequest + actual: GetNotificationConfigRequest, ) { assertEquals(expected.configIds, actual.configIds) assertEquals(expected.fromIndex, actual.fromIndex) @@ -29,28 +28,30 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request serialize and deserialize transport object should be equal`() { - val configRequest = GetNotificationConfigRequest( - setOf("sample_config_id"), - 0, - 10, - "sortField", - SortOrder.DESC, - mapOf(Pair("filterKey", "filterValue")) - ) + val configRequest = + GetNotificationConfigRequest( + setOf("sample_config_id"), + 0, + 10, + "sortField", + SortOrder.DESC, + mapOf(Pair("filterKey", "filterValue")), + ) val recreatedObject = recreateObject(configRequest) { GetNotificationConfigRequest(it) } assertGetRequestEquals(configRequest, recreatedObject) } @Test fun `Get request serialize and deserialize using json object should be equal`() { - val configRequest = GetNotificationConfigRequest( - setOf("sample_config_id"), - 0, - 10, - "sortField", - SortOrder.ASC, - mapOf(Pair("filterKey", "filterValue")) - ) + val configRequest = + GetNotificationConfigRequest( + setOf("sample_config_id"), + 0, + 10, + "sortField", + SortOrder.ASC, + mapOf(Pair("filterKey", "filterValue")), + ) val jsonString = getJsonString(configRequest) val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) @@ -58,34 +59,36 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request with all field should deserialize json object using parser`() { - val configRequest = GetNotificationConfigRequest( - setOf("sample_config_id"), - 10, - 100, - "sortField", - SortOrder.DESC, - mapOf( - Pair("filterKey1", "filterValue1"), - Pair("filterKey2", "true"), - Pair("filterKey3", "filter,Value,3"), - Pair("filterKey4", "4") + val configRequest = + GetNotificationConfigRequest( + setOf("sample_config_id"), + 10, + 100, + "sortField", + SortOrder.DESC, + mapOf( + Pair("filterKey1", "filterValue1"), + Pair("filterKey2", "true"), + Pair("filterKey3", "filter,Value,3"), + Pair("filterKey4", "4"), + ), ) - ) - val jsonString = """ - { - "config_id_list":["${configRequest.configIds.first()}"], - "from_index":"10", - "max_items":"100", - "sort_field":"sortField", - "sort_order":"desc", - "filter_param_list": { - "filterKey1":"filterValue1", - "filterKey2":"true", - "filterKey3":"filter,Value,3", - "filterKey4":"4" + val jsonString = + """ + { + "config_id_list":["${configRequest.configIds.first()}"], + "from_index":"10", + "max_items":"100", + "sort_field":"sortField", + "sort_order":"desc", + "filter_param_list": { + "filterKey1":"filterValue1", + "filterKey2":"true", + "filterKey3":"filter,Value,3", + "filterKey4":"4" + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @@ -93,11 +96,12 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request with only config_id field should deserialize json object using parser`() { val configRequest = GetNotificationConfigRequest(configIds = setOf("sample_config_id")) - val jsonString = """ - { - "config_id_list":["${configRequest.configIds.first()}"] - } - """.trimIndent() + val jsonString = + """ + { + "config_id_list":["${configRequest.configIds.first()}"] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @@ -105,11 +109,12 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request with only from_index field should deserialize json object using parser`() { val configRequest = GetNotificationConfigRequest(fromIndex = 20) - val jsonString = """ - { - "from_index":"20" - } - """.trimIndent() + val jsonString = + """ + { + "from_index":"20" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @@ -117,11 +122,12 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request with only max_items field should deserialize json object using parser`() { val configRequest = GetNotificationConfigRequest(maxItems = 100) - val jsonString = """ - { - "max_items":"100" - } - """.trimIndent() + val jsonString = + """ + { + "max_items":"100" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @@ -129,11 +135,12 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request with only sort_field field should deserialize json object using parser`() { val configRequest = GetNotificationConfigRequest(sortField = "sample_sort_field") - val jsonString = """ - { - "sort_field":"sample_sort_field" - } - """.trimIndent() + val jsonString = + """ + { + "sort_field":"sample_sort_field" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @@ -141,11 +148,12 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request with only sort_order=asc field should deserialize json object using parser`() { val configRequest = GetNotificationConfigRequest(sortOrder = SortOrder.ASC) - val jsonString = """ - { - "sort_order":"asc" - } - """.trimIndent() + val jsonString = + """ + { + "sort_order":"asc" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @@ -153,11 +161,12 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request with only sort_order=ASC field should deserialize json object using parser`() { val configRequest = GetNotificationConfigRequest(sortOrder = SortOrder.ASC) - val jsonString = """ - { - "sort_order":"ASC" - } - """.trimIndent() + val jsonString = + """ + { + "sort_order":"ASC" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @@ -165,11 +174,12 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request with only sort_order=desc field should deserialize json object using parser`() { val configRequest = GetNotificationConfigRequest(sortOrder = SortOrder.DESC) - val jsonString = """ - { - "sort_order":"desc" - } - """.trimIndent() + val jsonString = + """ + { + "sort_order":"desc" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @@ -177,22 +187,24 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request with only sort_order=DESC field should deserialize json object using parser`() { val configRequest = GetNotificationConfigRequest(sortOrder = SortOrder.DESC) - val jsonString = """ - { - "sort_order":"DESC" - } - """.trimIndent() + val jsonString = + """ + { + "sort_order":"DESC" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @Test fun `Get request with invalid sort_order should throw exception`() { - val jsonString = """ - { - "sort_order":"descending" - } - """.trimIndent() + val jsonString = + """ + { + "sort_order":"descending" + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } } @@ -200,24 +212,27 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request with only filter_param_list field should deserialize json object using parser`() { - val configRequest = GetNotificationConfigRequest( - filterParams = mapOf( - Pair("filterKey1", "filterValue1"), - Pair("filterKey2", "true"), - Pair("filterKey3", "filter,Value,3"), - Pair("filterKey4", "4") + val configRequest = + GetNotificationConfigRequest( + filterParams = + mapOf( + Pair("filterKey1", "filterValue1"), + Pair("filterKey2", "true"), + Pair("filterKey3", "filter,Value,3"), + Pair("filterKey4", "4"), + ), ) - ) - val jsonString = """ - { - "filter_param_list": { - "filterKey1":"filterValue1", - "filterKey2":"true", - "filterKey3":"filter,Value,3", - "filterKey4":"4" + val jsonString = + """ + { + "filter_param_list": { + "filterKey1":"filterValue1", + "filterKey2":"true", + "filterKey3":"filter,Value,3", + "filterKey4":"4" + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @@ -225,10 +240,11 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request no field should deserialize json object using parser`() { val configRequest = GetNotificationConfigRequest() - val jsonString = """ - { - } - """.trimIndent() + val jsonString = + """ + { + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } @@ -244,14 +260,15 @@ internal class GetNotificationConfigRequestTests { @Test fun `Get request should safely ignore extra field in json object`() { val configRequest = GetNotificationConfigRequest(configIds = setOf("sample_config_id")) - val jsonString = """ - { - "config_id_list":["${configRequest.configIds.first()}"], - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "config_id_list":["${configRequest.configIds.first()}"], + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigRequest.parse(it) } assertGetRequestEquals(configRequest, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigResponseTests.kt index a0c025ac..bc981bd9 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/GetNotificationConfigResponseTests.kt @@ -21,10 +21,9 @@ import org.opensearch.commons.utils.recreateObject import java.time.Instant internal class GetNotificationConfigResponseTests { - private fun assertSearchResultEquals( expected: NotificationConfigSearchResult, - actual: NotificationConfigSearchResult + actual: NotificationConfigSearchResult, ) { assertEquals(expected.startIndex, actual.startIndex) assertEquals(expected.totalHits, actual.totalHits) @@ -36,18 +35,20 @@ internal class GetNotificationConfigResponseTests { @Test fun `Search result serialize and deserialize with config object should be equal`() { val sampleSlack = Slack("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack - ) - val configInfo = NotificationConfigInfo( - "config_id", - Instant.now(), - Instant.now(), - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + ) + val configInfo = + NotificationConfigInfo( + "config_id", + Instant.now(), + Instant.now(), + sampleConfig, + ) val searchResult = NotificationConfigSearchResult(configInfo) val searchResponse = GetNotificationConfigResponse(searchResult) val recreatedObject = recreateObject(searchResponse) { GetNotificationConfigResponse(it) } @@ -56,48 +57,55 @@ internal class GetNotificationConfigResponseTests { @Test fun `Search result serialize and deserialize with multiple config object should be equal`() { - val sampleConfig1 = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = Slack("https://domain.com/sample_url#1234567890") - ) - val configInfo1 = NotificationConfigInfo( - "config_id1", - Instant.now(), - Instant.now(), - sampleConfig1 - ) - val sampleConfig2 = NotificationConfig( - "name", - "description", - ConfigType.CHIME, - configData = Chime("https://domain.com/sample_url#1234567890") - ) - val configInfo2 = NotificationConfigInfo( - "config_id2", - Instant.now(), - Instant.now(), - sampleConfig2 - ) - val sampleConfig3 = NotificationConfig( - "name", - "description", - ConfigType.MICROSOFT_TEAMS, - configData = MicrosoftTeams("https://domain.com/sample_url#1234567890") - ) - val configInfo3 = NotificationConfigInfo( - "config_id3", - Instant.now(), - Instant.now(), - sampleConfig3 - ) - val searchResult = NotificationConfigSearchResult( - 100, - 1000, - TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, - listOf(configInfo1, configInfo2, configInfo3) - ) + val sampleConfig1 = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = Slack("https://domain.com/sample_url#1234567890"), + ) + val configInfo1 = + NotificationConfigInfo( + "config_id1", + Instant.now(), + Instant.now(), + sampleConfig1, + ) + val sampleConfig2 = + NotificationConfig( + "name", + "description", + ConfigType.CHIME, + configData = Chime("https://domain.com/sample_url#1234567890"), + ) + val configInfo2 = + NotificationConfigInfo( + "config_id2", + Instant.now(), + Instant.now(), + sampleConfig2, + ) + val sampleConfig3 = + NotificationConfig( + "name", + "description", + ConfigType.MICROSOFT_TEAMS, + configData = MicrosoftTeams("https://domain.com/sample_url#1234567890"), + ) + val configInfo3 = + NotificationConfigInfo( + "config_id3", + Instant.now(), + Instant.now(), + sampleConfig3, + ) + val searchResult = + NotificationConfigSearchResult( + 100, + 1000, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, + listOf(configInfo1, configInfo2, configInfo3), + ) val searchResponse = GetNotificationConfigResponse(searchResult) val recreatedObject = recreateObject(searchResponse) { GetNotificationConfigResponse(it) } assertSearchResultEquals(searchResult, recreatedObject.searchResult) @@ -108,18 +116,20 @@ internal class GetNotificationConfigResponseTests { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) val sampleSlack = Slack("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack - ) - val configInfo = NotificationConfigInfo( - "config_id", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + ) + val configInfo = + NotificationConfigInfo( + "config_id", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig, + ) val searchResult = NotificationConfigSearchResult(configInfo) val searchResponse = GetNotificationConfigResponse(searchResult) val jsonString = getJsonString(searchResponse) @@ -131,48 +141,55 @@ internal class GetNotificationConfigResponseTests { fun `Search result serialize and deserialize using json with multiple config object should be equal`() { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) - val sampleConfig1 = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = Slack("https://domain.com/sample_url#1234567890") - ) - val configInfo1 = NotificationConfigInfo( - "config_id1", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig1 - ) - val sampleConfig2 = NotificationConfig( - "name", - "description", - ConfigType.CHIME, - configData = Chime("https://domain.com/sample_url#1234567890") - ) - val configInfo2 = NotificationConfigInfo( - "config_id2", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig2 - ) - val sampleConfig3 = NotificationConfig( - "name", - "description", - ConfigType.MICROSOFT_TEAMS, - configData = MicrosoftTeams("https://domain.com/sample_url#1234567890") - ) - val configInfo3 = NotificationConfigInfo( - "config_id3", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig3 - ) - val searchResult = NotificationConfigSearchResult( - 100, - 1000, - TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, - listOf(configInfo1, configInfo2, configInfo3) - ) + val sampleConfig1 = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = Slack("https://domain.com/sample_url#1234567890"), + ) + val configInfo1 = + NotificationConfigInfo( + "config_id1", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig1, + ) + val sampleConfig2 = + NotificationConfig( + "name", + "description", + ConfigType.CHIME, + configData = Chime("https://domain.com/sample_url#1234567890"), + ) + val configInfo2 = + NotificationConfigInfo( + "config_id2", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig2, + ) + val sampleConfig3 = + NotificationConfig( + "name", + "description", + ConfigType.MICROSOFT_TEAMS, + configData = MicrosoftTeams("https://domain.com/sample_url#1234567890"), + ) + val configInfo3 = + NotificationConfigInfo( + "config_id3", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig3, + ) + val searchResult = + NotificationConfigSearchResult( + 100, + 1000, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, + listOf(configInfo1, configInfo2, configInfo3), + ) val searchResponse = GetNotificationConfigResponse(searchResult) val jsonString = getJsonString(searchResponse) val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigResponse.parse(it) } @@ -184,44 +201,47 @@ internal class GetNotificationConfigResponseTests { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack, - isEnabled = true - ) - val configInfo = NotificationConfigInfo( - "config-Id", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + isEnabled = true, + ) + val configInfo = + NotificationConfigInfo( + "config-Id", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig, + ) val searchResult = NotificationConfigSearchResult(configInfo) - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq", - "config_list":[ - { - "config_id":"config-Id", - "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", - "created_time_ms":"${createdTimeMs.toEpochMilli()}", - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq", + "config_list":[ + { + "config_id":"config-Id", + "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", + "created_time_ms":"${createdTimeMs.toEpochMilli()}", + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + } } - } - ], - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + ], + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigResponse.parse(it) } assertSearchResultEquals(searchResult, recreatedObject.searchResult) } @@ -231,38 +251,41 @@ internal class GetNotificationConfigResponseTests { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack, - isEnabled = true - ) - val configInfo = NotificationConfigInfo( - "config-Id", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + isEnabled = true, + ) + val configInfo = + NotificationConfigInfo( + "config-Id", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig, + ) val searchResult = NotificationConfigSearchResult(configInfo) - val jsonString = """ - { - "config_list":[ - { - "config_id":"config-Id", - "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", - "created_time_ms":"${createdTimeMs.toEpochMilli()}", - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + val jsonString = + """ + { + "config_list":[ + { + "config_id":"config-Id", + "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", + "created_time_ms":"${createdTimeMs.toEpochMilli()}", + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + } } - } - ] - } - """.trimIndent() + ] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetNotificationConfigResponse.parse(it) } assertSearchResultEquals(searchResult, recreatedObject.searchResult) } @@ -271,20 +294,21 @@ internal class GetNotificationConfigResponseTests { fun `Search result should throw exception if notificationConfigs is absent in json`() { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq", - "config_list":[ - { - "config_id":"config-Id", - "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", - "created_time_ms":"${createdTimeMs.toEpochMilli()}" - } - ] - } - """.trimIndent() + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq", + "config_list":[ + { + "config_id":"config-Id", + "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", + "created_time_ms":"${createdTimeMs.toEpochMilli()}" + } + ] + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { GetNotificationConfigResponse.parse(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesRequestTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesRequestTests.kt index 1c85ed70..f024c7c7 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesRequestTests.kt @@ -13,10 +13,9 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class GetPluginFeaturesRequestTests { - private fun assertGetRequestEquals( expected: GetPluginFeaturesRequest, - actual: GetPluginFeaturesRequest + actual: GetPluginFeaturesRequest, ) { assertEquals(expected.compact, actual.compact) } @@ -47,13 +46,14 @@ internal class GetPluginFeaturesRequestTests { @Test fun `Get request should safely ignore extra field in json object`() { val request = GetPluginFeaturesRequest() - val jsonString = """ - { - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetPluginFeaturesRequest.parse(it) } assertGetRequestEquals(request, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesResponseTests.kt index 1aa065a2..07111d82 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/GetPluginFeaturesResponseTests.kt @@ -12,10 +12,9 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class GetPluginFeaturesResponseTests { - private fun assertResponseEquals( expected: GetPluginFeaturesResponse, - actual: GetPluginFeaturesResponse + actual: GetPluginFeaturesResponse, ) { assertEquals(expected.allowedConfigTypeList, actual.allowedConfigTypeList) assertEquals(expected.pluginFeatures, actual.pluginFeatures) @@ -23,28 +22,30 @@ internal class GetPluginFeaturesResponseTests { @Test fun `Get Response serialize and deserialize transport object should be equal`() { - val response = GetPluginFeaturesResponse( - listOf("config_type_1", "config_type_2", "config_type_3"), - mapOf( - Pair("FeatureKey1", "FeatureValue1"), - Pair("FeatureKey2", "FeatureValue2"), - Pair("FeatureKey3", "FeatureValue3") + val response = + GetPluginFeaturesResponse( + listOf("config_type_1", "config_type_2", "config_type_3"), + mapOf( + Pair("FeatureKey1", "FeatureValue1"), + Pair("FeatureKey2", "FeatureValue2"), + Pair("FeatureKey3", "FeatureValue3"), + ), ) - ) val recreatedObject = recreateObject(response) { GetPluginFeaturesResponse(it) } assertResponseEquals(response, recreatedObject) } @Test fun `Get Response serialize and deserialize using json config object should be equal`() { - val response = GetPluginFeaturesResponse( - listOf("config_type_1", "config_type_2", "config_type_3"), - mapOf( - Pair("FeatureKey1", "FeatureValue1"), - Pair("FeatureKey2", "FeatureValue2"), - Pair("FeatureKey3", "FeatureValue3") + val response = + GetPluginFeaturesResponse( + listOf("config_type_1", "config_type_2", "config_type_3"), + mapOf( + Pair("FeatureKey1", "FeatureValue1"), + Pair("FeatureKey2", "FeatureValue2"), + Pair("FeatureKey3", "FeatureValue3"), + ), ) - ) val jsonString = getJsonString(response) val recreatedObject = createObjectFromJsonString(jsonString) { GetPluginFeaturesResponse.parse(it) } assertResponseEquals(response, recreatedObject) @@ -52,42 +53,45 @@ internal class GetPluginFeaturesResponseTests { @Test fun `Get Response should safely ignore extra field in json object`() { - val response = GetPluginFeaturesResponse( - listOf("config_type_1", "config_type_2", "config_type_3"), - mapOf( - Pair("FeatureKey1", "FeatureValue1"), - Pair("FeatureKey2", "FeatureValue2"), - Pair("FeatureKey3", "FeatureValue3") + val response = + GetPluginFeaturesResponse( + listOf("config_type_1", "config_type_2", "config_type_3"), + mapOf( + Pair("FeatureKey1", "FeatureValue1"), + Pair("FeatureKey2", "FeatureValue2"), + Pair("FeatureKey3", "FeatureValue3"), + ), ) - ) - val jsonString = """ - { - "allowed_config_type_list":["config_type_1", "config_type_2", "config_type_3"], - "plugin_features":{ - "FeatureKey1":"FeatureValue1", - "FeatureKey2":"FeatureValue2", - "FeatureKey3":"FeatureValue3" - }, - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "allowed_config_type_list":["config_type_1", "config_type_2", "config_type_3"], + "plugin_features":{ + "FeatureKey1":"FeatureValue1", + "FeatureKey2":"FeatureValue2", + "FeatureKey3":"FeatureValue3" + }, + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { GetPluginFeaturesResponse.parse(it) } assertResponseEquals(response, recreatedObject) } @Test fun `Get Response should throw exception if allowed_config_type_list is absent in json`() { - val jsonString = """ - { - "plugin_features":{ - "FeatureKey1":"FeatureValue1", - "FeatureKey2":"FeatureValue2", - "FeatureKey3":"FeatureValue3" + val jsonString = + """ + { + "plugin_features":{ + "FeatureKey1":"FeatureValue1", + "FeatureKey2":"FeatureValue2", + "FeatureKey3":"FeatureValue3" + } } - } - """.trimIndent() + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { GetPluginFeaturesResponse.parse(it) } } @@ -95,11 +99,12 @@ internal class GetPluginFeaturesResponseTests { @Test fun `Get Response should throw exception if plugin_features is absent in json`() { - val jsonString = """ - { - "config_type_list":["config_type_1", "config_type_2", "config_type_3"] - } - """.trimIndent() + val jsonString = + """ + { + "config_type_list":["config_type_1", "config_type_2", "config_type_3"] + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { GetPluginFeaturesResponse.parse(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationRequestTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationRequestTests.kt index e4b990a5..1a5ce8a8 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationRequestTests.kt @@ -12,10 +12,9 @@ import org.opensearch.commons.destination.message.LegacyChimeMessage import org.opensearch.commons.utils.recreateObject internal class LegacyPublishNotificationRequestTests { - private fun assertRequestEquals( expected: LegacyPublishNotificationRequest, - actual: LegacyPublishNotificationRequest + actual: LegacyPublishNotificationRequest, ) { assertEquals(expected.baseMessage.channelName, actual.baseMessage.channelName) assertEquals(expected.baseMessage.channelType, actual.baseMessage.channelType) @@ -26,7 +25,12 @@ internal class LegacyPublishNotificationRequestTests { @Test fun `publish request serialize and deserialize transport object should be equal`() { - val baseMessage = LegacyChimeMessage.Builder("chime_message").withMessage("Hello world").withUrl("https://amazon.com").build() + val baseMessage = + LegacyChimeMessage + .Builder("chime_message") + .withMessage("Hello world") + .withUrl("https://amazon.com") + .build() val request = LegacyPublishNotificationRequest(baseMessage) val recreatedObject = recreateObject(request) { LegacyPublishNotificationRequest(it) } assertRequestEquals(request, recreatedObject) diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationResponseTests.kt index 4a75a82e..1b2d9808 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/LegacyPublishNotificationResponseTests.kt @@ -11,10 +11,14 @@ import org.opensearch.commons.destination.response.LegacyDestinationResponse import org.opensearch.commons.utils.recreateObject internal class LegacyPublishNotificationResponseTests { - @Test fun `Create response serialize and deserialize transport object should be equal`() { - val res = LegacyDestinationResponse.Builder().withStatusCode(200).withResponseContent("Hello world").build() + val res = + LegacyDestinationResponse + .Builder() + .withStatusCode(200) + .withResponseContent("Hello world") + .build() val configResponse = LegacyPublishNotificationResponse(res) val recreatedObject = recreateObject(configResponse) { LegacyPublishNotificationResponse(it) } assertEquals(configResponse.destinationResponse.statusCode, recreatedObject.destinationResponse.statusCode) diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationRequestTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationRequestTests.kt index 70e0bd6c..fd718f9b 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationRequestTests.kt @@ -18,10 +18,9 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class SendNotificationRequestTests { - private fun assertGetRequestEquals( expected: SendNotificationRequest, - actual: SendNotificationRequest + actual: SendNotificationRequest, ) { assertEquals(expected.eventSource, actual.eventSource) assertEquals(expected.channelMessage, actual.channelMessage) @@ -32,46 +31,52 @@ internal class SendNotificationRequestTests { @Test fun `Send request serialize and deserialize transport object should be equal`() { - val notificationInfo = EventSource( - "title", - "reference_id", - SeverityType.HIGH, - listOf("tag1", "tag2") - ) - val channelMessage = ChannelMessage( - "text_description", - "htmlDescription", - null - ) - val request = SendNotificationRequest( - notificationInfo, - channelMessage, - listOf("channelId1", "channelId2"), - "sample-thread-context" - ) + val notificationInfo = + EventSource( + "title", + "reference_id", + SeverityType.HIGH, + listOf("tag1", "tag2"), + ) + val channelMessage = + ChannelMessage( + "text_description", + "htmlDescription", + null, + ) + val request = + SendNotificationRequest( + notificationInfo, + channelMessage, + listOf("channelId1", "channelId2"), + "sample-thread-context", + ) val recreatedObject = recreateObject(request) { SendNotificationRequest(it) } assertGetRequestEquals(request, recreatedObject) } @Test fun `Send request serialize and deserialize using json object should be equal`() { - val notificationInfo = EventSource( - "title", - "reference_id", - SeverityType.CRITICAL, - listOf("tag1", "tag2") - ) - val channelMessage = ChannelMessage( - "text_description", - "htmlDescription", - null - ) - val request = SendNotificationRequest( - notificationInfo, - channelMessage, - listOf("channelId1", "channelId2"), - "sample-thread-context" - ) + val notificationInfo = + EventSource( + "title", + "reference_id", + SeverityType.CRITICAL, + listOf("tag1", "tag2"), + ) + val channelMessage = + ChannelMessage( + "text_description", + "htmlDescription", + null, + ) + val request = + SendNotificationRequest( + notificationInfo, + channelMessage, + listOf("channelId1", "channelId2"), + "sample-thread-context", + ) val jsonString = getJsonString(request) val recreatedObject = createObjectFromJsonString(jsonString) { SendNotificationRequest.parse(it) } assertGetRequestEquals(request, recreatedObject) @@ -87,94 +92,103 @@ internal class SendNotificationRequestTests { @Test fun `Send request should safely ignore extra field in json object`() { - val notificationInfo = EventSource( - "title", - "reference_id", - SeverityType.HIGH, - listOf("tag1", "tag2") - ) - val channelMessage = ChannelMessage( - "text_description", - "htmlDescription", - null - ) - val request = SendNotificationRequest( - notificationInfo, - channelMessage, - listOf("channelId1", "channelId2"), - "sample-thread-context" - ) - val jsonString = """ - { - "event_source":{ - "title":"${notificationInfo.title}", - "reference_id":"${notificationInfo.referenceId}", - "severity":"${notificationInfo.severity}", - "tags":["tag1", "tag2"] - }, - "channel_message":{ - "text_description":"${channelMessage.textDescription}", - "html_description":"${channelMessage.htmlDescription}" - }, - "channel_id_list":["channelId1", "channelId2"], - "context":"${request.threadContext}", - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val notificationInfo = + EventSource( + "title", + "reference_id", + SeverityType.HIGH, + listOf("tag1", "tag2"), + ) + val channelMessage = + ChannelMessage( + "text_description", + "htmlDescription", + null, + ) + val request = + SendNotificationRequest( + notificationInfo, + channelMessage, + listOf("channelId1", "channelId2"), + "sample-thread-context", + ) + val jsonString = + """ + { + "event_source":{ + "title":"${notificationInfo.title}", + "reference_id":"${notificationInfo.referenceId}", + "severity":"${notificationInfo.severity}", + "tags":["tag1", "tag2"] + }, + "channel_message":{ + "text_description":"${channelMessage.textDescription}", + "html_description":"${channelMessage.htmlDescription}" + }, + "channel_id_list":["channelId1", "channelId2"], + "context":"${request.threadContext}", + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { SendNotificationRequest.parse(it) } assertGetRequestEquals(request, recreatedObject) } @Test fun `Send request should safely ignore thread context is absent in json object`() { - val notificationInfo = EventSource( - "title", - "reference_id", - SeverityType.INFO, - listOf("tag1", "tag2") - ) - val channelMessage = ChannelMessage( - "text_description", - "htmlDescription", - null - ) - val request = SendNotificationRequest( - notificationInfo, - channelMessage, - listOf("channelId1", "channelId2"), - null - ) - val jsonString = """ - { - "event_source":{ - "title":"${notificationInfo.title}", - "reference_id":"${notificationInfo.referenceId}", - "severity":"${notificationInfo.severity}", - "tags":["tag1", "tag2"] - }, - "channel_message":{ - "text_description":"${channelMessage.textDescription}", - "html_description":"${channelMessage.htmlDescription}" - }, - "channel_id_list":["channelId1", "channelId2"] - } - """.trimIndent() + val notificationInfo = + EventSource( + "title", + "reference_id", + SeverityType.INFO, + listOf("tag1", "tag2"), + ) + val channelMessage = + ChannelMessage( + "text_description", + "htmlDescription", + null, + ) + val request = + SendNotificationRequest( + notificationInfo, + channelMessage, + listOf("channelId1", "channelId2"), + null, + ) + val jsonString = + """ + { + "event_source":{ + "title":"${notificationInfo.title}", + "reference_id":"${notificationInfo.referenceId}", + "severity":"${notificationInfo.severity}", + "tags":["tag1", "tag2"] + }, + "channel_message":{ + "text_description":"${channelMessage.textDescription}", + "html_description":"${channelMessage.htmlDescription}" + }, + "channel_id_list":["channelId1", "channelId2"] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { SendNotificationRequest.parse(it) } assertGetRequestEquals(request, recreatedObject) } @Test fun `Send request should throw exception if notificationInfo field is absent in json object`() { - val jsonString = """ - { - "channel_message":{ - "text_description":"text_description" - }, - "channel_id_list":["channelId1", "channelId2"] - } - """.trimIndent() + val jsonString = + """ + { + "channel_message":{ + "text_description":"text_description" + }, + "channel_id_list":["channelId1", "channelId2"] + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { SendNotificationRequest.parse(it) } } @@ -182,17 +196,18 @@ internal class SendNotificationRequestTests { @Test fun `Send request should throw exception if channelMessage field is absent in json object`() { - val jsonString = """ - { - "event_source":{ - "title":"title", - "reference_id":"reference_id", - "severity":"High", - "tags":["tag1", "tag2"] - }, - "channel_id_list":["channelId1", "channelId2"] - } - """.trimIndent() + val jsonString = + """ + { + "event_source":{ + "title":"title", + "reference_id":"reference_id", + "severity":"High", + "tags":["tag1", "tag2"] + }, + "channel_id_list":["channelId1", "channelId2"] + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { SendNotificationRequest.parse(it) } } @@ -200,19 +215,20 @@ internal class SendNotificationRequestTests { @Test fun `Send request should throw exception if channelIds field is absent in json object`() { - val jsonString = """ - { - "event_source":{ - "title":"title", - "reference_id":"reference_id", - "severity":"High", - "tags":["tag1", "tag2"] - }, - "channel_message":{ - "text_description":"text_description" + val jsonString = + """ + { + "event_source":{ + "title":"title", + "reference_id":"reference_id", + "severity":"High", + "tags":["tag1", "tag2"] + }, + "channel_message":{ + "text_description":"text_description" + } } - } - """.trimIndent() + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { SendNotificationRequest.parse(it) } } @@ -220,20 +236,21 @@ internal class SendNotificationRequestTests { @Test fun `Send request validate return exception if channelIds field is empty`() { - val jsonString = """ - { - "event_source":{ - "title":"title", - "reference_id":"reference_id", - "severity":"High", - "tags":["tag1", "tag2"] - }, - "channel_message":{ - "text_description":"text_description" - }, - "channel_id_list":[] - } - """.trimIndent() + val jsonString = + """ + { + "event_source":{ + "title":"title", + "reference_id":"reference_id", + "severity":"High", + "tags":["tag1", "tag2"] + }, + "channel_message":{ + "text_description":"text_description" + }, + "channel_id_list":[] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { SendNotificationRequest.parse(it) } assertNotNull(recreatedObject.validate()) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt index 1de3c8fa..ecaebdac 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt @@ -19,7 +19,6 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class SendNotificationResponseTests { - @Test fun `Create response serialize and deserialize transport object should be equal`() { val sampleEvent = getSampleEvent() @@ -64,30 +63,33 @@ internal class SendNotificationResponseTests { @Test fun `Create response should safely ignore extra field in json object`() { val sampleEvent = getSampleEvent() - val jsonString = """ - { - "event_id":"$sampleEvent", - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "event_id":"$sampleEvent", + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { SendNotificationResponse.parse(it) } assertEquals(sampleEvent, recreatedObject) } private fun getSampleEvent(): NotificationEvent { - val sampleEventSource = EventSource( - "title", - "reference_id", - severity = SeverityType.INFO - ) - val sampleStatus = EventStatus( - "config_id", - "name", - ConfigType.SLACK, - deliveryStatus = DeliveryStatus("404", "invalid recipient") - ) + val sampleEventSource = + EventSource( + "title", + "reference_id", + severity = SeverityType.INFO, + ) + val sampleStatus = + EventStatus( + "config_id", + "name", + ConfigType.SLACK, + deliveryStatus = DeliveryStatus("404", "invalid recipient"), + ) return NotificationEvent(sampleEventSource, listOf(sampleStatus)) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequestTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequestTests.kt index fecd7710..175563b3 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequestTests.kt @@ -25,7 +25,6 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class UpdateNotificationConfigRequestTests { - private fun createWebhookContentConfigObject(): NotificationConfig { val sampleWebhook = Webhook("https://domain.com/sample_webhook_url#1234567890") return NotificationConfig( @@ -33,9 +32,10 @@ internal class UpdateNotificationConfigRequestTests { "description", ConfigType.WEBHOOK, configData = sampleWebhook, - isEnabled = true + isEnabled = true, ) } + private fun createMicrosoftTeamsContentConfigObject(): NotificationConfig { val sampleMicrosoftTeams = MicrosoftTeams("https://domain.com/sample_microsoft_teams_url#1234567890") return NotificationConfig( @@ -43,9 +43,10 @@ internal class UpdateNotificationConfigRequestTests { "description", ConfigType.MICROSOFT_TEAMS, configData = sampleMicrosoftTeams, - isEnabled = true + isEnabled = true, ) } + private fun createSlackContentConfigObject(): NotificationConfig { val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") return NotificationConfig( @@ -53,7 +54,7 @@ internal class UpdateNotificationConfigRequestTests { "description", ConfigType.SLACK, configData = sampleSlack, - isEnabled = true + isEnabled = true, ) } @@ -64,7 +65,7 @@ internal class UpdateNotificationConfigRequestTests { "description", ConfigType.CHIME, configData = sampleChime, - isEnabled = true + isEnabled = true, ) } @@ -75,38 +76,40 @@ internal class UpdateNotificationConfigRequestTests { "description", ConfigType.EMAIL_GROUP, configData = sampleEmailGroup, - isEnabled = true + isEnabled = true, ) } private fun createEmailContentConfigObject(): NotificationConfig { - val sampleEmail = Email( - emailAccountID = "sample_1@dummy.com", - recipients = listOf(EmailRecipient("sample_2@dummy.com")), - emailGroupIds = listOf("sample_3@dummy.com") - ) + val sampleEmail = + Email( + emailAccountID = "sample_1@dummy.com", + recipients = listOf(EmailRecipient("sample_2@dummy.com")), + emailGroupIds = listOf("sample_3@dummy.com"), + ) return NotificationConfig( "name", "description", ConfigType.EMAIL, configData = sampleEmail, - isEnabled = true + isEnabled = true, ) } private fun createSmtpAccountContentConfigObject(): NotificationConfig { - val sampleSmtpAccount = SmtpAccount( - host = "http://dummy.com", - port = 11, - method = MethodType.SSL, - fromAddress = "sample@dummy.com" - ) + val sampleSmtpAccount = + SmtpAccount( + host = "http://dummy.com", + port = 11, + method = MethodType.SSL, + fromAddress = "sample@dummy.com", + ) return NotificationConfig( "name", "description", ConfigType.SMTP_ACCOUNT, configData = sampleSmtpAccount, - isEnabled = true + isEnabled = true, ) } @@ -246,27 +249,29 @@ internal class UpdateNotificationConfigRequestTests { @Test fun `Update config should deserialize json object using parser slack`() { val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") - val config = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "feature_list":["index_management"], - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + val config = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "feature_list":["index_management"], + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { UpdateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) assertEquals("config_id1", recreatedObject.configId) @@ -275,27 +280,29 @@ internal class UpdateNotificationConfigRequestTests { @Test fun `Update config should deserialize json object using parser webhook`() { val sampleWebhook = Webhook("https://domain.com/sample_webhook_url#1234567890") - val config = NotificationConfig( - "name", - "description", - ConfigType.WEBHOOK, - configData = sampleWebhook, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"webhook", - "feature_list":["index_management"], - "is_enabled":true, - "webhook":{"url":"https://domain.com/sample_webhook_url#1234567890"} + val config = + NotificationConfig( + "name", + "description", + ConfigType.WEBHOOK, + configData = sampleWebhook, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"webhook", + "feature_list":["index_management"], + "is_enabled":true, + "webhook":{"url":"https://domain.com/sample_webhook_url#1234567890"} + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { UpdateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) assertEquals("config_id1", recreatedObject.configId) @@ -304,27 +311,29 @@ internal class UpdateNotificationConfigRequestTests { @Test fun `Update config should deserialize json object using parser Chime`() { val sampleChime = Chime("https://domain.com/sample_chime_url#1234567890") - val config = NotificationConfig( - "name", - "description", - ConfigType.CHIME, - configData = sampleChime, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"chime", - "feature_list":["index_management"], - "is_enabled":true, - "chime":{"url":"https://domain.com/sample_chime_url#1234567890"} + val config = + NotificationConfig( + "name", + "description", + ConfigType.CHIME, + configData = sampleChime, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"chime", + "feature_list":["index_management"], + "is_enabled":true, + "chime":{"url":"https://domain.com/sample_chime_url#1234567890"} + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { UpdateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) assertEquals("config_id1", recreatedObject.configId) @@ -333,27 +342,29 @@ internal class UpdateNotificationConfigRequestTests { @Test fun `Update config should deserialize json object using parser Email Group`() { val sampleEmailGroup = EmailGroup(listOf(EmailRecipient("dummy@company.com"))) - val config = NotificationConfig( - "name", - "description", - ConfigType.EMAIL_GROUP, - configData = sampleEmailGroup, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"email_group", - "feature_list":["index_management"], - "is_enabled":true, - "email_group":{"recipient_list":[{"recipient":"dummy@company.com"}]} + val config = + NotificationConfig( + "name", + "description", + ConfigType.EMAIL_GROUP, + configData = sampleEmailGroup, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"email_group", + "feature_list":["index_management"], + "is_enabled":true, + "email_group":{"recipient_list":[{"recipient":"dummy@company.com"}]} + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { UpdateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) assertEquals("config_id1", recreatedObject.configId) @@ -361,36 +372,39 @@ internal class UpdateNotificationConfigRequestTests { @Test fun `Update config should deserialize json object using parser Email`() { - val sampleEmail = Email( - emailAccountID = "sample_1@dummy.com", - recipients = listOf(EmailRecipient("sample_2@dummy.com")), - emailGroupIds = listOf("sample_3@dummy.com") - ) - val config = NotificationConfig( - "name", - "description", - ConfigType.EMAIL, - configData = sampleEmail, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"email", - "feature_list":["index_management"], - "is_enabled":true, - "email":{ - "email_account_id":"sample_1@dummy.com", - "recipient_list":[{"recipient":"sample_2@dummy.com"}], - "email_group_id_list":["sample_3@dummy.com"] + val sampleEmail = + Email( + emailAccountID = "sample_1@dummy.com", + recipients = listOf(EmailRecipient("sample_2@dummy.com")), + emailGroupIds = listOf("sample_3@dummy.com"), + ) + val config = + NotificationConfig( + "name", + "description", + ConfigType.EMAIL, + configData = sampleEmail, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"email", + "feature_list":["index_management"], + "is_enabled":true, + "email":{ + "email_account_id":"sample_1@dummy.com", + "recipient_list":[{"recipient":"sample_2@dummy.com"}], + "email_group_id_list":["sample_3@dummy.com"] + } } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { UpdateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) assertEquals("config_id1", recreatedObject.configId) @@ -398,33 +412,36 @@ internal class UpdateNotificationConfigRequestTests { @Test fun `Update config should deserialize json object using parser SmtpAccount`() { - val sampleSmtpAccount = SmtpAccount( - host = "http://dummy.com", - port = 11, - method = MethodType.SSL, - fromAddress = "sample@dummy.com" - ) - val config = NotificationConfig( - "name", - "description", - ConfigType.SMTP_ACCOUNT, - configData = sampleSmtpAccount, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"smtp_account", - "feature_list":["index_management"], - "is_enabled":true, - "smtp_account":{"host":"http://dummy.com", "port":11,"method": "ssl", "from_address": "sample@dummy.com" } + val sampleSmtpAccount = + SmtpAccount( + host = "http://dummy.com", + port = 11, + method = MethodType.SSL, + fromAddress = "sample@dummy.com", + ) + val config = + NotificationConfig( + "name", + "description", + ConfigType.SMTP_ACCOUNT, + configData = sampleSmtpAccount, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"smtp_account", + "feature_list":["index_management"], + "is_enabled":true, + "smtp_account":{"host":"http://dummy.com", "port":11,"method": "ssl", "from_address": "sample@dummy.com" } + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { UpdateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) assertEquals("config_id1", recreatedObject.configId) @@ -441,30 +458,32 @@ internal class UpdateNotificationConfigRequestTests { @Test fun `Update config should safely ignore extra field in json object`() { val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") - val config = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack, - isEnabled = true - ) - - val jsonString = """ - { - "config_id":"config_id1", - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "feature_list":["index_management"], - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"}, - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" + val config = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + isEnabled = true, + ) + + val jsonString = + """ + { + "config_id":"config_id1", + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "feature_list":["index_management"], + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"}, + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { UpdateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) assertEquals("config_id1", recreatedObject.configId) diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigResponseTests.kt index ca0b18cc..a748db68 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigResponseTests.kt @@ -13,7 +13,6 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class UpdateNotificationConfigResponseTests { - @Test fun `Update response serialize and deserialize transport object should be equal`() { val configResponse = UpdateNotificationConfigResponse("sample_config_id") @@ -56,14 +55,15 @@ internal class UpdateNotificationConfigResponseTests { @Test fun `Update response should safely ignore extra field in json object`() { val configId = "sample_config_id" - val jsonString = """ - { - "config_id":"$configId", - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "config_id":"$configId", + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { UpdateNotificationConfigResponse.parse(it) } assertEquals(configId, recreatedObject.configId) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/AttachmentTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/AttachmentTests.kt index 5aa127fe..899bab73 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/AttachmentTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/AttachmentTests.kt @@ -12,27 +12,28 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class AttachmentTests { - @Test fun `Attachment Object serialize and deserialize using transport should be equal`() { - val attachment = Attachment( - "fileName", - "fileEncoding", - "fileData", - "fileContentType" - ) + val attachment = + Attachment( + "fileName", + "fileEncoding", + "fileData", + "fileContentType", + ) val recreatedObject = recreateObject(attachment) { Attachment(it) } assertEquals(attachment, recreatedObject) } @Test fun `Attachment Object serialize and deserialize using json should be equal`() { - val attachment = Attachment( - "fileName", - "fileEncoding", - "fileData", - "fileContentType" - ) + val attachment = + Attachment( + "fileName", + "fileEncoding", + "fileData", + "fileContentType", + ) val jsonString = getJsonString(attachment) val recreatedObject = createObjectFromJsonString(jsonString) { Attachment.parse(it) } assertEquals(attachment, recreatedObject) @@ -40,55 +41,60 @@ internal class AttachmentTests { @Test fun `Attachment Json parsing should safely ignore extra fields`() { - val attachment = Attachment( - "fileName", - "fileEncoding", - "fileData", - "fileContentType" - ) - val jsonString = """ - { - "file_name":"fileName", - "file_encoding":"fileEncoding", - "file_data":"fileData", - "file_content_type":"fileContentType", - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val attachment = + Attachment( + "fileName", + "fileEncoding", + "fileData", + "fileContentType", + ) + val jsonString = + """ + { + "file_name":"fileName", + "file_encoding":"fileEncoding", + "file_data":"fileData", + "file_content_type":"fileContentType", + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Attachment.parse(it) } assertEquals(attachment, recreatedObject) } @Test fun `Attachment Json parsing should safely ignore null content type`() { - val attachment = Attachment( - "fileName", - "fileEncoding", - "fileData", - null - ) - val jsonString = """ - { - "file_name":"fileName", - "file_encoding":"fileEncoding", - "file_data":"fileData" - } - """.trimIndent() + val attachment = + Attachment( + "fileName", + "fileEncoding", + "fileData", + null, + ) + val jsonString = + """ + { + "file_name":"fileName", + "file_encoding":"fileEncoding", + "file_data":"fileData" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Attachment.parse(it) } assertEquals(attachment, recreatedObject) } @Test fun `Attachment Json parsing should throw exception if file_name is absent`() { - val jsonString = """ - { - "file_encoding":"fileEncoding", - "file_data":"fileData", - "file_content_type":"fileContentType" - } - """.trimIndent() + val jsonString = + """ + { + "file_encoding":"fileEncoding", + "file_data":"fileData", + "file_content_type":"fileContentType" + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { Attachment.parse(it) } } @@ -96,13 +102,14 @@ internal class AttachmentTests { @Test fun `Attachment Json parsing should throw exception if file_encoding is absent`() { - val jsonString = """ - { - "file_name":"fileName", - "file_data":"fileData", - "file_content_type":"fileContentType" - } - """.trimIndent() + val jsonString = + """ + { + "file_name":"fileName", + "file_data":"fileData", + "file_content_type":"fileContentType" + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { Attachment.parse(it) } } @@ -110,13 +117,14 @@ internal class AttachmentTests { @Test fun `Attachment Json parsing should throw exception if file_data is absent`() { - val jsonString = """ - { - "file_name":"fileName", - "file_encoding":"fileEncoding", - "file_content_type":"fileContentType" - } - """.trimIndent() + val jsonString = + """ + { + "file_name":"fileName", + "file_encoding":"fileEncoding", + "file_content_type":"fileContentType" + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { Attachment.parse(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelListTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelListTests.kt index cad52261..7fc128de 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelListTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelListTests.kt @@ -13,10 +13,9 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class ChannelListTests { - private fun assertSearchResultEquals( expected: ChannelList, - actual: ChannelList + actual: ChannelList, ) { assertEquals(expected.startIndex, actual.startIndex) assertEquals(expected.totalHits, actual.totalHits) @@ -27,13 +26,14 @@ internal class ChannelListTests { @Test fun `Feature Channel List serialize and deserialize using transport should be equal`() { - val channel = Channel( - "configId", - "name", - "description", - ConfigType.SLACK, - true - ) + val channel = + Channel( + "configId", + "name", + "description", + ConfigType.SLACK, + true, + ) val channelList = ChannelList(channel) val recreatedObject = recreateObject(channelList) { ChannelList(it) } assertSearchResultEquals(channelList, recreatedObject) @@ -41,80 +41,89 @@ internal class ChannelListTests { @Test fun `Feature Channel List serialize and deserialize multiple object with default values should be equal`() { - val channel1 = Channel( - "configId1", - "name1", - "description1", - ConfigType.SLACK, - true - ) - val channel2 = Channel( - "configId2", - "name2", - "description2", - ConfigType.CHIME, - true - ) - val channel3 = Channel( - "configId3", - "name3", - "description3", - ConfigType.MICROSOFT_TEAMS, - true - ) + val channel1 = + Channel( + "configId1", + "name1", + "description1", + ConfigType.SLACK, + true, + ) + val channel2 = + Channel( + "configId2", + "name2", + "description2", + ConfigType.CHIME, + true, + ) + val channel3 = + Channel( + "configId3", + "name3", + "description3", + ConfigType.MICROSOFT_TEAMS, + true, + ) val channelList = ChannelList(listOf(channel1, channel2, channel3)) - val expectedResult = ChannelList( - 0, - 3, - TotalHits.Relation.EQUAL_TO, - listOf(channel1, channel2, channel3) - ) + val expectedResult = + ChannelList( + 0, + 3, + TotalHits.Relation.EQUAL_TO, + listOf(channel1, channel2, channel3), + ) val recreatedObject = recreateObject(channelList) { ChannelList(it) } assertSearchResultEquals(expectedResult, recreatedObject) } @Test fun `Feature Channel List serialize and deserialize with multiple object should be equal`() { - val channel1 = Channel( - "configId1", - "name1", - "description1", - ConfigType.SLACK, - true - ) - val channel2 = Channel( - "configId2", - "name2", - "description2", - ConfigType.CHIME, - true - ) - val channel3 = Channel( - "configId3", - "name3", - "description3", - ConfigType.MICROSOFT_TEAMS, - true - ) - val channelList = ChannelList( - 100, - 1000, - TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, - listOf(channel1, channel2, channel3) - ) + val channel1 = + Channel( + "configId1", + "name1", + "description1", + ConfigType.SLACK, + true, + ) + val channel2 = + Channel( + "configId2", + "name2", + "description2", + ConfigType.CHIME, + true, + ) + val channel3 = + Channel( + "configId3", + "name3", + "description3", + ConfigType.MICROSOFT_TEAMS, + true, + ) + val channelList = + ChannelList( + 100, + 1000, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, + listOf(channel1, channel2, channel3), + ) val recreatedObject = recreateObject(channelList) { ChannelList(it) } assertSearchResultEquals(channelList, recreatedObject) } @Test fun `Feature Channel List serialize and deserialize using json should be equal`() { - val channel = Channel( - "configId", - "name", - "description", - ConfigType.SLACK, - true - ) + val channel = + Channel( + "configId", + "name", + "description", + ConfigType.SLACK, + true, + ) val channelList = ChannelList(channel) val jsonString = getJsonString(channelList) val recreatedObject = createObjectFromJsonString(jsonString) { ChannelList(it) } @@ -123,33 +132,37 @@ internal class ChannelListTests { @Test fun `Feature Channel List serialize and deserialize using json with multiple object should be equal`() { - val channel1 = Channel( - "configId1", - "name1", - "description1", - ConfigType.SLACK, - true - ) - val channel2 = Channel( - "configId2", - "name2", - "description2", - ConfigType.CHIME, - true - ) - val channel3 = Channel( - "configId3", - "name3", - "description3", - ConfigType.MICROSOFT_TEAMS, - true - ) - val channelList = ChannelList( - 100, - 1000, - TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, - listOf(channel1, channel2, channel3) - ) + val channel1 = + Channel( + "configId1", + "name1", + "description1", + ConfigType.SLACK, + true, + ) + val channel2 = + Channel( + "configId2", + "name2", + "description2", + ConfigType.CHIME, + true, + ) + val channel3 = + Channel( + "configId3", + "name3", + "description3", + ConfigType.MICROSOFT_TEAMS, + true, + ) + val channelList = + ChannelList( + 100, + 1000, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, + listOf(channel1, channel2, channel3), + ) val jsonString = getJsonString(channelList) val recreatedObject = createObjectFromJsonString(jsonString) { ChannelList(it) } assertSearchResultEquals(channelList, recreatedObject) @@ -157,73 +170,79 @@ internal class ChannelListTests { @Test fun `Feature Channel List should safely ignore extra field in json object`() { - val channel = Channel( - "configId", - "name", - "description", - ConfigType.SLACK, - true - ) + val channel = + Channel( + "configId", + "name", + "description", + ConfigType.SLACK, + true, + ) val channelList = ChannelList(channel) - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq", - "channel_list":[ - { - "config_id":"configId", - "name":"name", - "description":"description", - "config_type":"slack", - "is_enabled":true - } - ], - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq", + "channel_list":[ + { + "config_id":"configId", + "name":"name", + "description":"description", + "config_type":"slack", + "is_enabled":true + } + ], + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { ChannelList(it) } assertSearchResultEquals(channelList, recreatedObject) } @Test + @Suppress("ktlint:standard:max-line-length") fun `Feature Channel List should safely fallback to default if startIndex, totalHits or totalHitRelation field absent in json object`() { - val channel = Channel( - "configId", - "name", - "description", - ConfigType.SLACK, - true - ) + val channel = + Channel( + "configId", + "name", + "description", + ConfigType.SLACK, + true, + ) val channelList = ChannelList(channel) - val jsonString = """ - { - "channel_list":[ - { - "config_id":"configId", - "name":"name", - "description":"description", - "config_type":"slack", - "is_enabled":true - } - ] - } - """.trimIndent() + val jsonString = + """ + { + "channel_list":[ + { + "config_id":"configId", + "name":"name", + "description":"description", + "config_type":"slack", + "is_enabled":true + } + ] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { ChannelList(it) } assertSearchResultEquals(channelList, recreatedObject) } @Test fun `Channel List should throw exception if channel_list is absent in json`() { - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq" - } - """.trimIndent() + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq" + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { ChannelList(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelMessageTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelMessageTests.kt index 0a9f3f87..d0ebaa70 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelMessageTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelMessageTests.kt @@ -12,37 +12,40 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class ChannelMessageTests { - @Test fun `ChannelMessage Object serialize and deserialize using transport should be equal`() { - val attachment = Attachment( - "fileName", - "fileEncoding", - "fileData", - "fileContentType" - ) - val channelMessage = ChannelMessage( - "textDescription", - "htmlDescription", - attachment - ) + val attachment = + Attachment( + "fileName", + "fileEncoding", + "fileData", + "fileContentType", + ) + val channelMessage = + ChannelMessage( + "textDescription", + "htmlDescription", + attachment, + ) val recreatedObject = recreateObject(channelMessage) { ChannelMessage(it) } assertEquals(channelMessage, recreatedObject) } @Test fun `ChannelMessage Object serialize and deserialize using json should be equal`() { - val attachment = Attachment( - "fileName", - "fileEncoding", - "fileData", - "fileContentType" - ) - val channelMessage = ChannelMessage( - "textDescription", - "htmlDescription", - attachment - ) + val attachment = + Attachment( + "fileName", + "fileEncoding", + "fileData", + "fileContentType", + ) + val channelMessage = + ChannelMessage( + "textDescription", + "htmlDescription", + attachment, + ) val jsonString = getJsonString(channelMessage) val recreatedObject = createObjectFromJsonString(jsonString) { ChannelMessage.parse(it) } assertEquals(channelMessage, recreatedObject) @@ -50,111 +53,122 @@ internal class ChannelMessageTests { @Test fun `ChannelMessage Json parsing should safely ignore extra fields`() { - val attachment = Attachment( - "fileName", - "fileEncoding", - "fileData", - "fileContentType" - ) - val channelMessage = ChannelMessage( - "textDescription", - "htmlDescription", - attachment - ) - val jsonString = """ - { - "text_description":"textDescription", - "html_description":"htmlDescription", - "attachment":{ - "file_name":"fileName", - "file_encoding":"fileEncoding", - "file_data":"fileData", - "file_content_type":"fileContentType" - }, - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val attachment = + Attachment( + "fileName", + "fileEncoding", + "fileData", + "fileContentType", + ) + val channelMessage = + ChannelMessage( + "textDescription", + "htmlDescription", + attachment, + ) + val jsonString = + """ + { + "text_description":"textDescription", + "html_description":"htmlDescription", + "attachment":{ + "file_name":"fileName", + "file_encoding":"fileEncoding", + "file_data":"fileData", + "file_content_type":"fileContentType" + }, + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { ChannelMessage.parse(it) } assertEquals(channelMessage, recreatedObject) } @Test fun `ChannelMessage Json parsing should safely ignore missing html description`() { - val attachment = Attachment( - "fileName", - "fileEncoding", - "fileData", - "fileContentType" - ) - val channelMessage = ChannelMessage( - "textDescription", - null, - attachment - ) - val jsonString = """ - { - "text_description":"textDescription", - "attachment":{ - "file_name":"fileName", - "file_encoding":"fileEncoding", - "file_data":"fileData", - "file_content_type":"fileContentType" + val attachment = + Attachment( + "fileName", + "fileEncoding", + "fileData", + "fileContentType", + ) + val channelMessage = + ChannelMessage( + "textDescription", + null, + attachment, + ) + val jsonString = + """ + { + "text_description":"textDescription", + "attachment":{ + "file_name":"fileName", + "file_encoding":"fileEncoding", + "file_data":"fileData", + "file_content_type":"fileContentType" + } } - } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { ChannelMessage.parse(it) } assertEquals(channelMessage, recreatedObject) } @Test fun `ChannelMessage Json parsing should safely ignore missing attachment`() { - val channelMessage = ChannelMessage( - "textDescription", - "htmlDescription", - null - ) - val jsonString = """ - { - "text_description":"textDescription", - "html_description":"htmlDescription" - } - """.trimIndent() + val channelMessage = + ChannelMessage( + "textDescription", + "htmlDescription", + null, + ) + val jsonString = + """ + { + "text_description":"textDescription", + "html_description":"htmlDescription" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { ChannelMessage.parse(it) } assertEquals(channelMessage, recreatedObject) } @Test fun `ChannelMessage Json parsing should safely ignore both missing html_description and attachment`() { - val channelMessage = ChannelMessage( - "textDescription", - null, - null - ) - val jsonString = """ - { - "text_description":"textDescription" - } - """.trimIndent() + val channelMessage = + ChannelMessage( + "textDescription", + null, + null, + ) + val jsonString = + """ + { + "text_description":"textDescription" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { ChannelMessage.parse(it) } assertEquals(channelMessage, recreatedObject) } @Test fun `ChannelMessage Json parsing should throw exception if text_description is empty`() { - val jsonString = """ - { - "text_description":"", - "html_description":"htmlDescription", - "attachment":{ - "file_name":"fileName", - "file_encoding":"fileEncoding", - "file_data":"fileData", - "file_content_type":"fileContentType" + val jsonString = + """ + { + "text_description":"", + "html_description":"htmlDescription", + "attachment":{ + "file_name":"fileName", + "file_encoding":"fileEncoding", + "file_data":"fileData", + "file_content_type":"fileContentType" + } } - } - """.trimIndent() + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { ChannelMessage.parse(it) } } @@ -162,17 +176,18 @@ internal class ChannelMessageTests { @Test fun `ChannelMessage Json parsing should throw exception if text_description is absent`() { - val jsonString = """ - { - "html_description":"htmlDescription", - "attachment":{ - "file_name":"fileName", - "file_encoding":"fileEncoding", - "file_data":"fileData", - "file_content_type":"fileContentType" + val jsonString = + """ + { + "html_description":"htmlDescription", + "attachment":{ + "file_name":"fileName", + "file_encoding":"fileEncoding", + "file_data":"fileData", + "file_content_type":"fileContentType" + } } - } - """.trimIndent() + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { ChannelMessage.parse(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelTests.kt index 3f64cc5a..21ad4fd8 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/ChannelTests.kt @@ -12,29 +12,30 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class ChannelTests { - @Test fun `Channel Object serialize and deserialize using transport should be equal`() { - val channel = Channel( - "configId", - "name", - "description", - ConfigType.SLACK, - true - ) + val channel = + Channel( + "configId", + "name", + "description", + ConfigType.SLACK, + true, + ) val recreatedObject = recreateObject(channel) { Channel(it) } assertEquals(channel, recreatedObject) } @Test fun `Channel Object serialize and deserialize using json should be equal`() { - val channel = Channel( - "configId", - "name", - "description", - ConfigType.CHIME, - false - ) + val channel = + Channel( + "configId", + "name", + "description", + ConfigType.CHIME, + false, + ) val jsonString = getJsonString(channel) val recreatedObject = createObjectFromJsonString(jsonString) { Channel.parse(it) } assertEquals(channel, recreatedObject) @@ -42,103 +43,112 @@ internal class ChannelTests { @Test fun `Channel Json parsing should safely ignore extra fields`() { - val channel = Channel( - "configId", - "name", - "description", - ConfigType.EMAIL_GROUP, - true - ) - val jsonString = """ - { - "config_id":"configId", - "name":"name", - "description":"description", - "config_type":"email_group", - "is_enabled":true, - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val channel = + Channel( + "configId", + "name", + "description", + ConfigType.EMAIL_GROUP, + true, + ) + val jsonString = + """ + { + "config_id":"configId", + "name":"name", + "description":"description", + "config_type":"email_group", + "is_enabled":true, + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Channel.parse(it) } assertEquals(channel, recreatedObject) } @Test fun `Channel Json parsing should safely ignore unknown config type`() { - val channel = Channel( - "configId", - "name", - "description", - ConfigType.NONE, - true - ) - val jsonString = """ - { - "config_id":"configId", - "name":"name", - "description":"description", - "config_type":"NewConfig", - "is_enabled":true - } - """.trimIndent() + val channel = + Channel( + "configId", + "name", + "description", + ConfigType.NONE, + true, + ) + val jsonString = + """ + { + "config_id":"configId", + "name":"name", + "description":"description", + "config_type":"NewConfig", + "is_enabled":true + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Channel.parse(it) } assertEquals(channel, recreatedObject) } @Test fun `Channel Json parsing should safely parse if description is absent`() { - val channel = Channel( - "configId", - "name", - "", - ConfigType.SLACK, - true - ) - val jsonString = """ - { - "config_id":"configId", - "name":"name", - "config_type":"slack", - "is_enabled":true - } - """.trimIndent() + val channel = + Channel( + "configId", + "name", + "", + ConfigType.SLACK, + true, + ) + val jsonString = + """ + { + "config_id":"configId", + "name":"name", + "config_type":"slack", + "is_enabled":true + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Channel.parse(it) } assertEquals(channel, recreatedObject) } @Test fun `Channel Json parsing should safely parse if is_enabled is absent`() { - val channel = Channel( - "configId", - "name", - "description", - ConfigType.SLACK, - true - ) - val jsonString = """ - { - "config_id":"configId", - "name":"name", - "description":"description", - "config_type":"slack" - } - """.trimIndent() + val channel = + Channel( + "configId", + "name", + "description", + ConfigType.SLACK, + true, + ) + val jsonString = + """ + { + "config_id":"configId", + "name":"name", + "description":"description", + "config_type":"slack" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Channel.parse(it) } assertEquals(channel, recreatedObject) } @Test fun `Channel Json parsing should throw exception if config_id is absent`() { - val jsonString = """ - { - "name":"name", - "description":"description", - "config_type":"slack", - "is_enabled":true - } - """.trimIndent() + val jsonString = + """ + { + "name":"name", + "description":"description", + "config_type":"slack", + "is_enabled":true + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { Channel.parse(it) } } @@ -146,15 +156,16 @@ internal class ChannelTests { @Test fun `Channel Json parsing should throw exception if config_id is empty`() { - val jsonString = """ - { - "config_id":"", - "name":"name", - "description":"description", - "config_type":"chime", - "is_enabled":true - } - """.trimIndent() + val jsonString = + """ + { + "config_id":"", + "name":"name", + "description":"description", + "config_type":"chime", + "is_enabled":true + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { Channel.parse(it) } } @@ -162,14 +173,15 @@ internal class ChannelTests { @Test fun `Channel Json parsing should throw exception if name is absent`() { - val jsonString = """ - { - "config_id":"configId", - "description":"description", - "config_type":"webhook", - "is_enabled":true - } - """.trimIndent() + val jsonString = + """ + { + "config_id":"configId", + "description":"description", + "config_type":"webhook", + "is_enabled":true + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { Channel.parse(it) } } @@ -177,15 +189,16 @@ internal class ChannelTests { @Test fun `Channel Json parsing should throw exception if name is empty`() { - val jsonString = """ - { - "config_id":"configId", - "name":"", - "description":"description", - "config_type":"email", - "is_enabled":true - } - """.trimIndent() + val jsonString = + """ + { + "config_id":"configId", + "name":"", + "description":"description", + "config_type":"email", + "is_enabled":true + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { Channel.parse(it) } } @@ -193,14 +206,15 @@ internal class ChannelTests { @Test fun `Channel Json parsing should throw exception if config_type is absent`() { - val jsonString = """ - { - "config_id":"configId", - "name":"name", - "description":"description", - "is_enabled":true - } - """.trimIndent() + val jsonString = + """ + { + "config_id":"configId", + "name":"name", + "description":"description", + "is_enabled":true + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { Channel.parse(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/ChimeTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/ChimeTests.kt index 8e7f434e..0f4fd221 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/ChimeTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/ChimeTests.kt @@ -14,7 +14,6 @@ import org.opensearch.commons.utils.recreateObject import java.net.MalformedURLException internal class ChimeTests { - @Test fun `Chime serialize and deserialize transport object should be equal`() { val sampleChime = Chime("https://domain.com/sample_url#1234567890") diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/ConfigTypeTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/ConfigTypeTests.kt index 6be8d68b..34bc7b83 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/ConfigTypeTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/ConfigTypeTests.kt @@ -10,7 +10,6 @@ import org.opensearch.commons.notifications.model.ConfigType.Companion.enumParse import org.opensearch.commons.notifications.model.ConfigType.Companion.fromTagOrDefault internal class ConfigTypeTests { - @Test fun `toString should return tag`() { ConfigType.values().forEach { diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/DeliveryStatusTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/DeliveryStatusTests.kt index 33c42e99..0ac4bef4 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/DeliveryStatusTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/DeliveryStatusTests.kt @@ -16,20 +16,22 @@ import org.opensearch.commons.utils.recreateObject internal class DeliveryStatusTests { @Test fun `DeliveryStatus serialize and deserialize should be equal`() { - val sampleDeliveryStatus = DeliveryStatus( - "404", - "invalid recipient" - ) + val sampleDeliveryStatus = + DeliveryStatus( + "404", + "invalid recipient", + ) val recreatedObject = recreateObject(sampleDeliveryStatus) { DeliveryStatus(it) } assertEquals(sampleDeliveryStatus, recreatedObject) } @Test fun `DeliveryStatus serialize and deserialize using json should be equal`() { - val sampleDeliveryStatus = DeliveryStatus( - "404", - "invalid recipient" - ) + val sampleDeliveryStatus = + DeliveryStatus( + "404", + "invalid recipient", + ) val jsonString = getJsonString(sampleDeliveryStatus) val recreatedObject = createObjectFromJsonString(jsonString) { DeliveryStatus.parse(it) } assertEquals(sampleDeliveryStatus, recreatedObject) @@ -45,17 +47,19 @@ internal class DeliveryStatusTests { @Test fun `DeliveryStatus should safely ignore extra field in json object`() { - val sampleDeliveryStatus = DeliveryStatus( - "404", - "invalid recipient" - ) - val jsonString = """ - { - "status_code": "404", - "status_text": "invalid recipient", - "extra": "field" - } - """.trimIndent() + val sampleDeliveryStatus = + DeliveryStatus( + "404", + "invalid recipient", + ) + val jsonString = + """ + { + "status_code": "404", + "status_text": "invalid recipient", + "extra": "field" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { DeliveryStatus.parse(it) } assertEquals(sampleDeliveryStatus, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/EmailGroupTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/EmailGroupTests.kt index 15ab3ade..13a7ce56 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/EmailGroupTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/EmailGroupTests.kt @@ -13,27 +13,28 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class EmailGroupTests { - @Test fun `EmailGroup serialize and deserialize transport object should be equal`() { - val sampleEmailGroup = EmailGroup( - listOf( - EmailRecipient("email1@email.com"), - EmailRecipient("email2@email.com") + val sampleEmailGroup = + EmailGroup( + listOf( + EmailRecipient("email1@email.com"), + EmailRecipient("email2@email.com"), + ), ) - ) val recreatedObject = recreateObject(sampleEmailGroup) { EmailGroup(it) } assertEquals(sampleEmailGroup, recreatedObject) } @Test fun `EmailGroup serialize and deserialize using json object should be equal`() { - val sampleEmailGroup = EmailGroup( - listOf( - EmailRecipient("email1@email.com"), - EmailRecipient("email2@email.com") + val sampleEmailGroup = + EmailGroup( + listOf( + EmailRecipient("email1@email.com"), + EmailRecipient("email2@email.com"), + ), ) - ) val jsonString = getJsonString(sampleEmailGroup) val recreatedObject = createObjectFromJsonString(jsonString) { EmailGroup.parse(it) } assertEquals(sampleEmailGroup, recreatedObject) @@ -41,20 +42,22 @@ internal class EmailGroupTests { @Test fun `EmailGroup should deserialize json object using parser`() { - val sampleEmailGroup = EmailGroup( - listOf( - EmailRecipient("email1@email.com"), - EmailRecipient("email2@email.com") + val sampleEmailGroup = + EmailGroup( + listOf( + EmailRecipient("email1@email.com"), + EmailRecipient("email2@email.com"), + ), ) - ) - val jsonString = """ + val jsonString = + """ { "recipient_list":[ {"recipient":"${sampleEmailGroup.recipients[0].recipient}"}, {"recipient":"${sampleEmailGroup.recipients[1].recipient}"} ] }" - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { EmailGroup.parse(it) } assertEquals(sampleEmailGroup, recreatedObject) } @@ -69,20 +72,22 @@ internal class EmailGroupTests { @Test fun `EmailGroup should throw exception when recipients is replaced with recipients2 in json object`() { - val sampleEmailGroup = EmailGroup( - listOf( - EmailRecipient("email1@email.com"), - EmailRecipient("email2@email.com") + val sampleEmailGroup = + EmailGroup( + listOf( + EmailRecipient("email1@email.com"), + EmailRecipient("email2@email.com"), + ), ) - ) - val jsonString = """ + val jsonString = + """ { "recipient_list2":[ {"recipient":"${sampleEmailGroup.recipients[0]}"}, {"recipient":"${sampleEmailGroup.recipients[1]}"} ] }" - """.trimIndent() + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { EmailGroup.parse(it) } } @@ -91,7 +96,8 @@ internal class EmailGroupTests { @Test fun `EmailGroup should safely ignore extra field in json object`() { val sampleEmailGroup = EmailGroup(listOf(EmailRecipient("email1@email.com"))) - val jsonString = """ + val jsonString = + """ { "recipient_list":[ {"recipient":"${sampleEmailGroup.recipients[0].recipient}"} @@ -100,7 +106,7 @@ internal class EmailGroupTests { "extra_field_2":{"extra":"value"}, "extra_field_3":"extra value 3" }" - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { EmailGroup.parse(it) } assertEquals(sampleEmailGroup, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/EmailRecipientStatusTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/EmailRecipientStatusTests.kt index c9bd89af..2f95404d 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/EmailRecipientStatusTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/EmailRecipientStatusTests.kt @@ -16,20 +16,22 @@ import org.opensearch.commons.utils.recreateObject internal class EmailRecipientStatusTests { @Test fun `EmailRecipientStatus serialize and deserialize should be equal`() { - val sampleEmailRecipientStatus = EmailRecipientStatus( - "sample@email.com", - DeliveryStatus("404", "invalid recipient") - ) + val sampleEmailRecipientStatus = + EmailRecipientStatus( + "sample@email.com", + DeliveryStatus("404", "invalid recipient"), + ) val recreatedObject = recreateObject(sampleEmailRecipientStatus) { EmailRecipientStatus(it) } assertEquals(sampleEmailRecipientStatus, recreatedObject) } @Test fun `EmailRecipientStatus serialize and deserialize using json should be equal`() { - val sampleEmailRecipientStatus = EmailRecipientStatus( - "sample@email.com", - DeliveryStatus("404", "invalid recipient") - ) + val sampleEmailRecipientStatus = + EmailRecipientStatus( + "sample@email.com", + DeliveryStatus("404", "invalid recipient"), + ) val jsonString = getJsonString(sampleEmailRecipientStatus) val recreatedObject = createObjectFromJsonString(jsonString) { EmailRecipientStatus.parse(it) } assertEquals(sampleEmailRecipientStatus, recreatedObject) @@ -52,20 +54,22 @@ internal class EmailRecipientStatusTests { @Test fun `EmailRecipientStatus should safely ignore extra field in json object`() { - val sampleEmailRecipientStatus = EmailRecipientStatus( - "sample@email.com", - DeliveryStatus("200", "Success") - ) - val jsonString = """ - { - "recipient": "sample@email.com", - "delivery_status": { - "status_code": "200", - "status_text": "Success" - }, - "extra": "field" - } - """.trimIndent() + val sampleEmailRecipientStatus = + EmailRecipientStatus( + "sample@email.com", + DeliveryStatus("200", "Success"), + ) + val jsonString = + """ + { + "recipient": "sample@email.com", + "delivery_status": { + "status_code": "200", + "status_text": "Success" + }, + "extra": "field" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { EmailRecipientStatus.parse(it) } assertEquals(sampleEmailRecipientStatus, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/EmailRecipientTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/EmailRecipientTests.kt index 56a5f752..7773aec8 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/EmailRecipientTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/EmailRecipientTests.kt @@ -14,7 +14,6 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class EmailRecipientTests { - private fun checkValidEmailAddress(emailAddress: String) { assertDoesNotThrow("should accept $emailAddress") { EmailRecipient(emailAddress) @@ -73,11 +72,12 @@ internal class EmailRecipientTests { @Test fun `EmailRecipient should deserialize json object using parser`() { val sampleEmailRecipient = EmailRecipient("email1@email.com") - val jsonString = """ + val jsonString = + """ { "recipient": "${sampleEmailRecipient.recipient}" }" - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { EmailRecipient.parse(it) } assertEquals(sampleEmailRecipient, recreatedObject) } @@ -93,11 +93,12 @@ internal class EmailRecipientTests { @Test fun `EmailRecipient should throw exception when recipients is replaced with recipients2 in json object`() { val sampleEmailRecipient = EmailRecipient("email1@email.com") - val jsonString = """ + val jsonString = + """ { "recipient2": "${sampleEmailRecipient.recipient}" }" - """.trimIndent() + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { EmailRecipient.parse(it) } } @@ -106,14 +107,15 @@ internal class EmailRecipientTests { @Test fun `EmailRecipient should safely ignore extra field in json object`() { val sampleEmailRecipient = EmailRecipient("email@email.com") - val jsonString = """ + val jsonString = + """ { "recipient": "${sampleEmailRecipient.recipient}", "extra_field_1":["extra", "value"], "extra_field_2":{"extra":"value"}, "extra_field_3":"extra value 3" }" - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { EmailRecipient.parse(it) } assertEquals(sampleEmailRecipient, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/EmailTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/EmailTests.kt index 8624b138..280b086a 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/EmailTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/EmailTests.kt @@ -13,31 +13,32 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class EmailTests { - @Test fun `Email serialize and deserialize transport object should be equal`() { - val sampleEmail = Email( - "sampleAccountId", - listOf( - EmailRecipient("email1@email.com"), - EmailRecipient("email2@email.com") - ), - listOf("sample_group_id_1", "sample_group_id_2") - ) + val sampleEmail = + Email( + "sampleAccountId", + listOf( + EmailRecipient("email1@email.com"), + EmailRecipient("email2@email.com"), + ), + listOf("sample_group_id_1", "sample_group_id_2"), + ) val recreatedObject = recreateObject(sampleEmail) { Email(it) } assertEquals(sampleEmail, recreatedObject) } @Test fun `Email serialize and deserialize using json object should be equal`() { - val sampleEmail = Email( - "sampleAccountId", - listOf( - EmailRecipient("email1@email.com"), - EmailRecipient("email2@email.com") - ), - listOf("sample_group_id_1", "sample_group_id_2") - ) + val sampleEmail = + Email( + "sampleAccountId", + listOf( + EmailRecipient("email1@email.com"), + EmailRecipient("email2@email.com"), + ), + listOf("sample_group_id_1", "sample_group_id_2"), + ) val jsonString = getJsonString(sampleEmail) val recreatedObject = createObjectFromJsonString(jsonString) { Email.parse(it) } assertEquals(sampleEmail, recreatedObject) @@ -45,15 +46,17 @@ internal class EmailTests { @Test fun `Email should deserialize json object using parser`() { - val sampleEmail = Email( - "sampleAccountId", - listOf( - EmailRecipient("email1@email.com"), - EmailRecipient("email2@email.com") - ), - listOf("sample_group_id_1", "sample_group_id_2") - ) - val jsonString = """ + val sampleEmail = + Email( + "sampleAccountId", + listOf( + EmailRecipient("email1@email.com"), + EmailRecipient("email2@email.com"), + ), + listOf("sample_group_id_1", "sample_group_id_2"), + ) + val jsonString = + """ { "email_account_id":"${sampleEmail.emailAccountID}", "recipient_list":[ @@ -65,7 +68,7 @@ internal class EmailTests { "${sampleEmail.emailGroupIds[1]}" ] }" - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Email.parse(it) } assertEquals(sampleEmail, recreatedObject) } @@ -80,15 +83,17 @@ internal class EmailTests { @Test fun `Email should throw exception when emailAccountID is replaced with emailAccountID2 in json object`() { - val sampleEmail = Email( - "sampleAccountId", - listOf( - EmailRecipient("email1@email.com"), - EmailRecipient("email2@email.com") - ), - listOf("sample_group_id_1", "sample_group_id_2") - ) - val jsonString = """ + val sampleEmail = + Email( + "sampleAccountId", + listOf( + EmailRecipient("email1@email.com"), + EmailRecipient("email2@email.com"), + ), + listOf("sample_group_id_1", "sample_group_id_2"), + ) + val jsonString = + """ { "email_account_id2":"${sampleEmail.emailAccountID}", "recipient_list":[ @@ -100,7 +105,7 @@ internal class EmailTests { "${sampleEmail.emailGroupIds[1]}" ] }" - """.trimIndent() + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { Email.parse(it) } } @@ -109,11 +114,12 @@ internal class EmailTests { @Test fun `Email should accept without defaultRecipients and defaultEmailGroupIds in json object`() { val sampleEmail = Email("sampleAccountId", listOf(), listOf()) - val jsonString = """ + val jsonString = + """ { "email_account_id":"${sampleEmail.emailAccountID}" }" - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Email.parse(it) } assertEquals(sampleEmail, recreatedObject) } @@ -121,7 +127,8 @@ internal class EmailTests { @Test fun `Email should safely ignore extra field in json object`() { val sampleEmail = Email("sampleAccountId", listOf(), listOf()) - val jsonString = """ + val jsonString = + """ { "email_account_id":"${sampleEmail.emailAccountID}", "recipient_list2":[ @@ -133,7 +140,7 @@ internal class EmailTests { ], "another":"field" }" - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Email.parse(it) } assertEquals(sampleEmail, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/EventSourceTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/EventSourceTests.kt index b36a2fc0..79efc808 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/EventSourceTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/EventSourceTests.kt @@ -12,25 +12,26 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class EventSourceTests { - @Test fun `Event source serialize and deserialize should be equal`() { - val sampleEventSource = EventSource( - "title", - "reference_id", - severity = SeverityType.INFO - ) + val sampleEventSource = + EventSource( + "title", + "reference_id", + severity = SeverityType.INFO, + ) val recreatedObject = recreateObject(sampleEventSource) { EventSource(it) } assertEquals(sampleEventSource, recreatedObject) } @Test fun `Event source serialize and deserialize using json should be equal`() { - val sampleEventSource = EventSource( - "title", - "reference_id", - severity = SeverityType.INFO - ) + val sampleEventSource = + EventSource( + "title", + "reference_id", + severity = SeverityType.INFO, + ) val jsonString = getJsonString(sampleEventSource) val recreatedObject = createObjectFromJsonString(jsonString) { EventSource.parse(it) } @@ -39,45 +40,49 @@ internal class EventSourceTests { @Test fun `Event source should safely ignore extra field in json object`() { - val sampleEventSource = EventSource( - "title", - "reference_id", - severity = SeverityType.INFO, - tags = listOf("tag1", "tag2") - ) - val jsonString = """ - { - "title":"title", - "reference_id":"reference_id", - "feature":"alerting", - "severity":"info", - "tags":["tag1", "tag2"], - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val sampleEventSource = + EventSource( + "title", + "reference_id", + severity = SeverityType.INFO, + tags = listOf("tag1", "tag2"), + ) + val jsonString = + """ + { + "title":"title", + "reference_id":"reference_id", + "feature":"alerting", + "severity":"info", + "tags":["tag1", "tag2"], + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { EventSource.parse(it) } assertEquals(sampleEventSource, recreatedObject) } @Test fun `Event source should safely accepts unknown feature type in json object`() { - val sampleEventSource = EventSource( - "title", - "reference_id", - severity = SeverityType.INFO, - tags = listOf("tag1", "tag2") - ) - val jsonString = """ - { - "title":"title", - "reference_id":"reference_id", - "feature": "NewFeature", - "severity":"info", - "tags":["tag1", "tag2"] - } - """.trimIndent() + val sampleEventSource = + EventSource( + "title", + "reference_id", + severity = SeverityType.INFO, + tags = listOf("tag1", "tag2"), + ) + val jsonString = + """ + { + "title":"title", + "reference_id":"reference_id", + "feature": "NewFeature", + "severity":"info", + "tags":["tag1", "tag2"] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { EventSource.parse(it) } assertEquals(sampleEventSource, recreatedObject) } @@ -89,7 +94,7 @@ internal class EventSourceTests { "", "reference_id", severity = SeverityType.INFO, - tags = listOf("tag1", "tag2") + tags = listOf("tag1", "tag2"), ) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/EventStatusTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/EventStatusTests.kt index 94b48e64..e19ff09c 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/EventStatusTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/EventStatusTests.kt @@ -14,27 +14,28 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class EventStatusTests { - @Test fun `Event Status serialize and deserialize should be equal`() { - val sampleStatus = EventStatus( - "config_id", - "name", - ConfigType.SLACK, - deliveryStatus = DeliveryStatus("404", "invalid recipient") - ) + val sampleStatus = + EventStatus( + "config_id", + "name", + ConfigType.SLACK, + deliveryStatus = DeliveryStatus("404", "invalid recipient"), + ) val recreatedObject = recreateObject(sampleStatus) { EventStatus(it) } assertEquals(sampleStatus, recreatedObject) } @Test fun `Event Status serialize and deserialize using json should be equal`() { - val sampleStatus = EventStatus( - "config_id", - "name", - ConfigType.SLACK, - deliveryStatus = DeliveryStatus("404", "invalid recipient") - ) + val sampleStatus = + EventStatus( + "config_id", + "name", + ConfigType.SLACK, + deliveryStatus = DeliveryStatus("404", "invalid recipient"), + ) val jsonString = getJsonString(sampleStatus) val recreatedObject = createObjectFromJsonString(jsonString) { EventStatus.parse(it) } assertEquals(sampleStatus, recreatedObject) @@ -42,47 +43,50 @@ internal class EventStatusTests { @Test fun `Event Status should safely ignore extra field in json object`() { - val sampleStatus = EventStatus( - "config_id", - "name", - ConfigType.SLACK, - deliveryStatus = DeliveryStatus("404", "invalid recipient") - ) - val jsonString = """ - { - "config_id":"config_id", - "config_type":"slack", - "config_name":"name", - "email_recipient_status":[], - "delivery_status": - { - "status_code":"404", - "status_text":"invalid recipient" - }, - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val sampleStatus = + EventStatus( + "config_id", + "name", + ConfigType.SLACK, + deliveryStatus = DeliveryStatus("404", "invalid recipient"), + ) + val jsonString = + """ + { + "config_id":"config_id", + "config_type":"slack", + "config_name":"name", + "email_recipient_status":[], + "delivery_status": + { + "status_code":"404", + "status_text":"invalid recipient" + }, + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { EventStatus.parse(it) } assertEquals(sampleStatus, recreatedObject) } @Test fun `Event Status should throw exception when config type is email with empty emailRecipientList`() { - val jsonString = """ - { - "config_id":"config_id", - "config_type":"email", - "config_name":"name", - "delivery_status": - { - "status_code":"404", - "status_text":"invalid recipient" - }, - "email_recipient_status":[] - } - """.trimIndent() + val jsonString = + """ + { + "config_id":"config_id", + "config_type":"email", + "config_name":"name", + "delivery_status": + { + "status_code":"404", + "status_text":"invalid recipient" + }, + "email_recipient_status":[] + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { EventStatus.parse(it) } } @@ -102,7 +106,7 @@ internal class EventStatusTests { EventStatus( "config_id", "name", - ConfigType.SLACK + ConfigType.SLACK, ) } } @@ -113,7 +117,7 @@ internal class EventStatusTests { EventStatus( "config_id", "name", - ConfigType.CHIME + ConfigType.CHIME, ) } } @@ -124,7 +128,7 @@ internal class EventStatusTests { EventStatus( "config_id", "name", - ConfigType.MICROSOFT_TEAMS + ConfigType.MICROSOFT_TEAMS, ) } } @@ -135,7 +139,7 @@ internal class EventStatusTests { EventStatus( "config_id", "name", - ConfigType.WEBHOOK + ConfigType.WEBHOOK, ) } } @@ -146,7 +150,7 @@ internal class EventStatusTests { EventStatus( "config_id", "name", - ConfigType.EMAIL + ConfigType.EMAIL, ) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/FilterConfigListTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/FilterConfigListTests.kt index 11488e38..f4631eca 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/FilterConfigListTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/FilterConfigListTests.kt @@ -13,10 +13,9 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class FilterConfigListTests { - private fun assertSearchResultEquals( expected: ChannelList, - actual: ChannelList + actual: ChannelList, ) { assertEquals(expected.startIndex, actual.startIndex) assertEquals(expected.totalHits, actual.totalHits) @@ -27,12 +26,13 @@ internal class FilterConfigListTests { @Test fun `Search result serialize and deserialize with config object should be equal`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.SLACK - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.SLACK, + ) val searchResult = ChannelList(sampleConfig) val recreatedObject = recreateObject(searchResult) { ChannelList(it) } assertSearchResultEquals(searchResult, recreatedObject) @@ -40,48 +40,54 @@ internal class FilterConfigListTests { @Test fun `Search result serialize and deserialize with multiple config object should be equal`() { - val sampleConfig1 = Channel( - "config_id1", - "name1", - "description1", - ConfigType.SLACK - ) - val sampleConfig2 = Channel( - "config_id2", - "name2", - "description2", - ConfigType.CHIME - ) - val sampleConfig3 = Channel( - "config_id3", - "name3", - "description3", - ConfigType.WEBHOOK - ) - val sampleConfig4 = Channel( - "config_id4", - "name4", - "description4", - ConfigType.MICROSOFT_TEAMS - ) - val searchResult = ChannelList( - 100, - 1000, - TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, - listOf(sampleConfig1, sampleConfig2, sampleConfig3, sampleConfig4) - ) + val sampleConfig1 = + Channel( + "config_id1", + "name1", + "description1", + ConfigType.SLACK, + ) + val sampleConfig2 = + Channel( + "config_id2", + "name2", + "description2", + ConfigType.CHIME, + ) + val sampleConfig3 = + Channel( + "config_id3", + "name3", + "description3", + ConfigType.WEBHOOK, + ) + val sampleConfig4 = + Channel( + "config_id4", + "name4", + "description4", + ConfigType.MICROSOFT_TEAMS, + ) + val searchResult = + ChannelList( + 100, + 1000, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, + listOf(sampleConfig1, sampleConfig2, sampleConfig3, sampleConfig4), + ) val recreatedObject = recreateObject(searchResult) { ChannelList(it) } assertSearchResultEquals(searchResult, recreatedObject) } @Test fun `Search result serialize and deserialize using json config object should be equal`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.EMAIL_GROUP - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.EMAIL_GROUP, + ) val searchResult = ChannelList(sampleConfig) val jsonString = getJsonString(searchResult) val recreatedObject = createObjectFromJsonString(jsonString) { ChannelList(it) } @@ -90,36 +96,41 @@ internal class FilterConfigListTests { @Test fun `Search result serialize and deserialize using json with multiple config object should be equal`() { - val sampleConfig1 = Channel( - "config_id1", - "name1", - "description1", - ConfigType.SLACK - ) - val sampleConfig2 = Channel( - "config_id2", - "name2", - "description2", - ConfigType.CHIME - ) - val sampleConfig3 = Channel( - "config_id3", - "name3", - "description3", - ConfigType.WEBHOOK - ) - val sampleConfig4 = Channel( - "config_id4", - "name4", - "description4", - ConfigType.MICROSOFT_TEAMS - ) - val searchResult = ChannelList( - 100, - 1000, - TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, - listOf(sampleConfig1, sampleConfig2, sampleConfig3, sampleConfig4) - ) + val sampleConfig1 = + Channel( + "config_id1", + "name1", + "description1", + ConfigType.SLACK, + ) + val sampleConfig2 = + Channel( + "config_id2", + "name2", + "description2", + ConfigType.CHIME, + ) + val sampleConfig3 = + Channel( + "config_id3", + "name3", + "description3", + ConfigType.WEBHOOK, + ) + val sampleConfig4 = + Channel( + "config_id4", + "name4", + "description4", + ConfigType.MICROSOFT_TEAMS, + ) + val searchResult = + ChannelList( + 100, + 1000, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, + listOf(sampleConfig1, sampleConfig2, sampleConfig3, sampleConfig4), + ) val jsonString = getJsonString(searchResult) val recreatedObject = createObjectFromJsonString(jsonString) { ChannelList(it) } assertSearchResultEquals(searchResult, recreatedObject) @@ -127,100 +138,107 @@ internal class FilterConfigListTests { @Test fun `Search result should use isEnabled=true if absent in json object`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.EMAIL, - true - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.EMAIL, + true, + ) val searchResult = ChannelList(sampleConfig) - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq", - "channel_list":[ - { - "config_id":"config_id", - "name":"name", - "description":"description", - "config_type":"email" - } - ] - } - """.trimIndent() + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq", + "channel_list":[ + { + "config_id":"config_id", + "name":"name", + "description":"description", + "config_type":"email" + } + ] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { ChannelList(it) } assertSearchResultEquals(searchResult, recreatedObject) } @Test fun `Search result should safely ignore extra field in json object`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.EMAIL - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.EMAIL, + ) val searchResult = ChannelList(sampleConfig) - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq", - "channel_list":[ - { - "config_id":"config_id", - "name":"name", - "description":"description", - "config_type":"email", - "is_enabled":true - } - ], - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq", + "channel_list":[ + { + "config_id":"config_id", + "name":"name", + "description":"description", + "config_type":"email", + "is_enabled":true + } + ], + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { ChannelList(it) } assertSearchResultEquals(searchResult, recreatedObject) } @Test fun `Search result should safely fallback to default if startIndex, totalHits or totalHitRelation field absent in json object`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.EMAIL - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.EMAIL, + ) val searchResult = ChannelList(sampleConfig) - val jsonString = """ - { - "channel_list":[ - { - "config_id":"config_id", - "name":"name", - "description":"description", - "config_type":"email", - "is_enabled":true - } - ] - } - """.trimIndent() + val jsonString = + """ + { + "channel_list":[ + { + "config_id":"config_id", + "name":"name", + "description":"description", + "config_type":"email", + "is_enabled":true + } + ] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { ChannelList(it) } assertSearchResultEquals(searchResult, recreatedObject) } @Test fun `Search result should throw exception if channelList is absent in json`() { - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq" - } - """.trimIndent() + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq" + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { ChannelList(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/FilterConfigTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/FilterConfigTests.kt index c3557e89..5a85a0bd 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/FilterConfigTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/FilterConfigTests.kt @@ -12,40 +12,42 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class FilterConfigTests { - @Test fun `Config serialize and deserialize with default isEnabled flag should be equal`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.SLACK - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.SLACK, + ) val recreatedObject = recreateObject(sampleConfig) { Channel(it) } assertEquals(sampleConfig, recreatedObject) } @Test fun `Config serialize and deserialize with isEnabled=false should be equal`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.CHIME, - false - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.CHIME, + false, + ) val recreatedObject = recreateObject(sampleConfig) { Channel(it) } assertEquals(sampleConfig, recreatedObject) } @Test fun `Config serialize and deserialize using json object with default isEnabled flag should be equal`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.WEBHOOK - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.WEBHOOK, + ) val jsonString = getJsonString(sampleConfig) val recreatedObject = createObjectFromJsonString(jsonString) { Channel.parse(it) } assertEquals(sampleConfig, recreatedObject) @@ -53,13 +55,14 @@ internal class FilterConfigTests { @Test fun `Config serialize and deserialize using json object with isEnabled=false should be equal`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.EMAIL_GROUP, - false - ) + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.EMAIL_GROUP, + false, + ) val jsonString = getJsonString(sampleConfig) val recreatedObject = createObjectFromJsonString(jsonString) { Channel.parse(it) } assertEquals(sampleConfig, recreatedObject) @@ -67,44 +70,48 @@ internal class FilterConfigTests { @Test fun `Config should safely ignore extra field in json object`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.EMAIL - ) - val jsonString = """ - { - "config_id":"config_id", - "name":"name", - "description":"description", - "config_type":"email", - "is_enabled":true, - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.EMAIL, + ) + val jsonString = + """ + { + "config_id":"config_id", + "name":"name", + "description":"description", + "config_type":"email", + "is_enabled":true, + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Channel.parse(it) } assertEquals(sampleConfig, recreatedObject) } @Test fun `Config should safely ignore unknown config type in json object`() { - val sampleConfig = Channel( - "config_id", - "name", - "description", - ConfigType.NONE - ) - val jsonString = """ - { - "config_id":"config_id", - "name":"name", - "description":"description", - "config_type":"NewConfig" - } - """.trimIndent() + val sampleConfig = + Channel( + "config_id", + "name", + "description", + ConfigType.NONE, + ) + val jsonString = + """ + { + "config_id":"config_id", + "name":"name", + "description":"description", + "config_type":"NewConfig" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Channel.parse(it) } assertEquals(sampleConfig, recreatedObject) } @@ -116,7 +123,7 @@ internal class FilterConfigTests { "", "name", "description", - ConfigType.EMAIL_GROUP + ConfigType.EMAIL_GROUP, ) } } @@ -128,7 +135,7 @@ internal class FilterConfigTests { "config_id", "", "description", - ConfigType.EMAIL_GROUP + ConfigType.EMAIL_GROUP, ) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/MethodTypeTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/MethodTypeTests.kt index f9982d7c..d79164eb 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/MethodTypeTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/MethodTypeTests.kt @@ -10,7 +10,6 @@ import org.opensearch.commons.notifications.model.MethodType.Companion.enumParse import org.opensearch.commons.notifications.model.MethodType.Companion.fromTagOrDefault internal class MethodTypeTests { - @Test fun `toString should return tag`() { MethodType.values().forEach { diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeamsTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeamsTests.kt index 4543c06b..4dd760cb 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeamsTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeamsTests.kt @@ -14,7 +14,6 @@ import org.opensearch.commons.utils.recreateObject import java.net.MalformedURLException internal class MicrosoftTeamsTests { - @Test fun `Microsoft Teams serialize and deserialize transport object should be equal`() { val sampleMicrosoftTeams = MicrosoftTeams("https://domain.com/sample_url#1234567890") diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigInfoTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigInfoTests.kt index c4e28f33..2690b676 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigInfoTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigInfoTests.kt @@ -13,22 +13,23 @@ import org.opensearch.commons.utils.recreateObject import java.time.Instant internal class NotificationConfigInfoTests { - @Test fun `Config info serialize and deserialize with config object should be equal`() { val sampleSlack = Slack("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack - ) - val configInfo = NotificationConfigInfo( - "config_id", - Instant.now(), - Instant.now(), - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + ) + val configInfo = + NotificationConfigInfo( + "config_id", + Instant.now(), + Instant.now(), + sampleConfig, + ) val recreatedObject = recreateObject(configInfo) { NotificationConfigInfo(it) } assertEquals(configInfo, recreatedObject) } @@ -38,18 +39,20 @@ internal class NotificationConfigInfoTests { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) val sampleSlack = Slack("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack - ) - val configInfo = NotificationConfigInfo( - "config_id", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + ) + val configInfo = + NotificationConfigInfo( + "config_id", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig, + ) val jsonString = getJsonString(configInfo) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfigInfo.parse(it) } assertEquals(configInfo, recreatedObject) @@ -60,37 +63,40 @@ internal class NotificationConfigInfoTests { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack, - isEnabled = true - ) - val configInfo = NotificationConfigInfo( - "config-Id", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig - ) - val jsonString = """ - { - "config_id":"config-Id", - "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", - "created_time_ms":"${createdTimeMs.toEpochMilli()}", - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "feature_list":["index_management"], - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} - }, - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + isEnabled = true, + ) + val configInfo = + NotificationConfigInfo( + "config-Id", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig, + ) + val jsonString = + """ + { + "config_id":"config-Id", + "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", + "created_time_ms":"${createdTimeMs.toEpochMilli()}", + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "feature_list":["index_management"], + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + }, + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfigInfo.parse(it) } assertEquals(configInfo, recreatedObject) } @@ -98,18 +104,19 @@ internal class NotificationConfigInfoTests { @Test fun `Config info should throw exception if configId is empty`() { val sampleSlack = Slack("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + ) Assertions.assertThrows(IllegalArgumentException::class.java) { NotificationConfigInfo( "", Instant.now(), Instant.now(), - sampleConfig + sampleConfig, ) } } @@ -118,20 +125,21 @@ internal class NotificationConfigInfoTests { fun `Config info should throw exception if configId is absent in json`() { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) - val jsonString = """ - { - "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", - "created_time_ms":"${createdTimeMs.toEpochMilli()}", - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "feature_list":["index_management"], - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + val jsonString = + """ + { + "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", + "created_time_ms":"${createdTimeMs.toEpochMilli()}", + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "feature_list":["index_management"], + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + } } - } - """.trimIndent() + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { NotificationConfigInfo.parse(it) } } @@ -141,20 +149,21 @@ internal class NotificationConfigInfoTests { fun `Config info should throw exception if lastUpdatedTimeMs is absent in json`() { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) - val jsonString = """ - { - "config_id":"config-Id", - "created_time_ms":"${createdTimeMs.toEpochMilli()}", - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "feature_list":["index_management"], - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + val jsonString = + """ + { + "config_id":"config-Id", + "created_time_ms":"${createdTimeMs.toEpochMilli()}", + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "feature_list":["index_management"], + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + } } - } - """.trimIndent() + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { NotificationConfigInfo.parse(it) } } @@ -163,20 +172,21 @@ internal class NotificationConfigInfoTests { @Test fun `Config info should throw exception if createdTimeMs is absent in json`() { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) - val jsonString = """ - { - "config_id":"config-Id", - "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "feature_list":["index_management"], - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + val jsonString = + """ + { + "config_id":"config-Id", + "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "feature_list":["index_management"], + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + } } - } - """.trimIndent() + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { NotificationConfigInfo.parse(it) } } @@ -186,13 +196,14 @@ internal class NotificationConfigInfoTests { fun `Config info should throw exception if notificationConfig is absent in json`() { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) - val jsonString = """ - { - "config_id":"config-Id", - "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", - "created_time_ms":"${createdTimeMs.toEpochMilli()}" - } - """.trimIndent() + val jsonString = + """ + { + "config_id":"config-Id", + "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", + "created_time_ms":"${createdTimeMs.toEpochMilli()}" + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { NotificationConfigInfo.parse(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigSearchResultsTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigSearchResultsTests.kt index 06bb3557..e5bd3d25 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigSearchResultsTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigSearchResultsTests.kt @@ -14,10 +14,9 @@ import org.opensearch.commons.utils.recreateObject import java.time.Instant internal class NotificationConfigSearchResultsTests { - private fun assertSearchResultEquals( expected: NotificationConfigSearchResult, - actual: NotificationConfigSearchResult + actual: NotificationConfigSearchResult, ) { assertEquals(expected.startIndex, actual.startIndex) assertEquals(expected.totalHits, actual.totalHits) @@ -29,18 +28,20 @@ internal class NotificationConfigSearchResultsTests { @Test fun `Search result serialize and deserialize with config object should be equal`() { val sampleSlack = Slack("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack - ) - val configInfo = NotificationConfigInfo( - "config_id", - Instant.now(), - Instant.now(), - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + ) + val configInfo = + NotificationConfigInfo( + "config_id", + Instant.now(), + Instant.now(), + sampleConfig, + ) val searchResult = NotificationConfigSearchResult(configInfo) val recreatedObject = recreateObject(searchResult) { NotificationConfigSearchResult(it) } assertSearchResultEquals(searchResult, recreatedObject) @@ -48,73 +49,83 @@ internal class NotificationConfigSearchResultsTests { @Test fun `Search result serialize and deserialize with multiple config default values should be equal`() { - val sampleConfig1 = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = Slack("https://domain.com/sample_url#1234567890") - ) - val configInfo1 = NotificationConfigInfo( - "config_id1", - Instant.now(), - Instant.now(), - sampleConfig1 - ) - val sampleConfig2 = NotificationConfig( - "name", - "description", - ConfigType.CHIME, - configData = Chime("https://domain.com/sample_url#1234567890") - ) - val configInfo2 = NotificationConfigInfo( - "config_id2", - Instant.now(), - Instant.now(), - sampleConfig2 - ) + val sampleConfig1 = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = Slack("https://domain.com/sample_url#1234567890"), + ) + val configInfo1 = + NotificationConfigInfo( + "config_id1", + Instant.now(), + Instant.now(), + sampleConfig1, + ) + val sampleConfig2 = + NotificationConfig( + "name", + "description", + ConfigType.CHIME, + configData = Chime("https://domain.com/sample_url#1234567890"), + ) + val configInfo2 = + NotificationConfigInfo( + "config_id2", + Instant.now(), + Instant.now(), + sampleConfig2, + ) val searchResult = NotificationConfigSearchResult(listOf(configInfo1, configInfo2)) - val expectedResult = NotificationConfigSearchResult( - 0, - 2, - TotalHits.Relation.EQUAL_TO, - listOf(configInfo1, configInfo2) - ) + val expectedResult = + NotificationConfigSearchResult( + 0, + 2, + TotalHits.Relation.EQUAL_TO, + listOf(configInfo1, configInfo2), + ) val recreatedObject = recreateObject(searchResult) { NotificationConfigSearchResult(it) } assertSearchResultEquals(expectedResult, recreatedObject) } @Test fun `Search result serialize and deserialize with multiple config object should be equal`() { - val sampleConfig1 = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = Slack("https://domain.com/sample_url#1234567890") - ) - val configInfo1 = NotificationConfigInfo( - "config_id1", - Instant.now(), - Instant.now(), - sampleConfig1 - ) - val sampleConfig2 = NotificationConfig( - "name", - "description", - ConfigType.CHIME, - configData = Chime("https://domain.com/sample_url#1234567890") - ) - val configInfo2 = NotificationConfigInfo( - "config_id2", - Instant.now(), - Instant.now(), - sampleConfig2 - ) - val searchResult = NotificationConfigSearchResult( - 100, - 1000, - TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, - listOf(configInfo1, configInfo2) - ) + val sampleConfig1 = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = Slack("https://domain.com/sample_url#1234567890"), + ) + val configInfo1 = + NotificationConfigInfo( + "config_id1", + Instant.now(), + Instant.now(), + sampleConfig1, + ) + val sampleConfig2 = + NotificationConfig( + "name", + "description", + ConfigType.CHIME, + configData = Chime("https://domain.com/sample_url#1234567890"), + ) + val configInfo2 = + NotificationConfigInfo( + "config_id2", + Instant.now(), + Instant.now(), + sampleConfig2, + ) + val searchResult = + NotificationConfigSearchResult( + 100, + 1000, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, + listOf(configInfo1, configInfo2), + ) val recreatedObject = recreateObject(searchResult) { NotificationConfigSearchResult(it) } assertSearchResultEquals(searchResult, recreatedObject) } @@ -124,18 +135,20 @@ internal class NotificationConfigSearchResultsTests { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) val sampleSlack = Slack("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack - ) - val configInfo = NotificationConfigInfo( - "config_id", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + ) + val configInfo = + NotificationConfigInfo( + "config_id", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig, + ) val searchResult = NotificationConfigSearchResult(configInfo) val jsonString = getJsonString(searchResult) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfigSearchResult(it) } @@ -146,36 +159,41 @@ internal class NotificationConfigSearchResultsTests { fun `Search result serialize and deserialize using json with multiple config object should be equal`() { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) - val sampleConfig1 = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = Slack("https://domain.com/sample_url#1234567890") - ) - val configInfo1 = NotificationConfigInfo( - "config_id1", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig1 - ) - val sampleConfig2 = NotificationConfig( - "name", - "description", - ConfigType.CHIME, - configData = Chime("https://domain.com/sample_url#1234567890") - ) - val configInfo2 = NotificationConfigInfo( - "config_id2", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig2 - ) - val searchResult = NotificationConfigSearchResult( - 100, - 1000, - TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, - listOf(configInfo1, configInfo2) - ) + val sampleConfig1 = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = Slack("https://domain.com/sample_url#1234567890"), + ) + val configInfo1 = + NotificationConfigInfo( + "config_id1", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig1, + ) + val sampleConfig2 = + NotificationConfig( + "name", + "description", + ConfigType.CHIME, + configData = Chime("https://domain.com/sample_url#1234567890"), + ) + val configInfo2 = + NotificationConfigInfo( + "config_id2", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig2, + ) + val searchResult = + NotificationConfigSearchResult( + 100, + 1000, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO, + listOf(configInfo1, configInfo2), + ) val jsonString = getJsonString(searchResult) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfigSearchResult(it) } assertSearchResultEquals(searchResult, recreatedObject) @@ -186,45 +204,48 @@ internal class NotificationConfigSearchResultsTests { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack, - isEnabled = true - ) - val configInfo = NotificationConfigInfo( - "config-Id", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + isEnabled = true, + ) + val configInfo = + NotificationConfigInfo( + "config-Id", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig, + ) val searchResult = NotificationConfigSearchResult(configInfo) - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq", - "config_list":[ - { - "config_id":"config-Id", - "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", - "created_time_ms":"${createdTimeMs.toEpochMilli()}", - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "feature_list":["index_management"], - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq", + "config_list":[ + { + "config_id":"config-Id", + "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", + "created_time_ms":"${createdTimeMs.toEpochMilli()}", + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "feature_list":["index_management"], + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + } } - } - ], - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + ], + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfigSearchResult(it) } assertSearchResultEquals(searchResult, recreatedObject) } @@ -234,39 +255,42 @@ internal class NotificationConfigSearchResultsTests { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack, - isEnabled = true - ) - val configInfo = NotificationConfigInfo( - "config-Id", - lastUpdatedTimeMs, - createdTimeMs, - sampleConfig - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + isEnabled = true, + ) + val configInfo = + NotificationConfigInfo( + "config-Id", + lastUpdatedTimeMs, + createdTimeMs, + sampleConfig, + ) val searchResult = NotificationConfigSearchResult(configInfo) - val jsonString = """ - { - "config_list":[ - { - "config_id":"config-Id", - "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", - "created_time_ms":"${createdTimeMs.toEpochMilli()}", - "config":{ - "name":"name", - "description":"description", - "config_type":"slack", - "feature_list":["index_management"], - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + val jsonString = + """ + { + "config_list":[ + { + "config_id":"config-Id", + "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", + "created_time_ms":"${createdTimeMs.toEpochMilli()}", + "config":{ + "name":"name", + "description":"description", + "config_type":"slack", + "feature_list":["index_management"], + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"} + } } - } - ] - } - """.trimIndent() + ] + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfigSearchResult(it) } assertSearchResultEquals(searchResult, recreatedObject) } @@ -275,20 +299,21 @@ internal class NotificationConfigSearchResultsTests { fun `Search result should throw exception if notificationConfigs is absent in json`() { val lastUpdatedTimeMs = Instant.ofEpochMilli(Instant.now().toEpochMilli()) val createdTimeMs = lastUpdatedTimeMs.minusSeconds(1000) - val jsonString = """ - { - "start_index":"0", - "total_hits":"1", - "total_hit_relation":"eq", - "config_list":[ - { - "config_id":"config-Id", - "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", - "created_time_ms":"${createdTimeMs.toEpochMilli()}" - } - ] - } - """.trimIndent() + val jsonString = + """ + { + "start_index":"0", + "total_hits":"1", + "total_hit_relation":"eq", + "config_list":[ + { + "config_id":"config-Id", + "last_updated_time_ms":"${lastUpdatedTimeMs.toEpochMilli()}", + "created_time_ms":"${createdTimeMs.toEpochMilli()}" + } + ] + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { NotificationConfigSearchResult(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigTests.kt index ee17777a..d70f6491 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigTests.kt @@ -11,16 +11,16 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class NotificationConfigTests { - @Test fun `Config serialize and deserialize with slack object should be equal`() { val sampleSlack = Slack("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + ) val recreatedObject = recreateObject(sampleConfig) { NotificationConfig(it) } assertEquals(sampleConfig, recreatedObject) } @@ -28,12 +28,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize using json slack object should be equal`() { val sampleSlack = Slack("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SLACK, - configData = sampleSlack - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SLACK, + configData = sampleSlack, + ) val jsonString = getJsonString(sampleConfig) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfig.parse(it) } assertEquals(sampleConfig, recreatedObject) @@ -42,12 +43,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with chime object should be equal`() { val sampleChime = Chime("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.CHIME, - configData = sampleChime - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.CHIME, + configData = sampleChime, + ) val recreatedObject = recreateObject(sampleConfig) { NotificationConfig(it) } assertEquals(sampleConfig, recreatedObject) } @@ -55,12 +57,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with json chime object should be equal`() { val sampleChime = Chime("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.CHIME, - configData = sampleChime - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.CHIME, + configData = sampleChime, + ) val jsonString = getJsonString(sampleConfig) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfig.parse(it) } assertEquals(sampleConfig, recreatedObject) @@ -69,12 +72,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with microsoft teams object should be equal`() { val sampleMicrosoftTeams = MicrosoftTeams("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.MICROSOFT_TEAMS, - configData = sampleMicrosoftTeams - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.MICROSOFT_TEAMS, + configData = sampleMicrosoftTeams, + ) val recreatedObject = recreateObject(sampleConfig) { NotificationConfig(it) } assertEquals(sampleConfig, recreatedObject) } @@ -82,12 +86,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with json microsoft teams object should be equal`() { val sampleMicrosoftTeams = MicrosoftTeams("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.MICROSOFT_TEAMS, - configData = sampleMicrosoftTeams - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.MICROSOFT_TEAMS, + configData = sampleMicrosoftTeams, + ) val jsonString = getJsonString(sampleConfig) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfig.parse(it) } assertEquals(sampleConfig, recreatedObject) @@ -96,12 +101,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with webhook object should be equal`() { val sampleWebhook = Webhook("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.WEBHOOK, - configData = sampleWebhook - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.WEBHOOK, + configData = sampleWebhook, + ) val recreatedObject = recreateObject(sampleConfig) { NotificationConfig(it) } assertEquals(sampleConfig, recreatedObject) } @@ -109,12 +115,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with json webhook object should be equal`() { val sampleWebhook = Webhook("https://domain.com/sample_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.WEBHOOK, - configData = sampleWebhook - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.WEBHOOK, + configData = sampleWebhook, + ) val jsonString = getJsonString(sampleConfig) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfig.parse(it) } assertEquals(sampleConfig, recreatedObject) @@ -123,12 +130,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with email object should be equal`() { val sampleEmail = Email("id_1234567890", listOf(EmailRecipient("email@domain.com")), listOf("groupId")) - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.EMAIL, - configData = sampleEmail - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.EMAIL, + configData = sampleEmail, + ) val recreatedObject = recreateObject(sampleConfig) { NotificationConfig(it) } assertEquals(sampleConfig, recreatedObject) } @@ -136,12 +144,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with json email object should be equal`() { val sampleEmail = Email("id_1234567890", listOf(EmailRecipient("email@domain.com")), listOf("groupId")) - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.EMAIL, - configData = sampleEmail - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.EMAIL, + configData = sampleEmail, + ) val jsonString = getJsonString(sampleConfig) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfig.parse(it) } assertEquals(sampleConfig, recreatedObject) @@ -150,12 +159,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with json smtpAccount object should be equal`() { val smtpAccount = SmtpAccount("domain.com", 1234, MethodType.SSL, "from@domain.com") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SMTP_ACCOUNT, - configData = smtpAccount - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SMTP_ACCOUNT, + configData = smtpAccount, + ) val jsonString = getJsonString(sampleConfig) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfig.parse(it) } assertEquals(sampleConfig, recreatedObject) @@ -164,12 +174,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with smtpAccount object should be equal`() { val sampleSmtpAccount = SmtpAccount("domain.com", 1234, MethodType.SSL, "from@domain.com") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.SMTP_ACCOUNT, - configData = sampleSmtpAccount - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.SMTP_ACCOUNT, + configData = sampleSmtpAccount, + ) val recreatedObject = recreateObject(sampleConfig) { NotificationConfig(it) } assertEquals(sampleConfig, recreatedObject) } @@ -177,12 +188,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with json emailGroup object should be equal`() { val sampleEmailGroup = EmailGroup(listOf(EmailRecipient("email@domain.com"))) - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.EMAIL_GROUP, - configData = sampleEmailGroup - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.EMAIL_GROUP, + configData = sampleEmailGroup, + ) val jsonString = getJsonString(sampleConfig) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfig.parse(it) } assertEquals(sampleConfig, recreatedObject) @@ -191,12 +203,13 @@ internal class NotificationConfigTests { @Test fun `Config serialize and deserialize with emailGroup object should be equal`() { val sampleEmailGroup = EmailGroup(listOf(EmailRecipient("email@domain.com"))) - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.EMAIL_GROUP, - configData = sampleEmailGroup - ) + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.EMAIL_GROUP, + configData = sampleEmailGroup, + ) val recreatedObject = recreateObject(sampleConfig) { NotificationConfig(it) } assertEquals(sampleConfig, recreatedObject) } @@ -204,27 +217,29 @@ internal class NotificationConfigTests { @Test fun `Config should safely ignore unknown config type in json object`() { val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.NONE, - configData = sampleSlack, - isEnabled = true - ) - val jsonString = """ - { - "name":"name", - "description":"description", - "config_type":"NewConfig", - "feature_list":["index_management"], - "is_enabled":true, - "slack":{"url":"https://domain.com/sample_slack_url#1234567890"}, - "chime":{"url":"https://domain.com/sample_chime_url#1234567890"}, - "webhook":{"url":"https://domain.com/sample_webhook_url#1234567890"}, - "new_config1":{"newField1":"new value 1"}, - "new_config2":{"newField2":"new value 2"} - } - """.trimIndent() + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.NONE, + configData = sampleSlack, + isEnabled = true, + ) + val jsonString = + """ + { + "name":"name", + "description":"description", + "config_type":"NewConfig", + "feature_list":["index_management"], + "is_enabled":true, + "slack":{"url":"https://domain.com/sample_slack_url#1234567890"}, + "chime":{"url":"https://domain.com/sample_chime_url#1234567890"}, + "webhook":{"url":"https://domain.com/sample_webhook_url#1234567890"}, + "new_config1":{"newField1":"new value 1"}, + "new_config2":{"newField2":"new value 2"} + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfig.parse(it) } assertEquals(sampleConfig, recreatedObject) } @@ -232,23 +247,25 @@ internal class NotificationConfigTests { @Test fun `Config should safely accepts unknown feature type in json object`() { val sampleWebhook = Webhook("https://domain.com/sample_webhook_url#1234567890") - val sampleConfig = NotificationConfig( - "name", - "description", - ConfigType.WEBHOOK, - configData = sampleWebhook, - isEnabled = true - ) - val jsonString = """ - { - "name":"name", - "description":"description", - "config_type":"webhook", - "feature_list":["index_management", "NewFeature1", "NewFeature2"], - "is_enabled":true, - "webhook":{"url":"https://domain.com/sample_webhook_url#1234567890"} - } - """.trimIndent() + val sampleConfig = + NotificationConfig( + "name", + "description", + ConfigType.WEBHOOK, + configData = sampleWebhook, + isEnabled = true, + ) + val jsonString = + """ + { + "name":"name", + "description":"description", + "config_type":"webhook", + "feature_list":["index_management", "NewFeature1", "NewFeature2"], + "is_enabled":true, + "webhook":{"url":"https://domain.com/sample_webhook_url#1234567890"} + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { NotificationConfig.parse(it) } assertEquals(sampleConfig, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationEventTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationEventTests.kt index 57df6066..691e5b1e 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationEventTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationEventTests.kt @@ -12,20 +12,21 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class NotificationEventTests { - @Test fun `Notification event serialize and deserialize should be equal`() { - val sampleEventSource = EventSource( - "title", - "reference_id", - severity = SeverityType.INFO - ) - val sampleStatus = EventStatus( - "config_id", - "name", - ConfigType.SLACK, - deliveryStatus = DeliveryStatus("404", "invalid recipient") - ) + val sampleEventSource = + EventSource( + "title", + "reference_id", + severity = SeverityType.INFO, + ) + val sampleStatus = + EventStatus( + "config_id", + "name", + ConfigType.SLACK, + deliveryStatus = DeliveryStatus("404", "invalid recipient"), + ) val sampleEvent = NotificationEvent(sampleEventSource, listOf(sampleStatus)) val recreatedObject = recreateObject(sampleEvent) { NotificationEvent(it) } assertEquals(sampleEvent, recreatedObject) @@ -33,17 +34,19 @@ internal class NotificationEventTests { @Test fun `Notification event serialize and deserialize using json should be equal`() { - val sampleEventSource = EventSource( - "title", - "reference_id", - severity = SeverityType.INFO - ) - val sampleStatus = EventStatus( - "config_id", - "name", - ConfigType.CHIME, - deliveryStatus = DeliveryStatus("200", "success") - ) + val sampleEventSource = + EventSource( + "title", + "reference_id", + severity = SeverityType.INFO, + ) + val sampleStatus = + EventStatus( + "config_id", + "name", + ConfigType.CHIME, + deliveryStatus = DeliveryStatus("200", "success"), + ) val sampleEvent = NotificationEvent(sampleEventSource, listOf(sampleStatus)) val jsonString = getJsonString(sampleEvent) val recreatedObject = createObjectFromJsonString(jsonString) { NotificationEvent.parse(it) } @@ -52,83 +55,88 @@ internal class NotificationEventTests { @Test fun `Notification event should safely ignore extra field in json object`() { - val sampleEventSource = EventSource( - "title", - "reference_id", - severity = SeverityType.INFO, - tags = listOf("tag1", "tag2") - ) - val status1 = EventStatus( - "config_id1", - "name 1", - ConfigType.CHIME, - deliveryStatus = DeliveryStatus("200", "success") - ) - val status2 = EventStatus( - "config_id2", - "name 2", - ConfigType.SLACK, - deliveryStatus = DeliveryStatus("503", "service unavailable") - ) + val sampleEventSource = + EventSource( + "title", + "reference_id", + severity = SeverityType.INFO, + tags = listOf("tag1", "tag2"), + ) + val status1 = + EventStatus( + "config_id1", + "name 1", + ConfigType.CHIME, + deliveryStatus = DeliveryStatus("200", "success"), + ) + val status2 = + EventStatus( + "config_id2", + "name 2", + ConfigType.SLACK, + deliveryStatus = DeliveryStatus("503", "service unavailable"), + ) val sampleEvent = NotificationEvent(sampleEventSource, listOf(status1, status2)) - val jsonString = """ - { - "event_source":{ - "title":"title", - "reference_id":"reference_id", - "feature":"alerting", - "severity":"info", - "tags":["tag1", "tag2"] - }, - "status_list":[ - { - "config_id":"config_id1", - "config_type":"chime", - "config_name":"name 1", - "delivery_status": - { - "status_code":"200", - "status_text":"success" - } + val jsonString = + """ + { + "event_source":{ + "title":"title", + "reference_id":"reference_id", + "feature":"alerting", + "severity":"info", + "tags":["tag1", "tag2"] }, - { - "config_id":"config_id2", - "config_type":"slack", - "config_name":"name 2", - "delivery_status": - { - "status_code":"503", - "status_text":"service unavailable" - } - } - ], - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + "status_list":[ + { + "config_id":"config_id1", + "config_type":"chime", + "config_name":"name 1", + "delivery_status": + { + "status_code":"200", + "status_text":"success" + } + }, + { + "config_id":"config_id2", + "config_type":"slack", + "config_name":"name 2", + "delivery_status": + { + "status_code":"503", + "status_text":"service unavailable" + } + } + ], + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { NotificationEvent.parse(it) } assertEquals(sampleEvent, recreatedObject) } @Test fun `Notification event throw exception if event source is absent`() { - val jsonString = """ - { - "status_list":[ - { - "config_id":"config_id", - "config_type":"chime", - "config_name":"name", - "delivery_status": - { - "status_code":"200", - "status_text":"success" - } - } - ] - } - """.trimIndent() + val jsonString = + """ + { + "status_list":[ + { + "config_id":"config_id", + "config_type":"chime", + "config_name":"name", + "delivery_status": + { + "status_code":"200", + "status_text":"success" + } + } + ] + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { NotificationEvent.parse(it) } } @@ -136,17 +144,18 @@ internal class NotificationEventTests { @Test fun `Notification event throw exception if status_list is absent`() { - val jsonString = """ - { - "event_source":{ - "title":"title", - "reference_id":"reference_id", - "feature":"alerting", - "severity":"info", - "tags":["tag1", "tag2"] + val jsonString = + """ + { + "event_source":{ + "title":"title", + "reference_id":"reference_id", + "feature":"alerting", + "severity":"info", + "tags":["tag1", "tag2"] + } } - } - """.trimIndent() + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { NotificationEvent.parse(it) } } @@ -154,18 +163,19 @@ internal class NotificationEventTests { @Test fun `Notification event throw exception if status_list is empty`() { - val jsonString = """ - { - "event_source":{ - "title":"title", - "reference_id":"reference_id", - "feature":"alerting", - "severity":"info", - "tags":["tag1", "tag2"] - }, - "status_list":[] - } - """.trimIndent() + val jsonString = + """ + { + "event_source":{ + "title":"title", + "reference_id":"reference_id", + "feature":"alerting", + "severity":"info", + "tags":["tag1", "tag2"] + }, + "status_list":[] + } + """.trimIndent() Assertions.assertThrows(IllegalArgumentException::class.java) { createObjectFromJsonString(jsonString) { NotificationEvent.parse(it) } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/SesAccountTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/SesAccountTests.kt index e5a52837..ea8b0c8c 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/SesAccountTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/SesAccountTests.kt @@ -14,18 +14,18 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class SesAccountTests { - @Test fun `SES should throw exception if empty region`() { assertThrows { SesAccount("", null, "from@domain.com") } - val jsonString = """ - { - "region":"", - "from_address":"from@domain.com" - } - """.trimIndent() + val jsonString = + """ + { + "region":"", + "from_address":"from@domain.com" + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { SesAccount.parse(it) } } @@ -36,13 +36,14 @@ internal class SesAccountTests { assertThrows { SesAccount("us-east-1", "arn:aws:iam:us-east-1:0123456789:role-test", "from@domain.com") } - val jsonString = """ - { - "region":"us-east-1", - "role_arn":"arn:aws:iam:us-east-1:0123456789:role-test", - "from_address":"from@domain.com" - } - """.trimIndent() + val jsonString = + """ + { + "region":"us-east-1", + "role_arn":"arn:aws:iam:us-east-1:0123456789:role-test", + "from_address":"from@domain.com" + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { SesAccount.parse(it) } } @@ -50,12 +51,13 @@ internal class SesAccountTests { @Test fun `SES should throw exception when email id is invalid`() { - val jsonString = """ - { - "region":"us-east-1", - "from_address":".from@domain.com" - } - """.trimIndent() + val jsonString = + """ + { + "region":"us-east-1", + "from_address":".from@domain.com" + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { SesAccount.parse(it) } } @@ -87,13 +89,14 @@ internal class SesAccountTests { @Test fun `SES should deserialize json object using parser`() { val sesAccount = SesAccount("us-east-1", "arn:aws:iam::012345678912:role/iam-test", "from@domain.com") - val jsonString = """ - { - "region":"${sesAccount.awsRegion}", - "role_arn":"${sesAccount.roleArn}", - "from_address":"${sesAccount.fromAddress}" - } - """.trimIndent() + val jsonString = + """ + { + "region":"${sesAccount.awsRegion}", + "role_arn":"${sesAccount.roleArn}", + "from_address":"${sesAccount.fromAddress}" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { SesAccount.parse(it) } assertEquals(sesAccount, recreatedObject) } @@ -101,13 +104,14 @@ internal class SesAccountTests { @Test fun `SES should deserialize json object will null role_arn using parser`() { val sesAccount = SesAccount("us-east-1", null, "from@domain.com") - val jsonString = """ - { - "region":"${sesAccount.awsRegion}", - "role_arn":null, - "from_address":"${sesAccount.fromAddress}" - } - """.trimIndent() + val jsonString = + """ + { + "region":"${sesAccount.awsRegion}", + "role_arn":null, + "from_address":"${sesAccount.fromAddress}" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { SesAccount.parse(it) } assertEquals(sesAccount, recreatedObject) } @@ -115,12 +119,13 @@ internal class SesAccountTests { @Test fun `SES should deserialize json object will missing role_arn using parser`() { val sesAccount = SesAccount("us-east-1", null, "from@domain.com") - val jsonString = """ - { - "region":"${sesAccount.awsRegion}", - "from_address":"${sesAccount.fromAddress}" - } - """.trimIndent() + val jsonString = + """ + { + "region":"${sesAccount.awsRegion}", + "from_address":"${sesAccount.fromAddress}" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { SesAccount.parse(it) } assertEquals(sesAccount, recreatedObject) } @@ -135,13 +140,14 @@ internal class SesAccountTests { @Test fun `SES should throw exception when region is replace with region2 in json object`() { - val jsonString = """ - { - "region2":"us-east-1", - "role_arn":"arn:aws:iam::012345678912:role/iam-test", - "from_address":"from@domain.com" - } - """.trimIndent() + val jsonString = + """ + { + "region2":"us-east-1", + "role_arn":"arn:aws:iam::012345678912:role/iam-test", + "from_address":"from@domain.com" + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { SesAccount.parse(it) } } @@ -149,13 +155,14 @@ internal class SesAccountTests { @Test fun `SES should throw exception when from_address is replace with from_address2 in json object`() { - val jsonString = """ - { - "region":"us-east-1", - "role_arn":"arn:aws:iam::012345678912:role/iam-test", - "from_address2":"from@domain.com" - } - """.trimIndent() + val jsonString = + """ + { + "region":"us-east-1", + "role_arn":"arn:aws:iam::012345678912:role/iam-test", + "from_address2":"from@domain.com" + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { SesAccount.parse(it) } } @@ -164,16 +171,17 @@ internal class SesAccountTests { @Test fun `SES should safely ignore extra field in json object`() { val sesAccount = SesAccount("us-east-1", "arn:aws:iam::012345678912:role/iam-test", "from@domain.com") - val jsonString = """ - { - "region":"${sesAccount.awsRegion}", - "role_arn":"${sesAccount.roleArn}", - "from_address":"${sesAccount.fromAddress}", - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() + val jsonString = + """ + { + "region":"${sesAccount.awsRegion}", + "role_arn":"${sesAccount.roleArn}", + "from_address":"${sesAccount.fromAddress}", + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { SesAccount.parse(it) } assertEquals(sesAccount, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/SeverityTypeTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/SeverityTypeTests.kt index 35f7b218..938755ee 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/SeverityTypeTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/SeverityTypeTests.kt @@ -10,7 +10,6 @@ import org.opensearch.commons.notifications.model.SeverityType.Companion.enumPar import org.opensearch.commons.notifications.model.SeverityType.Companion.fromTagOrDefault internal class SeverityTypeTests { - @Test fun `toString should return tag`() { SeverityType.values().forEach { diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/SlackTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/SlackTests.kt index 5c64c6ae..6d8b8014 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/SlackTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/SlackTests.kt @@ -14,7 +14,6 @@ import org.opensearch.commons.utils.recreateObject import java.net.MalformedURLException internal class SlackTests { - @Test fun `Slack serialize and deserialize transport object should be equal`() { val sampleSlack = Slack("https://domain.com/sample_url#1234567890") diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/SmtpAccountTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/SmtpAccountTests.kt index 6617d1f6..2777c978 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/SmtpAccountTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/SmtpAccountTests.kt @@ -13,7 +13,6 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class SmtpAccountTests { - @Test fun `SmtpAccount serialize and deserialize transport object should be equal`() { val sampleSmtpAccount = SmtpAccount("domain.com", 1234, MethodType.SSL, "from@domain.com") @@ -32,14 +31,15 @@ internal class SmtpAccountTests { @Test fun `SmtpAccount should deserialize json object using parser`() { val sampleSmtpAccount = SmtpAccount("domain.com", 1234, MethodType.SSL, "from@domain.com") - val jsonString = """ - { - "host":"domain.com", - "port":"1234", - "method":"ssl", - "from_address":"from@domain.com" - } - """.trimIndent() + val jsonString = + """ + { + "host":"domain.com", + "port":"1234", + "method":"ssl", + "from_address":"from@domain.com" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { SmtpAccount.parse(it) } assertEquals(sampleSmtpAccount, recreatedObject) } @@ -54,14 +54,15 @@ internal class SmtpAccountTests { @Test fun `SmtpAccount should throw exception when email id is invalid`() { - val jsonString = """ - { - "host":"domain.com", - "port":"1234", - "method":"ssl", - "from_address":".from@domain.com" - } - """.trimIndent() + val jsonString = + """ + { + "host":"domain.com", + "port":"1234", + "method":"ssl", + "from_address":".from@domain.com" + } + """.trimIndent() assertThrows { createObjectFromJsonString(jsonString) { SmtpAccount.parse(it) } } @@ -69,22 +70,24 @@ internal class SmtpAccountTests { @Test fun `SmtpAccount should safely ignore extra field in json object`() { - val sampleSmtpAccount = SmtpAccount( - "domain.com", - 1234, - MethodType.START_TLS, - "from@domain.com" - ) - val jsonString = """ - { - "host":"domain.com", - "port":"1234", - "method":"start_tls", - "from_address":"from@domain.com", - "extra_field_1":"extra value 1", - "extra_field_2":"extra value 2" - } - """.trimIndent() + val sampleSmtpAccount = + SmtpAccount( + "domain.com", + 1234, + MethodType.START_TLS, + "from@domain.com", + ) + val jsonString = + """ + { + "host":"domain.com", + "port":"1234", + "method":"start_tls", + "from_address":"from@domain.com", + "extra_field_1":"extra value 1", + "extra_field_2":"extra value 2" + } + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { SmtpAccount.parse(it) } assertEquals(sampleSmtpAccount, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/SnsTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/SnsTests.kt index f81e8d3f..2d1b337d 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/SnsTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/SnsTests.kt @@ -15,7 +15,6 @@ import org.opensearch.commons.utils.getJsonString import org.opensearch.commons.utils.recreateObject internal class SnsTests { - @Test fun `SNS should throw exception if empty topic`() { assertThrows(IllegalArgumentException::class.java) { @@ -55,7 +54,7 @@ internal class SnsTests { try { Sns( "arn:aws:sns:ap-southeast-2:333654771707:sns-fifo-alerting.fifo", - "arn:aws:iam::012345678912:role/iam-test" + "arn:aws:iam::012345678912:role/iam-test", ) } catch (e: Exception) { fail("Expected fifo sns topic ARN to be validated successfully", e) diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/WebhookTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/WebhookTests.kt index 3272203d..37960550 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/WebhookTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/WebhookTests.kt @@ -14,7 +14,6 @@ import org.opensearch.commons.utils.recreateObject import java.net.MalformedURLException internal class WebhookTests { - @Test fun `Webhook serialize and deserialize transport object should be equal`() { val sampleWebhook = Webhook("https://domain.com/sample_url#1234567890", mapOf(Pair("key", "value"))) @@ -24,11 +23,12 @@ internal class WebhookTests { @Test fun `Webhook serialize and deserialize using json object should be equal`() { - val sampleWebhook = Webhook( - "http://domain.com/sample_url#1234567890", - mapOf(Pair("key", "value")), - HttpMethodType.PUT - ) + val sampleWebhook = + Webhook( + "http://domain.com/sample_url#1234567890", + mapOf(Pair("key", "value")), + HttpMethodType.PUT, + ) val jsonString = getJsonString(sampleWebhook) val recreatedObject = createObjectFromJsonString(jsonString) { Webhook.parse(it) } assertEquals(sampleWebhook, recreatedObject) @@ -36,12 +36,14 @@ internal class WebhookTests { @Test fun `Webhook should deserialize json object using parser`() { - val sampleWebhook = Webhook( - "https://domain.com/sample_url#1234567890", - mapOf(Pair("key", "value")), - HttpMethodType.PATCH - ) - val jsonString = """ + val sampleWebhook = + Webhook( + "https://domain.com/sample_url#1234567890", + mapOf(Pair("key", "value")), + HttpMethodType.PATCH, + ) + val jsonString = + """ { "url":"${sampleWebhook.url}", "header_params":{ @@ -49,7 +51,7 @@ internal class WebhookTests { }, "method":"PATCH" } - """.trimIndent() + """.trimIndent() val recreatedObject = createObjectFromJsonString(jsonString) { Webhook.parse(it) } assertEquals(sampleWebhook, recreatedObject) } diff --git a/src/test/kotlin/org/opensearch/commons/replication/ReplicationPluginInterfaceTests.kt b/src/test/kotlin/org/opensearch/commons/replication/ReplicationPluginInterfaceTests.kt index 14e74738..ceaed42a 100644 --- a/src/test/kotlin/org/opensearch/commons/replication/ReplicationPluginInterfaceTests.kt +++ b/src/test/kotlin/org/opensearch/commons/replication/ReplicationPluginInterfaceTests.kt @@ -1,65 +1,64 @@ -/* - * Copyright OpenSearch Contributors - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.opensearch.commons.replication - -import com.nhaarman.mockitokotlin2.whenever -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import org.mockito.Mockito.any -import org.mockito.Mockito.mock -import org.mockito.Mockito.verify -import org.mockito.junit.jupiter.MockitoExtension -import org.opensearch.action.support.clustermanager.AcknowledgedResponse -import org.opensearch.commons.replication.action.StopIndexReplicationRequest -import org.opensearch.core.action.ActionListener -import org.opensearch.core.action.ActionResponse -import org.opensearch.transport.client.node.NodeClient - -@ExtendWith(MockitoExtension::class) -internal class ReplicationPluginInterfaceTests { - - @Test - fun `test stopReplication successful response`() { - // Mock dependencies - val client: NodeClient = mock() - val request: StopIndexReplicationRequest = mock() - val listener: ActionListener = mock() - val acknowledgedResponse = AcknowledgedResponse(true) // Successful response - - // Mock the behavior of NodeClient.execute() - whenever(client.execute(any(), any(), any>())) - .thenAnswer { invocation -> - val actionListener = invocation.getArgument>(2) - actionListener.onResponse(acknowledgedResponse) // Simulate success - } - - // Call method under test - ReplicationPluginInterface.stopReplication(client, request, listener) - // Verify that listener.onResponse is called with the correct response - verify(listener).onResponse(acknowledgedResponse) - } - - @Test - fun `test stopReplication failure response`() { - // Mock dependencies - val client: NodeClient = mock() - val request: StopIndexReplicationRequest = mock() - val listener: ActionListener = mock() - val exception = Exception("Test failure") - - // Mock the behavior of NodeClient.execute() - whenever(client.execute(any(), any(), any>())) - .thenAnswer { invocation -> - val actionListener = invocation.getArgument>(2) - actionListener.onFailure(exception) // Simulate failure - } - - // Call method under test - ReplicationPluginInterface.stopReplication(client, request, listener) - // Verify that listener.onResponse is called with the correct response - verify(listener).onFailure(exception) - } -} +/* + * Copyright OpenSearch Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.opensearch.commons.replication + +import com.nhaarman.mockitokotlin2.whenever +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.mockito.Mockito.any +import org.mockito.Mockito.mock +import org.mockito.Mockito.verify +import org.mockito.junit.jupiter.MockitoExtension +import org.opensearch.action.support.clustermanager.AcknowledgedResponse +import org.opensearch.commons.replication.action.StopIndexReplicationRequest +import org.opensearch.core.action.ActionListener +import org.opensearch.core.action.ActionResponse +import org.opensearch.transport.client.node.NodeClient + +@ExtendWith(MockitoExtension::class) +internal class ReplicationPluginInterfaceTests { + @Test + fun `test stopReplication successful response`() { + // Mock dependencies + val client: NodeClient = mock() + val request: StopIndexReplicationRequest = mock() + val listener: ActionListener = mock() + val acknowledgedResponse = AcknowledgedResponse(true) // Successful response + + // Mock the behavior of NodeClient.execute() + whenever(client.execute(any(), any(), any>())) + .thenAnswer { invocation -> + val actionListener = invocation.getArgument>(2) + actionListener.onResponse(acknowledgedResponse) // Simulate success + } + + // Call method under test + ReplicationPluginInterface.stopReplication(client, request, listener) + // Verify that listener.onResponse is called with the correct response + verify(listener).onResponse(acknowledgedResponse) + } + + @Test + fun `test stopReplication failure response`() { + // Mock dependencies + val client: NodeClient = mock() + val request: StopIndexReplicationRequest = mock() + val listener: ActionListener = mock() + val exception = Exception("Test failure") + + // Mock the behavior of NodeClient.execute() + whenever(client.execute(any(), any(), any>())) + .thenAnswer { invocation -> + val actionListener = invocation.getArgument>(2) + actionListener.onFailure(exception) // Simulate failure + } + + // Call method under test + ReplicationPluginInterface.stopReplication(client, request, listener) + // Verify that listener.onResponse is called with the correct response + verify(listener).onFailure(exception) + } +} diff --git a/src/test/kotlin/org/opensearch/commons/utils/TestHelpers.kt b/src/test/kotlin/org/opensearch/commons/utils/TestHelpers.kt index 1170851b..0f47e471 100644 --- a/src/test/kotlin/org/opensearch/commons/utils/TestHelpers.kt +++ b/src/test/kotlin/org/opensearch/commons/utils/TestHelpers.kt @@ -24,10 +24,12 @@ fun getJsonString(xContent: ToXContent): String { inline fun createObjectFromJsonString( jsonString: String, - block: (XContentParser) -> CreateType + block: (XContentParser) -> CreateType, ): CreateType { - val parser = XContentType.JSON.xContent() - .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.IGNORE_DEPRECATIONS, jsonString) + val parser = + XContentType.JSON + .xContent() + .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.IGNORE_DEPRECATIONS, jsonString) parser.nextToken() return block(parser) } From f4c816ed62cbb2e8566ae9d431597ef6e6366493 Mon Sep 17 00:00:00 2001 From: Craig Perkins Date: Wed, 3 Dec 2025 22:49:21 -0500 Subject: [PATCH 2/6] Fix compiler warnings Signed-off-by: Craig Perkins --- .../opensearch/commons/alerting/model/Monitor.kt | 2 +- .../commons/alerting/model/MonitorMetadata.kt | 16 ++++++++++++---- .../commons/alerting/model/WorkflowMetadata.kt | 1 - .../commons/alerting/model/WorkflowRunContext.kt | 6 +++++- .../commons/utils/ValidationHelpers.kt | 14 ++++++++++++-- .../opensearch/commons/alerting/TestHelpers.kt | 10 ---------- .../action/DocLevelMonitorFanOutResponseTests.kt | 2 +- 7 files changed, 31 insertions(+), 20 deletions(-) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt index 953998a3..2cba052f 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt @@ -260,7 +260,7 @@ data class Monitor( it.writeTo(out) } out.writeMap(uiMetadata) - out.writeBoolean(dataSources != null) // for backward compatibility with pre-existing monitors which don't have datasources field + out.writeBoolean(true) // for backward compatibility with pre-existing monitors which don't have datasources field dataSources.writeTo(out) if (out.version.onOrAfter(Version.V_2_15_0)) { out.writeOptionalBoolean(deleteQueryIndexInEveryRun) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorMetadata.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorMetadata.kt index 5b9dc0ce..a64bf181 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorMetadata.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/MonitorMetadata.kt @@ -37,7 +37,10 @@ data class MonitorMetadata( monitorId = sin.readString(), lastActionExecutionTimes = sin.readList(ActionExecutionTime.Companion::readFrom), lastRunContext = Monitor.suppressWarning(sin.readMap()), - sourceToQueryIndexMapping = sin.readMap() as MutableMap, + sourceToQueryIndexMapping = + sin + .readMap(StreamInput::readString, StreamInput::readString) + .toMutableMap(), ) override fun writeTo(out: StreamOutput) { @@ -47,7 +50,11 @@ data class MonitorMetadata( out.writeString(monitorId) out.writeCollection(lastActionExecutionTimes) out.writeMap(lastRunContext) - out.writeMap(sourceToQueryIndexMapping as MutableMap) + out.writeMap( + sourceToQueryIndexMapping, + StreamOutput::writeString, + StreamOutput::writeString, + ) } override fun toXContent( @@ -61,7 +68,8 @@ data class MonitorMetadata( .field(LAST_ACTION_EXECUTION_FIELD, lastActionExecutionTimes.toTypedArray()) if (lastRunContext.isNotEmpty()) builder.field(LAST_RUN_CONTEXT_FIELD, lastRunContext) if (sourceToQueryIndexMapping.isNotEmpty()) { - builder.field(SOURCE_TO_QUERY_INDEX_MAP_FIELD, sourceToQueryIndexMapping as MutableMap) + val sourceToQueryIndexMapForXContent: Map = sourceToQueryIndexMapping + builder.field(SOURCE_TO_QUERY_INDEX_MAP_FIELD, sourceToQueryIndexMapForXContent) } if (params.paramAsBoolean("with_type", false)) builder.endObject() return builder.endObject() @@ -110,7 +118,7 @@ data class MonitorMetadata( } SOURCE_TO_QUERY_INDEX_MAP_FIELD -> { - sourceToQueryIndexMapping = xcp.map() as MutableMap + sourceToQueryIndexMapping = xcp.mapStrings().toMutableMap() } } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowMetadata.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowMetadata.kt index 5d0193ac..2a946ad9 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowMetadata.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowMetadata.kt @@ -65,7 +65,6 @@ data class WorkflowMetadata( const val LATEST_EXECUTION_ID = "latest_execution_id" @JvmStatic - @JvmOverloads @Throws(IOException::class) fun parse(xcp: XContentParser): WorkflowMetadata { lateinit var workflowId: String diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt index bbf5b1b1..90ec58fa 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt @@ -31,7 +31,11 @@ data class WorkflowRunContext( workflowId = sin.readString(), workflowMetadataId = sin.readString(), chainedMonitorId = sin.readOptionalString(), - matchingDocIdsPerIndex = sin.readMap() as Map>, + matchingDocIdsPerIndex = + sin.readMap( + StreamInput::readString, + StreamInput::readStringList, + ), auditDelegateMonitorAlerts = sin.readBoolean(), findingIds = if (sin.version.onOrAfter(Version.V_2_15_0)) sin.readOptionalStringList() else emptyList(), ) diff --git a/src/main/kotlin/org/opensearch/commons/utils/ValidationHelpers.kt b/src/main/kotlin/org/opensearch/commons/utils/ValidationHelpers.kt index 1da87aa2..b317036e 100644 --- a/src/main/kotlin/org/opensearch/commons/utils/ValidationHelpers.kt +++ b/src/main/kotlin/org/opensearch/commons/utils/ValidationHelpers.kt @@ -5,6 +5,7 @@ package org.opensearch.commons.utils +import java.net.URI import java.net.URL import java.util.regex.Pattern @@ -45,8 +46,17 @@ fun validateId(idString: String) { } fun isValidUrl(urlString: String): Boolean { - val url = URL(urlString) // throws MalformedURLException if URL is invalid - return ("https" == url.protocol || "http" == url.protocol) // Support only http/https, other protocols not supported + return try { + val uri = URI(urlString) + + // Must have http/https + val scheme = uri.scheme ?: return false + // Support only http/https, other protocols not supported + (scheme == "http" || scheme == "https") + } catch (e: Exception) { + // throws MalformedURLException if URL is invalid + false + } } /** diff --git a/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt b/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt index cb067c6e..2f2e3437 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt @@ -226,16 +226,6 @@ fun randomWorkflow( } } var input = listOf(CompositeInput(Sequence(delegates))) - if (input == null) { - input = - listOf( - CompositeInput( - Sequence( - listOf(Delegate(1, "delegate1")), - ), - ), - ) - } return Workflow( name = name, workflowType = Workflow.WorkflowType.COMPOSITE, diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutResponseTests.kt index f1f2a891..0e2dbff2 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/DocLevelMonitorFanOutResponseTests.kt @@ -43,7 +43,7 @@ class DocLevelMonitorFanOutResponseTests { "nodeid", "eid", "monitorId", - mapOf("index" to mapOf("1" to "1")) as MutableMap, + mutableMapOf("index" to mapOf("1" to "1")), InputRunResults(), mapOf("1" to randomDocumentLevelTriggerRunResult(), "2" to randomDocumentLevelTriggerRunResult()), ) From d1e60d5c225273ea7801f64c546ede2a27352f06 Mon Sep 17 00:00:00 2001 From: Craig Perkins Date: Thu, 4 Dec 2025 14:18:29 -0500 Subject: [PATCH 3/6] Fix a few tests Signed-off-by: Craig Perkins --- build.gradle | 11 ++- .../alerting/model/WorkflowRunContext.kt | 2 +- .../message/LegacySNSMessageTest.java | 99 +++++++++---------- .../action/SearchCommentRequestTests.kt | 8 +- .../action/SearchMonitorRequestTests.kt | 8 +- .../BucketSelectorExtAggregatorTests.kt | 2 +- .../action/SendNotificationResponseTests.kt | 2 +- .../commons/notifications/model/ChimeTests.kt | 4 +- .../model/MicrosoftTeamsTests.kt | 4 +- .../commons/notifications/model/SlackTests.kt | 4 +- .../notifications/model/WebhookTests.kt | 4 +- 11 files changed, 81 insertions(+), 67 deletions(-) diff --git a/build.gradle b/build.gradle index 74e49a92..e46ac097 100644 --- a/build.gradle +++ b/build.gradle @@ -91,9 +91,15 @@ dependencies { compileOnly "commons-validator:commons-validator:1.7" testImplementation "org.opensearch.test:framework:${opensearch_version}" testImplementation "org.jetbrains.kotlin:kotlin-test:${kotlin_version}" - testImplementation "org.mockito:mockito-core:3.10.0" + testImplementation "org.mockito:mockito-core:5.20.0" + testImplementation('junit:junit:4.13.2') { + exclude group: 'org.hamcrest', module: 'hamcrest-core' + } + testRuntimeOnly('org.junit.vintage:junit-vintage-engine:5.11.4') { + exclude group: 'org.hamcrest', module: 'hamcrest-core' + } testImplementation 'org.junit.jupiter:junit-jupiter-api:5.11.4' - testImplementation 'org.mockito:mockito-junit-jupiter:3.10.0' + testImplementation 'org.mockito:mockito-junit-jupiter:5.20.0' testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0" testImplementation "com.cronutils:cron-utils:9.2.1" testImplementation "commons-validator:commons-validator:1.7" @@ -104,6 +110,7 @@ dependencies { test { useJUnitPlatform() + systemProperty "jdk.attach.allowAttachSelf", true testLogging { exceptionFormat = "full" events "skipped", "passed", "failed" // "started" diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt index 90ec58fa..1e9ed1f7 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/WorkflowRunContext.kt @@ -44,7 +44,7 @@ data class WorkflowRunContext( out.writeString(workflowId) out.writeString(workflowMetadataId) out.writeOptionalString(chainedMonitorId) - out.writeMap(matchingDocIdsPerIndex) + out.writeMapOfLists(matchingDocIdsPerIndex, StreamOutput::writeString, StreamOutput::writeString) out.writeBoolean(auditDelegateMonitorAlerts) if (out.version.onOrAfter(Version.V_2_15_0)) { out.writeOptionalStringCollection(findingIds) diff --git a/src/test/java/org/opensearch/commons/destination/message/LegacySNSMessageTest.java b/src/test/java/org/opensearch/commons/destination/message/LegacySNSMessageTest.java index a9fd1dd3..1905cb29 100644 --- a/src/test/java/org/opensearch/commons/destination/message/LegacySNSMessageTest.java +++ b/src/test/java/org/opensearch/commons/destination/message/LegacySNSMessageTest.java @@ -5,69 +5,69 @@ package org.opensearch.commons.destination.message; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class LegacySNSMessageTest { @Test public void testCreateRoleArnMissingMessage() { - try { - LegacySNSMessage message = new LegacySNSMessage.Builder("sms").withMessage("dummyMessage").build(); - } catch (Exception ex) { - assertEquals("Role arn is missing/invalid: null", ex.getMessage()); - throw ex; - } + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> new LegacySNSMessage.Builder("sms") + .withMessage("dummyMessage") + .build() + ); + assertEquals("Role arn is missing/invalid: null", ex.getMessage()); } @Test public void testCreateTopicArnMissingMessage() { - try { - LegacySNSMessage message = new LegacySNSMessage.Builder("sms") - .withMessage("dummyMessage") - .withRole("arn:aws:iam::853806060000:role/domain/abc") - .build(); - } catch (Exception ex) { - assertEquals("Topic arn is missing/invalid: null", ex.getMessage()); - throw ex; - } + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> new LegacySNSMessage.Builder("sms") + .withMessage("dummyMessage") + .withRole("arn:aws:iam::853806060000:role/domain/abc") + .build() + ); + assertEquals("Topic arn is missing/invalid: null", ex.getMessage()); } @Test public void testCreateContentMissingMessage() { - try { - LegacySNSMessage message = new LegacySNSMessage.Builder("sms") - .withRole("arn:aws:iam::853806060000:role/domain/abc") - .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") - .build(); - } catch (Exception ex) { - assertEquals("Message content is missing", ex.getMessage()); - throw ex; - } + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> new LegacySNSMessage.Builder("sms") + .withRole("arn:aws:iam::853806060000:role/domain/abc") + .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") + .build() + ); + assertEquals("Message content is missing", ex.getMessage()); } @Test public void testInValidRoleMessage() { - try { - LegacySNSMessage message = new LegacySNSMessage.Builder("sms") - .withMessage("dummyMessage") - .withRole("dummyRole") - .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") - .build(); - } catch (Exception ex) { - assertEquals("Role arn is missing/invalid: dummyRole", ex.getMessage()); - throw ex; - } + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> new LegacySNSMessage.Builder("sms") + .withMessage("dummyMessage") + .withRole("dummyRole") + .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") + .build() + ); + assertEquals("Role arn is missing/invalid: dummyRole", ex.getMessage()); } @Test public void testValidMessage() { LegacySNSMessage message = new LegacySNSMessage.Builder("sms") - .withMessage("dummyMessage") - .withRole("arn:aws:iam::853806060000:role/domain/abc") - .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") - .build(); + .withMessage("dummyMessage") + .withRole("arn:aws:iam::853806060000:role/domain/abc") + .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") + .build(); + assertEquals(LegacyDestinationType.LEGACY_SNS, message.getChannelType()); assertEquals("sms", message.getChannelName()); assertEquals("dummyMessage", message.getMessage()); @@ -77,15 +77,14 @@ public void testValidMessage() { @Test public void testInValidChannelName() { - try { - LegacySNSMessage message = new LegacySNSMessage.Builder("") - .withMessage("dummyMessage") - .withRole("arn:aws:iam::853806060000:role/domain/abc") - .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") - .build(); - } catch (Exception ex) { - assertEquals("Channel name must be defined", ex.getMessage()); - throw ex; - } + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> new LegacySNSMessage.Builder("") + .withMessage("dummyMessage") + .withRole("arn:aws:iam::853806060000:role/domain/abc") + .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") + .build() + ); + assertEquals("Channel name must be defined", ex.getMessage()); } } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequestTests.kt index babcc67c..25df776b 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/SearchCommentRequestTests.kt @@ -1,5 +1,6 @@ package org.opensearch.commons.alerting.action +import org.junit.Test import org.opensearch.action.search.SearchRequest import org.opensearch.common.io.stream.BytesStreamOutput import org.opensearch.common.unit.TimeValue @@ -8,13 +9,16 @@ import org.opensearch.search.builder.SearchSourceBuilder import org.opensearch.test.OpenSearchTestCase import org.opensearch.test.rest.OpenSearchRestTestCase import java.util.concurrent.TimeUnit -import kotlin.test.Test class SearchCommentRequestTests : OpenSearchTestCase() { @Test fun `test search comments request`() { val searchSourceBuilder = SearchSourceBuilder().from(0).size(100).timeout(TimeValue(60, TimeUnit.SECONDS)) - val searchRequest = SearchRequest().indices(OpenSearchRestTestCase.randomAlphaOfLength(10)).source(searchSourceBuilder) + val searchRequest = + SearchRequest() + .indices( + OpenSearchRestTestCase.randomAlphaOfLength(10), + ).source(searchSourceBuilder) val searchCommentRequest = SearchCommentRequest(searchRequest) assertNotNull(searchCommentRequest) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt index 0ff1d23c..64282a84 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt @@ -11,7 +11,6 @@ import org.opensearch.common.unit.TimeValue import org.opensearch.core.common.io.stream.StreamInput import org.opensearch.search.builder.SearchSourceBuilder import org.opensearch.test.OpenSearchTestCase -import org.opensearch.test.rest.OpenSearchRestTestCase import java.util.concurrent.TimeUnit import kotlin.test.Test @@ -19,7 +18,12 @@ class SearchMonitorRequestTests : OpenSearchTestCase() { @Test fun `test search monitors request`() { val searchSourceBuilder = SearchSourceBuilder().from(0).size(100).timeout(TimeValue(60, TimeUnit.SECONDS)) - val searchRequest = SearchRequest().indices(OpenSearchRestTestCase.randomAlphaOfLength(10)).source(searchSourceBuilder) + val searchRequest = + SearchRequest() + .indices( + OpenSearchTestCase + .randomAlphaOfLength(10), + ).source(searchSourceBuilder) val searchMonitorRequest = SearchMonitorRequest(searchRequest) assertNotNull(searchMonitorRequest) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/bucketselectorext/BucketSelectorExtAggregatorTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/bucketselectorext/BucketSelectorExtAggregatorTests.kt index 5a65f36b..dc6aa2a2 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/bucketselectorext/BucketSelectorExtAggregatorTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/bucketselectorext/BucketSelectorExtAggregatorTests.kt @@ -14,6 +14,7 @@ import org.apache.lucene.search.Query import org.apache.lucene.tests.index.RandomIndexWriter import org.apache.lucene.util.BytesRef import org.hamcrest.CoreMatchers +import org.junit.Test import org.opensearch.common.CheckedConsumer import org.opensearch.common.settings.Settings import org.opensearch.commons.alerting.aggregation.bucketselectorext.BucketSelectorExtAggregationBuilder @@ -45,7 +46,6 @@ import java.io.IOException import java.util.Collections import java.util.function.Consumer import java.util.function.Function -import kotlin.test.Test class BucketSelectorExtAggregatorTests : AggregatorTestCase() { private var scriptName = "bucket_selector_script" diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt index ecaebdac..0b147514 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt @@ -5,8 +5,8 @@ package org.opensearch.commons.notifications.action import com.fasterxml.jackson.core.JsonParseException -import org.junit.Test import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.opensearch.commons.notifications.model.ConfigType import org.opensearch.commons.notifications.model.DeliveryStatus diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/ChimeTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/ChimeTests.kt index 0f4fd221..c9032580 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/ChimeTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/ChimeTests.kt @@ -56,11 +56,11 @@ internal class ChimeTests { @Test fun `Chime should throw exception when url is not proper`() { - assertThrows { + assertThrows { Chime("domain.com/sample_url#1234567890") } val jsonString = "{\"url\":\"domain.com/sample_url\"}" - assertThrows { + assertThrows { createObjectFromJsonString(jsonString) { Chime.parse(it) } } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeamsTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeamsTests.kt index 4dd760cb..f7d3f182 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeamsTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/MicrosoftTeamsTests.kt @@ -56,11 +56,11 @@ internal class MicrosoftTeamsTests { @Test fun `Microsoft Teams should throw exception when url is not proper`() { - assertThrows { + assertThrows { MicrosoftTeams("domain.com/sample_url#1234567890") } val jsonString = "{\"url\":\"domain.com/sample_url\"}" - assertThrows { + assertThrows { createObjectFromJsonString(jsonString) { MicrosoftTeams.parse(it) } } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/SlackTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/SlackTests.kt index 6d8b8014..b7d871f5 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/SlackTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/SlackTests.kt @@ -56,11 +56,11 @@ internal class SlackTests { @Test fun `Slack should throw exception when url is not proper`() { - assertThrows { + assertThrows { Slack("domain.com/sample_url#1234567890") } val jsonString = "{\"url\":\"domain.com/sample_url\"}" - assertThrows { + assertThrows { createObjectFromJsonString(jsonString) { Slack.parse(it) } } } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/WebhookTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/WebhookTests.kt index 37960550..3777ec8f 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/WebhookTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/WebhookTests.kt @@ -75,11 +75,11 @@ internal class WebhookTests { @Test fun `Webhook should throw exception when url is not proper`() { - assertThrows { + assertThrows { Webhook("domain.com/sample_url#1234567890") } val jsonString = "{\"url\":\"domain.com/sample_url\"}" - assertThrows { + assertThrows { createObjectFromJsonString(jsonString) { Webhook.parse(it) } } } From 338f3856025eb2d0fb92dae2a6ebb71ae033350e Mon Sep 17 00:00:00 2001 From: Craig Perkins Date: Thu, 4 Dec 2025 14:35:19 -0500 Subject: [PATCH 4/6] Fix all tests Signed-off-by: Craig Perkins --- .../action/SearchMonitorRequestTests.kt | 2 +- .../action/SendNotificationResponseTests.kt | 68 ++++++++++--------- 2 files changed, 38 insertions(+), 32 deletions(-) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt index 64282a84..9073c6d0 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/SearchMonitorRequestTests.kt @@ -5,6 +5,7 @@ package org.opensearch.commons.alerting.action +import org.junit.Test import org.opensearch.action.search.SearchRequest import org.opensearch.common.io.stream.BytesStreamOutput import org.opensearch.common.unit.TimeValue @@ -12,7 +13,6 @@ import org.opensearch.core.common.io.stream.StreamInput import org.opensearch.search.builder.SearchSourceBuilder import org.opensearch.test.OpenSearchTestCase import java.util.concurrent.TimeUnit -import kotlin.test.Test class SearchMonitorRequestTests : OpenSearchTestCase() { @Test diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt index 0b147514..d62107f1 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt @@ -21,40 +21,37 @@ import org.opensearch.commons.utils.recreateObject internal class SendNotificationResponseTests { @Test fun `Create response serialize and deserialize transport object should be equal`() { - val sampleEvent = getSampleEvent() + val original = SendNotificationResponse(getSampleEvent()) - val recreatedObject = recreateObject(sampleEvent) { SendNotificationResponse(it) } - assertEquals(sampleEvent, recreatedObject) + val roundTripped = recreateObject(original) { SendNotificationResponse(it) } + + assertEquals(getJsonString(original), getJsonString(roundTripped)) } @Test fun `Create response serialize and deserialize using json object should be equal`() { - val sampleEvent = getSampleEvent() + val original = SendNotificationResponse(getSampleEvent()) - val jsonString = getJsonString(sampleEvent) - val recreatedObject = createObjectFromJsonString(jsonString) { SendNotificationResponse.parse(it) } - assertEquals(sampleEvent, recreatedObject) - } + val json = getJsonString(original) + val parsed = createObjectFromJsonString(json) { SendNotificationResponse.parse(it) } - @Test - fun `Create response should deserialize json object using parser`() { - val sampleEvent = getSampleEvent() - val jsonString = "{\"event_id\":\"$sampleEvent\"}" - val recreatedObject = createObjectFromJsonString(jsonString) { SendNotificationResponse.parse(it) } - assertEquals(sampleEvent, recreatedObject) + assertEquals(getJsonString(original), getJsonString(parsed)) } @Test fun `Create response should throw exception when invalid json object is passed`() { val jsonString = "sample message" + assertThrows { createObjectFromJsonString(jsonString) { SendNotificationResponse.parse(it) } } } @Test - fun `Create response should throw exception when notificationId is replace with notificationId2 in json object`() { - val jsonString = "{\"event_id2\":\"sample_notification_id\"}" + fun `Create response should throw exception when required fields are missing`() { + // No event_source / status_list – just a bogus field + val jsonString = """{"event_id2":"sample_notification_id"}""" + assertThrows { createObjectFromJsonString(jsonString) { SendNotificationResponse.parse(it) } } @@ -62,18 +59,27 @@ internal class SendNotificationResponseTests { @Test fun `Create response should safely ignore extra field in json object`() { - val sampleEvent = getSampleEvent() - val jsonString = - """ - { - "event_id":"$sampleEvent", - "extra_field_1":["extra", "value"], - "extra_field_2":{"extra":"value"}, - "extra_field_3":"extra value 3" - } - """.trimIndent() - val recreatedObject = createObjectFromJsonString(jsonString) { SendNotificationResponse.parse(it) } - assertEquals(sampleEvent, recreatedObject) + val original = SendNotificationResponse(getSampleEvent()) + val baseJson = getJsonString(original) + + // Take the valid JSON and append extra fields at the root. + // baseJson is something like: + // {"event_source":{...},"status_list":[...]} + val jsonWithExtras = + baseJson.removeSuffix("}") + + """ + , + "event_id":"legacy-id", + "extra_field_1":["extra", "value"], + "extra_field_2":{"extra":"value"}, + "extra_field_3":"extra value 3" + } + """.trimIndent() + + val parsed = createObjectFromJsonString(jsonWithExtras) { SendNotificationResponse.parse(it) } + + // Extra fields should be ignored – core payload stays the same + assertEquals(getJsonString(original), getJsonString(parsed)) } private fun getSampleEvent(): NotificationEvent { @@ -85,9 +91,9 @@ internal class SendNotificationResponseTests { ) val sampleStatus = EventStatus( - "config_id", - "name", - ConfigType.SLACK, + configId = "config_id", + configName = "name", + configType = ConfigType.SLACK, deliveryStatus = DeliveryStatus("404", "invalid recipient"), ) From 7a67f0e2ff5ef36abccfb1c6ae82031cb32b034a Mon Sep 17 00:00:00 2001 From: Craig Perkins Date: Mon, 9 Feb 2026 09:20:39 -0500 Subject: [PATCH 5/6] Run ktlintFormat Signed-off-by: Craig Perkins --- .../commons/notifications/model/ConfigType.kt | 10 +++----- .../model/config/ConfigDataProperties.kt | 25 ++++++++++--------- 2 files changed, 16 insertions(+), 19 deletions(-) diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/ConfigType.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/ConfigType.kt index c15f7fbc..b08f34aa 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/ConfigType.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/ConfigType.kt @@ -40,15 +40,11 @@ enum class ConfigType( override fun toString(): String = tag }, MICROSOFT_TEAMS("microsoft_teams") { - override fun toString(): String { - return tag - } + override fun toString(): String = tag }, MATTERMOST("mattermost") { - override fun toString(): String { - return tag - } - }; + override fun toString(): String = tag + }, ; companion object { private val tagMap = values().associateBy { it.tag } diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/config/ConfigDataProperties.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/config/ConfigDataProperties.kt index 9254eb56..e4a3e593 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/config/ConfigDataProperties.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/config/ConfigDataProperties.kt @@ -29,18 +29,19 @@ internal object ConfigDataProperties { val configDataParser: XParser, ) - private val CONFIG_PROPERTIES_MAP = mapOf( - Pair(ConfigType.SLACK, ConfigProperty(Slack.reader, Slack.xParser)), - Pair(ConfigType.CHIME, ConfigProperty(Chime.reader, Chime.xParser)), - Pair(ConfigType.WEBHOOK, ConfigProperty(Webhook.reader, Webhook.xParser)), - Pair(ConfigType.EMAIL, ConfigProperty(Email.reader, Email.xParser)), - Pair(ConfigType.SNS, ConfigProperty(Sns.reader, Sns.xParser)), - Pair(ConfigType.SES_ACCOUNT, ConfigProperty(SesAccount.reader, SesAccount.xParser)), - Pair(ConfigType.EMAIL_GROUP, ConfigProperty(EmailGroup.reader, EmailGroup.xParser)), - Pair(ConfigType.SMTP_ACCOUNT, ConfigProperty(SmtpAccount.reader, SmtpAccount.xParser)), - Pair(ConfigType.MICROSOFT_TEAMS, ConfigProperty(MicrosoftTeams.reader, MicrosoftTeams.xParser)), - Pair(ConfigType.MATTERMOST, ConfigProperty(Slack.reader, Slack.xParser)) - ) + private val CONFIG_PROPERTIES_MAP = + mapOf( + Pair(ConfigType.SLACK, ConfigProperty(Slack.reader, Slack.xParser)), + Pair(ConfigType.CHIME, ConfigProperty(Chime.reader, Chime.xParser)), + Pair(ConfigType.WEBHOOK, ConfigProperty(Webhook.reader, Webhook.xParser)), + Pair(ConfigType.EMAIL, ConfigProperty(Email.reader, Email.xParser)), + Pair(ConfigType.SNS, ConfigProperty(Sns.reader, Sns.xParser)), + Pair(ConfigType.SES_ACCOUNT, ConfigProperty(SesAccount.reader, SesAccount.xParser)), + Pair(ConfigType.EMAIL_GROUP, ConfigProperty(EmailGroup.reader, EmailGroup.xParser)), + Pair(ConfigType.SMTP_ACCOUNT, ConfigProperty(SmtpAccount.reader, SmtpAccount.xParser)), + Pair(ConfigType.MICROSOFT_TEAMS, ConfigProperty(MicrosoftTeams.reader, MicrosoftTeams.xParser)), + Pair(ConfigType.MATTERMOST, ConfigProperty(Slack.reader, Slack.xParser)), + ) /** * Get Reader for provided config type From 61a94b387a56a90239555c2506bd5c7a242bcff7 Mon Sep 17 00:00:00 2001 From: Craig Perkins Date: Mon, 9 Feb 2026 10:12:45 -0500 Subject: [PATCH 6/6] Fix spotless issue Signed-off-by: Craig Perkins --- .../message/LegacySNSMessageTest.java | 62 +++++++++---------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/src/test/java/org/opensearch/commons/destination/message/LegacySNSMessageTest.java b/src/test/java/org/opensearch/commons/destination/message/LegacySNSMessageTest.java index 1905cb29..8c95652a 100644 --- a/src/test/java/org/opensearch/commons/destination/message/LegacySNSMessageTest.java +++ b/src/test/java/org/opensearch/commons/destination/message/LegacySNSMessageTest.java @@ -5,20 +5,18 @@ package org.opensearch.commons.destination.message; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + public class LegacySNSMessageTest { @Test public void testCreateRoleArnMissingMessage() { IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> new LegacySNSMessage.Builder("sms") - .withMessage("dummyMessage") - .build() + IllegalArgumentException.class, + () -> new LegacySNSMessage.Builder("sms").withMessage("dummyMessage").build() ); assertEquals("Role arn is missing/invalid: null", ex.getMessage()); } @@ -26,11 +24,11 @@ public void testCreateRoleArnMissingMessage() { @Test public void testCreateTopicArnMissingMessage() { IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> new LegacySNSMessage.Builder("sms") - .withMessage("dummyMessage") - .withRole("arn:aws:iam::853806060000:role/domain/abc") - .build() + IllegalArgumentException.class, + () -> new LegacySNSMessage.Builder("sms") + .withMessage("dummyMessage") + .withRole("arn:aws:iam::853806060000:role/domain/abc") + .build() ); assertEquals("Topic arn is missing/invalid: null", ex.getMessage()); } @@ -38,11 +36,11 @@ public void testCreateTopicArnMissingMessage() { @Test public void testCreateContentMissingMessage() { IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> new LegacySNSMessage.Builder("sms") - .withRole("arn:aws:iam::853806060000:role/domain/abc") - .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") - .build() + IllegalArgumentException.class, + () -> new LegacySNSMessage.Builder("sms") + .withRole("arn:aws:iam::853806060000:role/domain/abc") + .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") + .build() ); assertEquals("Message content is missing", ex.getMessage()); } @@ -50,12 +48,12 @@ public void testCreateContentMissingMessage() { @Test public void testInValidRoleMessage() { IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> new LegacySNSMessage.Builder("sms") - .withMessage("dummyMessage") - .withRole("dummyRole") - .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") - .build() + IllegalArgumentException.class, + () -> new LegacySNSMessage.Builder("sms") + .withMessage("dummyMessage") + .withRole("dummyRole") + .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") + .build() ); assertEquals("Role arn is missing/invalid: dummyRole", ex.getMessage()); } @@ -63,10 +61,10 @@ public void testInValidRoleMessage() { @Test public void testValidMessage() { LegacySNSMessage message = new LegacySNSMessage.Builder("sms") - .withMessage("dummyMessage") - .withRole("arn:aws:iam::853806060000:role/domain/abc") - .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") - .build(); + .withMessage("dummyMessage") + .withRole("arn:aws:iam::853806060000:role/domain/abc") + .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") + .build(); assertEquals(LegacyDestinationType.LEGACY_SNS, message.getChannelType()); assertEquals("sms", message.getChannelName()); @@ -78,12 +76,12 @@ public void testValidMessage() { @Test public void testInValidChannelName() { IllegalArgumentException ex = assertThrows( - IllegalArgumentException.class, - () -> new LegacySNSMessage.Builder("") - .withMessage("dummyMessage") - .withRole("arn:aws:iam::853806060000:role/domain/abc") - .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") - .build() + IllegalArgumentException.class, + () -> new LegacySNSMessage.Builder("") + .withMessage("dummyMessage") + .withRole("arn:aws:iam::853806060000:role/domain/abc") + .withTopicArn("arn:aws:sns:us-west-2:475313751589:test-notification") + .build() ); assertEquals("Channel name must be defined", ex.getMessage()); }