From 7f29409406ef7f1c7bc3b49c213abcac958c555a Mon Sep 17 00:00:00 2001 From: Alex Ruiz Date: Tue, 17 Dec 2024 20:46:25 +0100 Subject: [PATCH] Add final variables that are effectively final --- .../jobscheduler/SearchThread.java | 37 +++++++++--------- .../utils/httpclient/HttpRestClient.java | 38 +++++-------------- 2 files changed, 29 insertions(+), 46 deletions(-) diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/jobscheduler/SearchThread.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/jobscheduler/SearchThread.java index 1d4dbc0..a2546f7 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/jobscheduler/SearchThread.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/jobscheduler/SearchThread.java @@ -89,7 +89,7 @@ public SearchThread(Client client) { * @return the nested object cast into the proper type. */ public static T getNestedObject(Map map, String key, Class type) { - Object value = map.get(key); + final Object value = map.get(key); if (value == null) { return null; } @@ -120,7 +120,7 @@ public void handlePage(SearchResponse searchResponse) throws IllegalStateExcepti SearchHits searchHits = searchResponse.getHits(); ArrayList orders = new ArrayList<>(); for (SearchHit hit : searchHits) { - Map orderMap = + final Map orderMap = getNestedObject(hit.getSourceAsMap(), Command.COMMAND, Map.class); if (orderMap != null) { orderMap.put("document_id", hit.getId()); @@ -128,9 +128,10 @@ public void handlePage(SearchResponse searchResponse) throws IllegalStateExcepti } } try (XContentBuilder builder = XContentFactory.jsonBuilder()) { - String payload = builder.map(Collections.singletonMap("orders", orders)).toString(); + final String payload = + builder.map(Collections.singletonMap("orders", orders)).toString(); - SimpleHttpResponse response = deliverOrders(payload); + final SimpleHttpResponse response = deliverOrders(payload); if (response == null) { log.error("No reply from server."); return; @@ -142,7 +143,7 @@ public void handlePage(SearchResponse searchResponse) throws IllegalStateExcepti status = Status.SENT; } for (SearchHit hit : searchHits) { - setSentStatus(hit, status); + this.setSentStatus(hit, status); } } catch (IOException e) { log.error("Error parsing hit contents: {}", e.getMessage()); @@ -157,14 +158,16 @@ public void handlePage(SearchResponse searchResponse) throws IllegalStateExcepti private SimpleHttpResponse deliverOrders(String orders) { SimpleHttpResponse response = null; try { - PluginSettings settings = PluginSettings.getInstance(); - URI host = new URIBuilder(settings.getUri() + SearchThread.ORDERS_ENDPOINT).build(); + final PluginSettings settings = PluginSettings.getInstance(); + final URI host = + new URIBuilder(settings.getUri() + SearchThread.ORDERS_ENDPOINT).build(); response = AccessController.doPrivileged( (PrivilegedAction) () -> { - AuthHttpRestClient httpClient = new AuthHttpRestClient(); + final AuthHttpRestClient httpClient = + new AuthHttpRestClient(); return httpClient.post(host, orders, null); }); } catch (URISyntaxException e) { @@ -183,7 +186,7 @@ private SimpleHttpResponse deliverOrders(String orders) { */ @SuppressWarnings("unchecked") private void setSentStatus(SearchHit hit, Status status) throws IllegalStateException { - Map commandMap = + final Map commandMap = getNestedObject( hit.getSourceAsMap(), CommandManagerPlugin.COMMAND_DOCUMENT_PARENT_OBJECT_NAME, @@ -191,7 +194,7 @@ private void setSentStatus(SearchHit hit, Status status) throws IllegalStateExce commandMap.put(Command.STATUS, status); hit.getSourceAsMap() .put(CommandManagerPlugin.COMMAND_DOCUMENT_PARENT_OBJECT_NAME, commandMap); - IndexRequest indexRequest = + final IndexRequest indexRequest = new IndexRequest() .index(CommandManagerPlugin.INDEX_NAME) .source(hit.getSourceAsMap()) @@ -211,10 +214,10 @@ private void setSentStatus(SearchHit hit, Status status) throws IllegalStateExce */ public SearchResponse pitQuery(PointInTimeBuilder pointInTimeBuilder, Object[] searchAfter) throws IllegalStateException { - SearchRequest searchRequest = new SearchRequest(CommandManagerPlugin.INDEX_NAME); - TermQueryBuilder termQueryBuilder = + final SearchRequest searchRequest = new SearchRequest(CommandManagerPlugin.INDEX_NAME); + final TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(SearchThread.COMMAND_STATUS_FIELD, Status.PENDING); - TimeValue timeout = + final TimeValue timeout = TimeValue.timeValueSeconds(CommandManagerPlugin.DEFAULT_TIMEOUT_SECONDS); this.searchSourceBuilder .query(termQueryBuilder) @@ -237,7 +240,7 @@ public void run() { log.debug("Running scheduled job"); long consumableHits = 0L; boolean firstPage = true; - PointInTimeBuilder pointInTimeBuilder = buildPit(); + final PointInTimeBuilder pointInTimeBuilder = buildPit(); try { do { this.currentPage = @@ -294,7 +297,7 @@ private Optional getSearchAfter(SearchResponse searchResponse) { return Optional.empty(); } try { - List hits = Arrays.asList(searchResponse.getHits().getHits()); + final List hits = Arrays.asList(searchResponse.getHits().getHits()); if (hits.isEmpty()) { log.warn("Empty hits page, not getting searchAfter values"); return Optional.empty(); @@ -312,8 +315,8 @@ private Optional getSearchAfter(SearchResponse searchResponse) { * @return a PointInTimeBuilder or null. */ private PointInTimeBuilder buildPit() { - CompletableFuture future = new CompletableFuture<>(); - ActionListener actionListener = + final CompletableFuture future = new CompletableFuture<>(); + final ActionListener actionListener = new ActionListener<>() { @Override public void onResponse(CreatePitResponse createPitResponse) { 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 8cc9cd2..c613437 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 @@ -25,7 +25,6 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder; -import org.apache.hc.core5.function.Factory; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHost; @@ -39,7 +38,6 @@ import org.apache.logging.log4j.Logger; import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; import java.net.URI; import java.util.concurrent.ExecutionException; @@ -87,19 +85,6 @@ private void startHttpAsyncClient() { try { // From the official example on // https://opensearch.org/docs/latest/clients/java/#initializing-the-client-with-ssl-and-tls-enabled-using-apache-httpclient-5-transport - // TODO extract hardcoded values to settings. - // System.setProperty("javax.net.ssl.trustStore", - // "/usr/share/wazuh-indexer/jdk/lib/security/cacerts"); - // System.setProperty("javax.net.ssl.trustStorePassword", ""); - - // CredentialsProvider basicCredentials = - // CredentialsProviderBuilder.create() - // .add( - // HttpHost.create(loginUri), - // PluginSettings.getInstance().getAuthUsername(), - // - // PluginSettings.getInstance().getAuthPassword().toCharArray() - // ).build(); // Basic auth final String mApiURI = PluginSettings.getInstance().getUri(); @@ -124,14 +109,10 @@ private void startHttpAsyncClient() { ClientTlsStrategyBuilder.create() .setSslContext(sslContext) .setTlsDetailsFactory( - new Factory() { - @Override - public TlsDetails create(SSLEngine sslEngine) { - return new TlsDetails( + sslEngine -> + new TlsDetails( sslEngine.getSession(), - sslEngine.getApplicationProtocol()); - } - }) + sslEngine.getApplicationProtocol())) .build(); final PoolingAsyncClientConnectionManager connectionManager = @@ -139,7 +120,7 @@ public TlsDetails create(SSLEngine sslEngine) { .setTlsStrategy(tlsStrategy) .build(); - IOReactorConfig ioReactorConfig = + final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(TIMEOUT, TimeUnit.SECONDS).build(); httpClient = @@ -149,8 +130,7 @@ public TlsDetails create(SSLEngine sslEngine) { .setConnectionManager(connectionManager) .build(); httpClient.start(); - } catch (Exception e) { - // handle exception + } catch (Exception e) { // FIXME catch of generic exception log.error("Error starting async Http client {}", e.getMessage()); } } @@ -180,12 +160,12 @@ public SimpleHttpResponse post( @Nullable String payloadId, @Nullable Header... headers) { try { - HttpHost httpHost = HttpHost.create(receiverURI); + final HttpHost httpHost = HttpHost.create(receiverURI); log.info("Sending payload with id [{}] to [{}]", payloadId, receiverURI); log.debug("Headers {}", (Object) headers); - SimpleRequestBuilder builder = SimpleRequestBuilder.post(); + final SimpleRequestBuilder builder = SimpleRequestBuilder.post(); if (payload != null) { builder.setBody(payload, ContentType.APPLICATION_JSON); } @@ -193,10 +173,10 @@ public SimpleHttpResponse post( builder.setHeaders(headers); } - SimpleHttpRequest httpPostRequest = + final SimpleHttpRequest httpPostRequest = builder.setHttpHost(httpHost).setPath(receiverURI.getPath()).build(); - Future future = + final Future future = this.httpClient.execute( SimpleRequestProducer.create(httpPostRequest), SimpleResponseConsumer.create(),