diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/CommandManagerPlugin.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/CommandManagerPlugin.java index 34781f4..fe11b1d 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/CommandManagerPlugin.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/CommandManagerPlugin.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,10 +8,6 @@ */ package com.wazuh.commandmanager; -import com.wazuh.commandmanager.index.CommandIndex; -import com.wazuh.commandmanager.rest.RestPostCommandAction; -import com.wazuh.commandmanager.utils.httpclient.HttpRestClient; -import com.wazuh.commandmanager.utils.httpclient.HttpRestClientDemo; import org.opensearch.client.Client; import org.opensearch.cluster.metadata.IndexNameExpressionResolver; import org.opensearch.cluster.node.DiscoveryNodes; @@ -38,11 +35,15 @@ import java.util.List; import java.util.function.Supplier; +import com.wazuh.commandmanager.index.CommandIndex; +import com.wazuh.commandmanager.rest.RestPostCommandAction; +import com.wazuh.commandmanager.utils.httpclient.HttpRestClient; +import com.wazuh.commandmanager.utils.httpclient.HttpRestClientDemo; + /** - * The Command Manager plugin exposes an HTTP API with a single endpoint to - * receive raw commands from the Wazuh Server. These commands are processed, - * indexed and sent back to the Server for its delivery to, in most cases, the - * Agents. + * The Command Manager plugin exposes an HTTP API with a single endpoint to receive raw commands + * from the Wazuh Server. These commands are processed, indexed and sent back to the Server for its + * delivery to, in most cases, the Agents. */ public class CommandManagerPlugin extends Plugin implements ActionPlugin { public static final String COMMAND_MANAGER_BASE_URI = "/_plugins/_command_manager"; @@ -64,8 +65,7 @@ public Collection createComponents( NodeEnvironment nodeEnvironment, NamedWriteableRegistry namedWriteableRegistry, IndexNameExpressionResolver indexNameExpressionResolver, - Supplier repositoriesServiceSupplier - ) { + Supplier repositoriesServiceSupplier) { this.commandIndex = new CommandIndex(client, clusterService, threadPool); // HttpRestClient stuff @@ -82,8 +82,7 @@ public List getRestHandlers( IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver, - Supplier nodesInCluster - ) { + Supplier nodesInCluster) { return Collections.singletonList(new RestPostCommandAction(this.commandIndex)); } diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/index/CommandIndex.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/index/CommandIndex.java index c9cf80a..ea8f2c2 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/index/CommandIndex.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/index/CommandIndex.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,9 +8,6 @@ */ package com.wazuh.commandmanager.index; -import com.wazuh.commandmanager.CommandManagerPlugin; -import com.wazuh.commandmanager.model.Document; -import com.wazuh.commandmanager.utils.IndexTemplateUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest; @@ -31,9 +29,11 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; -/** - * Class to manage the Command Manager index and index template. - */ +import com.wazuh.commandmanager.CommandManagerPlugin; +import com.wazuh.commandmanager.model.Document; +import com.wazuh.commandmanager.utils.IndexTemplateUtils; + +/** Class to manage the Command Manager index and index template. */ public class CommandIndex implements IndexingOperationListener { private static final Logger log = LogManager.getLogger(CommandIndex.class); @@ -45,9 +45,9 @@ public class CommandIndex implements IndexingOperationListener { /** * Default constructor * - * @param client OpenSearch client. + * @param client OpenSearch client. * @param clusterService OpenSearch cluster service. - * @param threadPool An OpenSearch ThreadPool. + * @param threadPool An OpenSearch ThreadPool. */ public CommandIndex(Client client, ClusterService clusterService, ThreadPool threadPool) { this.client = client; @@ -69,30 +69,31 @@ public CompletableFuture asyncCreate(Document document) { } else { log.info( "Index template {} already exists. Skipping creation.", - CommandManagerPlugin.COMMAND_MANAGER_INDEX_TEMPLATE_NAME - ); + CommandManagerPlugin.COMMAND_MANAGER_INDEX_TEMPLATE_NAME); } log.info("Indexing command with id [{}]", document.getId()); try { - IndexRequest request = new IndexRequest() - .index(CommandManagerPlugin.COMMAND_MANAGER_INDEX_NAME) - .source(document.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS)) - .id(document.getId()) - .create(true); + IndexRequest request = + new IndexRequest() + .index(CommandManagerPlugin.COMMAND_MANAGER_INDEX_NAME) + .source( + document.toXContent( + XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS)) + .id(document.getId()) + .create(true); executor.submit( () -> { - try (ThreadContext.StoredContext ignored = this.threadPool.getThreadContext().stashContext()) { + try (ThreadContext.StoredContext ignored = + this.threadPool.getThreadContext().stashContext()) { RestStatus restStatus = client.index(request).actionGet().status(); future.complete(restStatus); } catch (Exception e) { future.completeExceptionally(e); } - } - ); + }); } catch (IOException e) { - log.error( - "Error indexing command with id [{}] due to {}", document.getId(), e); + log.error("Error indexing command with id [{}] due to {}", document.getId(), e); } return future; } @@ -104,10 +105,8 @@ public CompletableFuture asyncCreate(Document document) { * @return whether the index template exists. */ public boolean indexTemplateExists(String template_name) { - Map templates = this.clusterService - .state() - .metadata() - .templates(); + Map templates = + this.clusterService.state().metadata().templates(); log.debug("Existing index templates: {} ", templates); return templates.containsKey(template_name); @@ -124,25 +123,25 @@ public void putIndexTemplate(String templateName) { // @throws IOException Map template = IndexTemplateUtils.fromFile(templateName + ".json"); - PutIndexTemplateRequest putIndexTemplateRequest = new PutIndexTemplateRequest() - .mapping(IndexTemplateUtils.get(template, "mappings")) - .settings(IndexTemplateUtils.get(template, "settings")) - .name(templateName) - .patterns((List) template.get("index_patterns")); - - executor.submit(() -> { - AcknowledgedResponse acknowledgedResponse = this.client - .admin() - .indices() - .putTemplate(putIndexTemplateRequest) - .actionGet(); - if (acknowledgedResponse.isAcknowledged()) { - log.info( - "Index template [{}] created successfully", - templateName - ); - } - }); + PutIndexTemplateRequest putIndexTemplateRequest = + new PutIndexTemplateRequest() + .mapping(IndexTemplateUtils.get(template, "mappings")) + .settings(IndexTemplateUtils.get(template, "settings")) + .name(templateName) + .patterns((List) template.get("index_patterns")); + + executor.submit( + () -> { + AcknowledgedResponse acknowledgedResponse = + this.client + .admin() + .indices() + .putTemplate(putIndexTemplateRequest) + .actionGet(); + if (acknowledgedResponse.isAcknowledged()) { + log.info("Index template [{}] created successfully", templateName); + } + }); } catch (IOException e) { log.error("Error reading index template [{}] from filesystem", templateName); diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Command.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Command.java index 60993f8..57b7ec5 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Command.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Command.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -12,11 +13,12 @@ import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import reactor.util.annotation.NonNull; import java.io.IOException; import java.util.ArrayList; +import reactor.util.annotation.NonNull; + public class Command implements ToXContentObject { public static final String COMMAND = "command"; public static final String ORDER_ID = "order_id"; @@ -37,19 +39,18 @@ public class Command implements ToXContentObject { /** * Default constructor * - * @param source origin of the request. - * @param target {@link Target} + * @param source origin of the request. + * @param target {@link Target} * @param timeout time window in which the command has to be sent to its target. - * @param user the user that originated the request - * @param action {@link Action} + * @param user the user that originated the request + * @param action {@link Action} */ public Command( @NonNull String source, @NonNull Target target, @NonNull Integer timeout, @NonNull String user, - @NonNull Action action - ) { + @NonNull Action action) { this.requestId = UUIDs.base64UUID(); this.orderId = UUIDs.base64UUID(); this.source = source; @@ -65,10 +66,11 @@ public Command( * * @param parser XContentParser from the Rest Request * @return instance of Command - * @throws IOException error parsing request content + * @throws IOException error parsing request content * @throws IllegalArgumentException missing arguments */ - public static Command parse(XContentParser parser) throws IOException, IllegalArgumentException { + public static Command parse(XContentParser parser) + throws IOException, IllegalArgumentException { String source = null; Target target = null; Integer timeout = null; @@ -121,13 +123,7 @@ public static Command parse(XContentParser parser) throws IOException, IllegalAr if (!nullArguments.isEmpty()) { throw new IllegalArgumentException("Missing arguments: " + nullArguments); } else { - return new Command( - source, - target, - timeout, - user, - action - ); + return new Command(source, target, timeout, user, action); } } @@ -148,15 +144,27 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return "Command{" + - "orderId='" + orderId + '\'' + - ", requestId='" + requestId + '\'' + - ", source='" + source + '\'' + - ", target=" + target + - ", timeout=" + timeout + - ", user='" + user + '\'' + - ", status=" + status + - ", action=" + action + - '}'; + return "Command{" + + "orderId='" + + orderId + + '\'' + + ", requestId='" + + requestId + + '\'' + + ", source='" + + source + + '\'' + + ", target=" + + target + + ", timeout=" + + timeout + + ", user='" + + user + + '\'' + + ", status=" + + status + + ", action=" + + action + + '}'; } } diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/rest/RestPostCommandAction.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/rest/RestPostCommandAction.java index f7f88c5..ef7884c 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/rest/RestPostCommandAction.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/rest/RestPostCommandAction.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,12 +8,6 @@ */ package com.wazuh.commandmanager.rest; -import com.wazuh.commandmanager.CommandManagerPlugin; -import com.wazuh.commandmanager.index.CommandIndex; -import com.wazuh.commandmanager.model.Agent; -import com.wazuh.commandmanager.model.Command; -import com.wazuh.commandmanager.model.Document; -import com.wazuh.commandmanager.utils.httpclient.HttpRestClient; import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; import org.apache.hc.core5.net.URIBuilder; import org.apache.logging.log4j.LogManager; @@ -34,17 +29,24 @@ import java.util.List; import java.util.Locale; +import com.wazuh.commandmanager.CommandManagerPlugin; +import com.wazuh.commandmanager.index.CommandIndex; +import com.wazuh.commandmanager.model.Agent; +import com.wazuh.commandmanager.model.Command; +import com.wazuh.commandmanager.model.Document; +import com.wazuh.commandmanager.utils.httpclient.HttpRestClient; + import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken; import static org.opensearch.rest.RestRequest.Method.POST; /** - * Handles HTTP requests to the POST - * {@value com.wazuh.commandmanager.CommandManagerPlugin#COMMANDS_URI} - * endpoint. + * Handles HTTP requests to the POST {@value + * com.wazuh.commandmanager.CommandManagerPlugin#COMMANDS_URI} endpoint. */ public class RestPostCommandAction extends BaseRestHandler { - public static final String POST_COMMAND_ACTION_REQUEST_DETAILS = "post_command_action_request_details"; + public static final String POST_COMMAND_ACTION_REQUEST_DETAILS = + "post_command_action_request_details"; private static final Logger log = LogManager.getLogger(RestPostCommandAction.class); private final CommandIndex commandIndex; @@ -55,7 +57,6 @@ public class RestPostCommandAction extends BaseRestHandler { */ public RestPostCommandAction(CommandIndex commandIndex) { this.commandIndex = commandIndex; - } public String getName() { @@ -66,21 +67,12 @@ public String getName() { public List routes() { return Collections.singletonList( new Route( - POST, - String.format( - Locale.ROOT, - "%s", - CommandManagerPlugin.COMMANDS_URI - ) - ) - ); + POST, String.format(Locale.ROOT, "%s", CommandManagerPlugin.COMMANDS_URI))); } @Override - protected RestChannelConsumer prepareRequest( - final RestRequest request, - final NodeClient client - ) throws IOException { + protected RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) + throws IOException { switch (request.method()) { case POST: return handlePost(request); @@ -103,27 +95,27 @@ private RestChannelConsumer handlePost(RestRequest request) throws IOException { request.method().name(), request.uri(), request.getRequestId(), - request.header("Host") - ); + request.header("Host")); // Get request details XContentParser parser = request.contentParser(); ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser); Command command = Command.parse(parser); - Document document = new Document( - new Agent(List.of("groups000")), // TODO read agent from .agents index - command - ); + Document document = + new Document( + new Agent(List.of("groups000")), // TODO read agent from .agents index + command); // Commands delivery to the Management API. // Note: needs to be decoupled from the Rest handler (job scheduler task). HttpRestClient httpClient = HttpRestClient.getInstance(); try { String uri = "https://httpbin.org/post"; -// String uri = "https://127.0.0.1:5000"; - URI receiverURI = new URIBuilder(uri) - .build(); - String payload = document.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS).toString(); + // String uri = "https://127.0.0.1:5000"; + URI receiverURI = new URIBuilder(uri).build(); + String payload = + document.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS) + .toString(); SimpleHttpResponse response = httpClient.post(receiverURI, payload, document.getId()); log.info("Received response to POST request with code [{}]", response.getCode()); log.info("Raw response:\n{}", response.getBodyText()); @@ -135,27 +127,35 @@ private RestChannelConsumer handlePost(RestRequest request) throws IOException { // Send response return channel -> { - this.commandIndex.asyncCreate(document) - .thenAccept(restStatus -> { - try (XContentBuilder builder = channel.newBuilder()) { - builder.startObject(); - builder.field("_index", CommandManagerPlugin.COMMAND_MANAGER_INDEX_NAME); - builder.field("_id", document.getId()); - builder.field("result", restStatus.name()); - builder.endObject(); - channel.sendResponse(new BytesRestResponse(restStatus, builder)); - } catch (IOException e) { - log.error("Error preparing response to [{}] request with id [{}] due to {}", - request.method().name(), - request.getRequestId(), - e.getMessage() - ); - } - }).exceptionally(e -> { - channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, e.getMessage())); - return null; - }); - + this.commandIndex + .asyncCreate(document) + .thenAccept( + restStatus -> { + try (XContentBuilder builder = channel.newBuilder()) { + builder.startObject(); + builder.field( + "_index", + CommandManagerPlugin.COMMAND_MANAGER_INDEX_NAME); + builder.field("_id", document.getId()); + builder.field("result", restStatus.name()); + builder.endObject(); + channel.sendResponse( + new BytesRestResponse(restStatus, builder)); + } catch (IOException e) { + log.error( + "Error preparing response to [{}] request with id [{}] due to {}", + request.method().name(), + request.getRequestId(), + e.getMessage()); + } + }) + .exceptionally( + e -> { + channel.sendResponse( + new BytesRestResponse( + RestStatus.INTERNAL_SERVER_ERROR, e.getMessage())); + return null; + }); }; } } diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClient.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClient.java index 679bd72..9e70783 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClient.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClient.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -26,10 +27,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -/** - * HTTP Rest client. Currently used to perform - * POST requests against the Wazuh Server. - */ +/** HTTP Rest client. Currently used to perform POST requests against the Wazuh Server. */ public class HttpRestClient { public static final long TIMEOUT = 4; @@ -38,9 +36,7 @@ public class HttpRestClient { private static HttpRestClient instance; private CloseableHttpAsyncClient httpClient; - /** - * Private default constructor - */ + /** Private default constructor */ private HttpRestClient() { startHttpAsyncClient(); } @@ -57,23 +53,21 @@ public static HttpRestClient getInstance() { return HttpRestClient.instance; } - /** - * Starts http async client. - */ + /** Starts http async client. */ private void startHttpAsyncClient() { if (this.httpClient == null) { try { PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create().build(); - IOReactorConfig ioReactorConfig = IOReactorConfig.custom() - .setSoTimeout(Timeout.ofSeconds(5)) - .build(); + IOReactorConfig ioReactorConfig = + IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build(); - httpClient = HttpAsyncClients.custom() - .setIOReactorConfig(ioReactorConfig) - .setConnectionManager(cm) - .build(); + httpClient = + HttpAsyncClients.custom() + .setIOReactorConfig(ioReactorConfig) + .setConnectionManager(cm) + .build(); httpClient.start(); } catch (Exception e) { @@ -83,9 +77,7 @@ private void startHttpAsyncClient() { } } - /** - * Stop http async client. - */ + /** Stop http async client. */ public void stopHttpAsyncClient() { if (this.httpClient != null) { log.info("Shutting down."); @@ -98,26 +90,22 @@ public void stopHttpAsyncClient() { * Sends a POST request. * * @param receiverURI Well-formed URI - * @param payload data to send - * @param payloadId payload ID + * @param payload data to send + * @param payloadId payload ID * @return SimpleHttpResponse response */ public SimpleHttpResponse post(URI receiverURI, String payload, String payloadId) { try { HttpHost httpHost = HttpHost.create(receiverURI); - log.info( - "Sending payload with id [{}] to [{}]", - payloadId, - receiverURI - ); + log.info("Sending payload with id [{}] to [{}]", payloadId, receiverURI); - SimpleHttpRequest httpPostRequest = SimpleRequestBuilder - .post() - .setHttpHost(httpHost) - .setPath(receiverURI.getPath()) - .setBody(payload, ContentType.APPLICATION_JSON) - .build(); + SimpleHttpRequest httpPostRequest = + SimpleRequestBuilder.post() + .setHttpHost(httpHost) + .setPath(receiverURI.getPath()) + .setBody(payload, ContentType.APPLICATION_JSON) + .build(); Future future = this.httpClient.execute( @@ -125,9 +113,9 @@ public SimpleHttpResponse post(URI receiverURI, String payload, String payloadId SimpleResponseConsumer.create(), new HttpResponseCallback( httpPostRequest, - "Failed to execute outgoing POST request with payload id [" + payloadId + "]" - ) - ); + "Failed to execute outgoing POST request with payload id [" + + payloadId + + "]")); return future.get(TIMEOUT, TIME_UNIT); } catch (InterruptedException e) { diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClientDemo.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClientDemo.java index d11e423..2fff5c6 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClientDemo.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClientDemo.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -17,9 +18,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; -/** - * Demo class to test the {@link HttpRestClient} class. - */ +/** Demo class to test the {@link HttpRestClient} class. */ public class HttpRestClientDemo { private static final Logger log = LogManager.getLogger(HttpRestClientDemo.class); @@ -28,25 +27,28 @@ public class HttpRestClientDemo { * Demo method to test the {@link HttpRestClient} class. * * @param endpoint POST's requests endpoint as a well-formed URI - * @param body POST's request body as a JSON string. + * @param body POST's request body as a JSON string. */ public static void run(String endpoint, String body) { log.info("Executing POST request"); AccessController.doPrivileged( - (PrivilegedAction) () -> { - HttpRestClient httpClient = HttpRestClient.getInstance(); - try { - URI host = new URIBuilder(endpoint).build(); - SimpleHttpResponse response = httpClient.post(host, body, "randomId"); - log.info("Received response to POST request with code {}", response.getCode()); - log.info("Raw response:\n{}", response.getBodyText()); - } catch (URISyntaxException e) { - log.error("Bad URI:{}", e.getMessage()); - } catch (Exception e) { - log.error("Error reading response: {}", e.getMessage()); - } - return null; - } - ); + (PrivilegedAction) + () -> { + HttpRestClient httpClient = HttpRestClient.getInstance(); + try { + URI host = new URIBuilder(endpoint).build(); + SimpleHttpResponse response = + httpClient.post(host, body, "randomId"); + log.info( + "Received response to POST request with code {}", + response.getCode()); + log.info("Raw response:\n{}", response.getBodyText()); + } catch (URISyntaxException e) { + log.error("Bad URI:{}", e.getMessage()); + } catch (Exception e) { + log.error("Error reading response: {}", e.getMessage()); + } + return null; + }); } } diff --git a/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerTests.java b/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerTests.java index 6c09f88..ea5bf95 100644 --- a/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerTests.java +++ b/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerTests.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,16 +8,17 @@ */ package com.wazuh.commandmanager; -import com.wazuh.commandmanager.utils.httpclient.HttpRestClient; import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; -import org.junit.Assert; import org.opensearch.test.OpenSearchTestCase; +import org.junit.Assert; import java.net.URI; import java.net.URISyntaxException; import java.security.AccessController; import java.security.PrivilegedAction; +import com.wazuh.commandmanager.utils.httpclient.HttpRestClient; + public class CommandManagerTests extends OpenSearchTestCase { // Add unit tests for your plugin @@ -25,26 +27,27 @@ public class CommandManagerTests extends OpenSearchTestCase { public void testPost_success() { try { AccessController.doPrivileged( - (PrivilegedAction) () -> { - this.httpClient = HttpRestClient.getInstance(); - URI uri; - try { - uri = new URI("https://httpbin.org/post"); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - String payload = "{\"message\": \"Hello world!\"}"; - SimpleHttpResponse postResponse = this.httpClient.post(uri, payload, "randomId"); - - String responseText = postResponse.getBodyText(); - assertNotEquals(null, postResponse); - assertNotEquals(null, responseText); - assertEquals(200, postResponse.getCode()); - assertNotEquals(0, responseText.length()); - assertTrue(responseText.contains("Hello world!")); - return postResponse; - } - ); + (PrivilegedAction) + () -> { + this.httpClient = HttpRestClient.getInstance(); + URI uri; + try { + uri = new URI("https://httpbin.org/post"); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + String payload = "{\"message\": \"Hello world!\"}"; + SimpleHttpResponse postResponse = + this.httpClient.post(uri, payload, "randomId"); + + String responseText = postResponse.getBodyText(); + assertNotEquals(null, postResponse); + assertNotEquals(null, responseText); + assertEquals(200, postResponse.getCode()); + assertNotEquals(0, responseText.length()); + assertTrue(responseText.contains("Hello world!")); + return postResponse; + }); } catch (Exception e) { Assert.fail("Failed to execute HTTP request: " + e); } finally { @@ -52,9 +55,7 @@ public void testPost_success() { } } - public void testPost_badUri() { - } + public void testPost_badUri() {} - public void testPost_badPayload() { - } + public void testPost_badPayload() {} }