Skip to content

Commit

Permalink
Add final variables that are effectively final
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexRuiz7 committed Dec 17, 2024
1 parent d71ea03 commit 7f29409
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public SearchThread(Client client) {
* @return the nested object cast into the proper type.
*/
public static <T> T getNestedObject(Map<String, Object> map, String key, Class<T> type) {
Object value = map.get(key);
final Object value = map.get(key);
if (value == null) {
return null;
}
Expand Down Expand Up @@ -120,17 +120,18 @@ public void handlePage(SearchResponse searchResponse) throws IllegalStateExcepti
SearchHits searchHits = searchResponse.getHits();
ArrayList<Object> orders = new ArrayList<>();
for (SearchHit hit : searchHits) {
Map<String, Object> orderMap =
final Map<String, Object> orderMap =
getNestedObject(hit.getSourceAsMap(), Command.COMMAND, Map.class);
if (orderMap != null) {
orderMap.put("document_id", hit.getId());
orders.add(orderMap);
}
}
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;
Expand All @@ -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());
Expand All @@ -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<SimpleHttpResponse>)
() -> {
AuthHttpRestClient httpClient = new AuthHttpRestClient();
final AuthHttpRestClient httpClient =
new AuthHttpRestClient();
return httpClient.post(host, orders, null);
});
} catch (URISyntaxException e) {
Expand All @@ -183,15 +186,15 @@ private SimpleHttpResponse deliverOrders(String orders) {
*/
@SuppressWarnings("unchecked")
private void setSentStatus(SearchHit hit, Status status) throws IllegalStateException {
Map<String, Object> commandMap =
final Map<String, Object> commandMap =
getNestedObject(
hit.getSourceAsMap(),
CommandManagerPlugin.COMMAND_DOCUMENT_PARENT_OBJECT_NAME,
Map.class);
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())
Expand All @@ -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)
Expand All @@ -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 =
Expand Down Expand Up @@ -294,7 +297,7 @@ private Optional<Object[]> getSearchAfter(SearchResponse searchResponse) {
return Optional.empty();
}
try {
List<SearchHit> hits = Arrays.asList(searchResponse.getHits().getHits());
final List<SearchHit> hits = Arrays.asList(searchResponse.getHits().getHits());
if (hits.isEmpty()) {
log.warn("Empty hits page, not getting searchAfter values");
return Optional.empty();
Expand All @@ -312,8 +315,8 @@ private Optional<Object[]> getSearchAfter(SearchResponse searchResponse) {
* @return a PointInTimeBuilder or null.
*/
private PointInTimeBuilder buildPit() {
CompletableFuture<CreatePitResponse> future = new CompletableFuture<>();
ActionListener<CreatePitResponse> actionListener =
final CompletableFuture<CreatePitResponse> future = new CompletableFuture<>();
final ActionListener<CreatePitResponse> actionListener =
new ActionListener<>() {
@Override
public void onResponse(CreatePitResponse createPitResponse) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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();
Expand All @@ -124,22 +109,18 @@ private void startHttpAsyncClient() {
ClientTlsStrategyBuilder.create()
.setSslContext(sslContext)
.setTlsDetailsFactory(
new Factory<SSLEngine, TlsDetails>() {
@Override
public TlsDetails create(SSLEngine sslEngine) {
return new TlsDetails(
sslEngine ->
new TlsDetails(
sslEngine.getSession(),
sslEngine.getApplicationProtocol());
}
})
sslEngine.getApplicationProtocol()))
.build();

final PoolingAsyncClientConnectionManager connectionManager =
PoolingAsyncClientConnectionManagerBuilder.create()
.setTlsStrategy(tlsStrategy)
.build();

IOReactorConfig ioReactorConfig =
final IOReactorConfig ioReactorConfig =
IOReactorConfig.custom().setSoTimeout(TIMEOUT, TimeUnit.SECONDS).build();

httpClient =
Expand All @@ -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());
}
}
Expand Down Expand Up @@ -180,23 +160,23 @@ 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);
}
if (headers != null) {
builder.setHeaders(headers);
}

SimpleHttpRequest httpPostRequest =
final SimpleHttpRequest httpPostRequest =
builder.setHttpHost(httpHost).setPath(receiverURI.getPath()).build();

Future<SimpleHttpResponse> future =
final Future<SimpleHttpResponse> future =
this.httpClient.execute(
SimpleRequestProducer.create(httpPostRequest),
SimpleResponseConsumer.create(),
Expand Down

0 comments on commit 7f29409

Please sign in to comment.