From c72c2aab9c20d70b4f45d44103929a7dbb23f4e1 Mon Sep 17 00:00:00 2001 From: Sashir Estela Date: Tue, 19 Mar 2024 02:11:34 +0000 Subject: [PATCH] Improve Sonar quality gate --- .../cleverclient/http/HttpConnector.java | 39 ++++++++----------- .../cleverclient/http/HttpProcessor.java | 11 ++---- .../metadata/InterfaceMetadata.java | 26 ++++++------- .../metadata/InterfaceMetadataStore.java | 10 ++--- .../sender/HttpAsyncStreamSender.java | 10 +++-- .../cleverclient/sender/HttpSender.java | 2 +- .../sender/HttpSyncStreamSender.java | 10 +++-- .../cleverclient/support/CleverClientSSE.java | 31 +++++---------- .../cleverclient/support/Configurator.java | 28 ++++++++++--- .../cleverclient/util/CommonUtil.java | 12 +++--- .../cleverclient/util/Constant.java | 4 +- .../metadata/InterfaceMetadataStoreTest.java | 2 +- .../support/CleverClientSSETest.java | 2 +- .../util/UnixTimestampDeserializerTest.java | 2 +- 14 files changed, 95 insertions(+), 94 deletions(-) diff --git a/src/main/java/io/github/sashirestela/cleverclient/http/HttpConnector.java b/src/main/java/io/github/sashirestela/cleverclient/http/HttpConnector.java index b3b5825..ccf4719 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/http/HttpConnector.java +++ b/src/main/java/io/github/sashirestela/cleverclient/http/HttpConnector.java @@ -48,8 +48,9 @@ public Object sendRequest() { if (requestInterceptor != null) { interceptRequest(); } + var formattedHeaders = printHeaders(headers); logger.debug("Http Call : {} {}", httpMethod, url); - logger.debug("Request Headers : {}", printHeaders(headers)); + logger.debug("Request Headers : {}", formattedHeaders); var bodyPublisher = createBodyPublisher(bodyObject, contentType); var responseClass = returnType.getBaseClass(); @@ -94,34 +95,28 @@ private BodyPublisher createBodyPublisher(Object bodyObject, ContentType content if (contentType == null) { logger.debug("Request Body : (Empty)"); bodyPublisher = BodyPublishers.noBody(); - } else { - switch (contentType) { - case MULTIPART_FORMDATA: - logger.debug("Request Body : {}", (Map) bodyObject); - var bodyBytes = HttpMultipart.toByteArrays((Map) bodyObject); - bodyPublisher = BodyPublishers.ofByteArrays(bodyBytes); - break; - - case APPLICATION_JSON: - logger.debug("Request Body : {}", (String) bodyObject); - bodyPublisher = BodyPublishers.ofString((String) bodyObject); - break; - } + } else if (contentType == ContentType.MULTIPART_FORMDATA) { + logger.debug("Request Body : {}", bodyObject); + var bodyBytes = HttpMultipart.toByteArrays((Map) bodyObject); + bodyPublisher = BodyPublishers.ofByteArrays(bodyBytes); + } else if (contentType == ContentType.APPLICATION_JSON) { + logger.debug("Request Body : {}", bodyObject); + bodyPublisher = BodyPublishers.ofString((String) bodyObject); } return bodyPublisher; } private String printHeaders(List headers) { - var print = "{"; - for (var i = 0; i < headers.size(); i++) { + var print = new StringBuilder("{"); + for (var i = 0; i < headers.size(); i += 2) { if (i > 1) { - print += ", "; + print.append(", "); } - var headerKey = headers.get(i++); - var headerVal = headerKey.equals("Authorization") ? "*".repeat(10) : headers.get(i); - print += headerKey + " = " + headerVal; + var headerKey = headers.get(i); + var headerVal = headerKey.equals("Authorization") ? "*".repeat(10) : headers.get(i + 1); + print.append(headerKey + " = " + headerVal); } - print += "}"; - return print; + print.append("}"); + return print.toString(); } } \ No newline at end of file diff --git a/src/main/java/io/github/sashirestela/cleverclient/http/HttpProcessor.java b/src/main/java/io/github/sashirestela/cleverclient/http/HttpProcessor.java index 0469a52..914ece9 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/http/HttpProcessor.java +++ b/src/main/java/io/github/sashirestela/cleverclient/http/HttpProcessor.java @@ -123,13 +123,10 @@ private Object calculateBodyObject(MethodMetadata methodMetadata, Object[] argum var bodyIndex = methodMetadata.getBodyIndex(); var bodyObject = bodyIndex >= 0 ? arguments[bodyIndex] : null; if (bodyObject != null) { - switch (methodMetadata.getContentType()) { - case MULTIPART_FORMDATA: - bodyObject = JsonUtil.objectToMap(bodyObject); - break; - case APPLICATION_JSON: - bodyObject = JsonUtil.objectToJson(bodyObject); - break; + if (methodMetadata.getContentType() == ContentType.MULTIPART_FORMDATA) { + bodyObject = JsonUtil.objectToMap(bodyObject); + } else if (methodMetadata.getContentType() == ContentType.APPLICATION_JSON) { + bodyObject = JsonUtil.objectToJson(bodyObject); } } return bodyObject; diff --git a/src/main/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadata.java b/src/main/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadata.java index a972822..d1b200c 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadata.java +++ b/src/main/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadata.java @@ -13,14 +13,14 @@ @Value @Builder public class InterfaceMetadata { - private final static String ANNOT_RESOURCE = "Resource"; - private final static String ANNOT_HEADER = "Header"; - private final static String ANNOT_MULTIPART = "Multipart"; - private final static String ANNOT_PARAM_BODY = "Body"; - private final static String ANNOT_PARAM_PATH = "Path"; - private final static String ANNOT_PARAM_QUERY = "Query"; - private final static String ANNOT_FIELD_NAME = "name"; - private final static String ANNOT_FIELD_VALUE = "value"; + private static final String ANNOT_RESOURCE = "Resource"; + private static final String ANNOT_HEADER = "Header"; + private static final String ANNOT_MULTIPART = "Multipart"; + private static final String ANNOT_PARAM_BODY = "Body"; + private static final String ANNOT_PARAM_PATH = "Path"; + private static final String ANNOT_PARAM_QUERY = "Query"; + private static final String ANNOT_FIELD_NAME = "name"; + private static final String ANNOT_FIELD_VALUE = "value"; String name; List annotations; @@ -77,11 +77,11 @@ public String getHttpAnnotationName() { } public ContentType getContentType() { - return getBodyIndex() == -1 - ? null - : isMultipart() - ? ContentType.MULTIPART_FORMDATA - : ContentType.APPLICATION_JSON; + if (getBodyIndex() == -1) { + return null; + } else { + return isMultipart() ? ContentType.MULTIPART_FORMDATA : ContentType.APPLICATION_JSON; + } } private boolean isMultipart() { diff --git a/src/main/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadataStore.java b/src/main/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadataStore.java index 36d00a0..5f58791 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadataStore.java +++ b/src/main/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadataStore.java @@ -114,7 +114,7 @@ private List getParameters(Parameter[] javaParameters) { var annotations = getAnnotations(javaParameter.getDeclaredAnnotations()); var parameterMetadata = ParameterMetadata.builder() .index(index++) - .annotation(annotations.size() > 0 ? annotations.get(0) : null) + .annotation(!annotations.isEmpty() ? annotations.get(0) : null) .build(); parameters.add(parameterMetadata); } @@ -123,11 +123,9 @@ private List getParameters(Parameter[] javaParameters) { private void validate(InterfaceMetadata interfaceMetadata) { interfaceMetadata.getMethodBySignature().forEach((methodSignature, methodMetadata) -> { - if (!methodMetadata.isDefault()) { - if (!methodMetadata.hasHttpAnnotation()) { - throw new CleverClientException("Missing HTTP annotation for the method {0}.", - methodMetadata.getName(), null); - } + if (!methodMetadata.isDefault() && !methodMetadata.hasHttpAnnotation()) { + throw new CleverClientException("Missing HTTP annotation for the method {0}.", + methodMetadata.getName(), null); } var url = interfaceMetadata.getFullUrlByMethod(methodMetadata); var listPathParams = CommonUtil.findFullMatches(url, Constant.REGEX_PATH_PARAM_URL); diff --git a/src/main/java/io/github/sashirestela/cleverclient/sender/HttpAsyncStreamSender.java b/src/main/java/io/github/sashirestela/cleverclient/sender/HttpAsyncStreamSender.java index e363cf2..6ee8a21 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/sender/HttpAsyncStreamSender.java +++ b/src/main/java/io/github/sashirestela/cleverclient/sender/HttpAsyncStreamSender.java @@ -20,12 +20,14 @@ public Object sendRequest(HttpClient httpClient, HttpRequest httpRequest, throwExceptionIfErrorIsPresent(response, Stream.class); - final var record = new CleverClientSSE.LineRecord(); + final var lineRecord = new CleverClientSSE.LineRecord(); return response.body() - .peek(line -> logger.debug("Response : {}", line)) - .peek(line -> record.updateWith(line)) - .map(line -> new CleverClientSSE(record)) + .peek(line -> { + logger.debug("Response : {}", line); + lineRecord.updateWith(line); + }) + .map(line -> new CleverClientSSE(lineRecord)) .filter(CleverClientSSE::isActualData) .map(item -> JsonUtil.jsonToObject(item.getActualData(), responseClass)); }); diff --git a/src/main/java/io/github/sashirestela/cleverclient/sender/HttpSender.java b/src/main/java/io/github/sashirestela/cleverclient/sender/HttpSender.java index e396bf9..45dd080 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/sender/HttpSender.java +++ b/src/main/java/io/github/sashirestela/cleverclient/sender/HttpSender.java @@ -57,7 +57,7 @@ protected void throwExceptionIfErrorIsPresent(HttpResponse response, Class try { data = new String(((InputStream) response.body()).readAllBytes(), StandardCharsets.UTF_8); } catch (IOException e) { - e.printStackTrace(); + logger.error("Cannot read input stream. {}", e.getMessage()); } } else { data = (String) response.body(); diff --git a/src/main/java/io/github/sashirestela/cleverclient/sender/HttpSyncStreamSender.java b/src/main/java/io/github/sashirestela/cleverclient/sender/HttpSyncStreamSender.java index 5c30f24..7b9d6e1 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/sender/HttpSyncStreamSender.java +++ b/src/main/java/io/github/sashirestela/cleverclient/sender/HttpSyncStreamSender.java @@ -21,12 +21,14 @@ public Object sendRequest(HttpClient httpClient, HttpRequest httpRequest, throwExceptionIfErrorIsPresent(httpResponse, Stream.class); - final var record = new CleverClientSSE.LineRecord(); + final var lineRecord = new CleverClientSSE.LineRecord(); return httpResponse.body() - .peek(line -> logger.debug("Response : {}", line)) - .peek(line -> record.updateWith(line)) - .map(line -> new CleverClientSSE(record)) + .peek(line -> { + logger.debug("Response : {}", line); + lineRecord.updateWith(line); + }) + .map(line -> new CleverClientSSE(lineRecord)) .filter(CleverClientSSE::isActualData) .map(item -> JsonUtil.jsonToObject(item.getActualData(), responseClass)); diff --git a/src/main/java/io/github/sashirestela/cleverclient/support/CleverClientSSE.java b/src/main/java/io/github/sashirestela/cleverclient/support/CleverClientSSE.java index 7b44c11..b82c993 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/support/CleverClientSSE.java +++ b/src/main/java/io/github/sashirestela/cleverclient/support/CleverClientSSE.java @@ -1,43 +1,32 @@ package io.github.sashirestela.cleverclient.support; import java.util.List; -import java.util.stream.Collectors; public class CleverClientSSE { - private static final String EVENT_HEADER = "event: "; private static final String DATA_HEADER = "data: "; - private static final String SEPARATOR = ""; - private static List linesToCheck = null; - - private LineRecord record; - private List eventsToRead; + private LineRecord lineRecord; private List endsOfStream; + private List linesToCheck; - public CleverClientSSE(LineRecord record) { - this.record = record; - this.eventsToRead = Configurator.one().getEventsToRead(); + public CleverClientSSE(LineRecord lineRecord) { + this.lineRecord = lineRecord; + this.linesToCheck = Configurator.one().getLinesToCheck(); this.endsOfStream = Configurator.one().getEndsOfStream(); - - if (linesToCheck == null) { - linesToCheck = this.eventsToRead.stream().filter(etr -> !etr.isEmpty()).map(etr -> (EVENT_HEADER + etr)) - .collect(Collectors.toList()); - linesToCheck.add(SEPARATOR); - } } - public LineRecord getRecord() { - return record; + public LineRecord getLineRecord() { + return lineRecord; } public boolean isActualData() { - return linesToCheck.contains(record.previous()) && record.current().startsWith(DATA_HEADER) - && endsOfStream.stream().anyMatch(eos -> !record.current().contains(eos)); + return linesToCheck.contains(lineRecord.previous()) && lineRecord.current().startsWith(DATA_HEADER) + && endsOfStream.stream().anyMatch(eos -> !lineRecord.current().contains(eos)); } public String getActualData() { - return record.current().replace(DATA_HEADER, "").strip(); + return lineRecord.current().replace(DATA_HEADER, "").strip(); } public static class LineRecord { diff --git a/src/main/java/io/github/sashirestela/cleverclient/support/Configurator.java b/src/main/java/io/github/sashirestela/cleverclient/support/Configurator.java index f5266d4..b6e9e48 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/support/Configurator.java +++ b/src/main/java/io/github/sashirestela/cleverclient/support/Configurator.java @@ -1,37 +1,55 @@ package io.github.sashirestela.cleverclient.support; import java.util.List; +import java.util.stream.Collectors; import lombok.Builder; import lombok.Getter; import lombok.Singular; -@Getter public class Configurator { - private static Configurator configurator; + private static final String EVENT_HEADER = "event: "; + private static final String SEPARATOR = ""; + private static Configurator configurator = new Configurator(); + + @Getter private List eventsToRead; + @Getter private List endsOfStream; + private List linesToCheck; + private boolean wasBuilt = false; + private Configurator() { } @Builder public Configurator(@Singular("eventToRead") List eventsToRead, @Singular("endOfStream") List endsOfStream) { - if (configurator != null) { + if (configurator.wasBuilt) { return; } - configurator = new Configurator(); configurator.eventsToRead = eventsToRead; configurator.endsOfStream = endsOfStream; + configurator.wasBuilt = true; } public static Configurator one() { - if (configurator == null) { + if (!configurator.wasBuilt) { throw new CleverClientException("You have to call Configurator.builder() first."); } return configurator; } + + public List getLinesToCheck() { + if (linesToCheck == null) { + linesToCheck = eventsToRead.stream().filter(etr -> !etr.isEmpty()).map(etr -> (EVENT_HEADER + etr)) + .collect(Collectors.toList()); + linesToCheck.add(SEPARATOR); + } + return linesToCheck; + } + } diff --git a/src/main/java/io/github/sashirestela/cleverclient/util/CommonUtil.java b/src/main/java/io/github/sashirestela/cleverclient/util/CommonUtil.java index ae302b8..9e287ef 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/util/CommonUtil.java +++ b/src/main/java/io/github/sashirestela/cleverclient/util/CommonUtil.java @@ -49,12 +49,12 @@ public static Map createMapString(String... keyValPairs) { throw new IllegalArgumentException("It is expected an even number of elements."); } Map map = new HashMap<>(); - for (var i = 0; i < keyValPairs.length; i++) { + for (var i = 0; i < keyValPairs.length; i += 2) { var key = keyValPairs[i]; if (key == null) { throw new IllegalArgumentException("Unexpected null element for key in position " + i + "."); } - var val = keyValPairs[++i]; + var val = keyValPairs[i + 1]; map.put(key, val); } return map; @@ -62,10 +62,10 @@ public static Map createMapString(String... keyValPairs) { public static List mapToListOfString(Map map) { List list = new ArrayList<>(); - map.entrySet().stream().peek(e -> { - list.add(e.getKey()); - list.add(e.getValue()); - }).collect(Collectors.counting()); + for (var entry : map.entrySet()) { + list.add(entry.getKey()); + list.add(entry.getValue()); + } return list; } diff --git a/src/main/java/io/github/sashirestela/cleverclient/util/Constant.java b/src/main/java/io/github/sashirestela/cleverclient/util/Constant.java index 0a21655..82c09c9 100644 --- a/src/main/java/io/github/sashirestela/cleverclient/util/Constant.java +++ b/src/main/java/io/github/sashirestela/cleverclient/util/Constant.java @@ -1,13 +1,13 @@ package io.github.sashirestela.cleverclient.util; import java.math.BigInteger; -import java.util.Random; +import java.security.SecureRandom; public class Constant { private Constant() { } - public static final String BOUNDARY_VALUE = new BigInteger(256, new Random()).toString(); + public static final String BOUNDARY_VALUE = new BigInteger(256, new SecureRandom()).toString(); public static final String REGEX_PATH_PARAM_URL = "\\{(.*?)\\}"; diff --git a/src/test/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadataStoreTest.java b/src/test/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadataStoreTest.java index f347665..c67e45b 100644 --- a/src/test/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadataStoreTest.java +++ b/src/test/java/io/github/sashirestela/cleverclient/metadata/InterfaceMetadataStoreTest.java @@ -16,7 +16,7 @@ import io.github.sashirestela.cleverclient.support.CleverClientException; import io.github.sashirestela.cleverclient.support.ReturnType;; -public class InterfaceMetadataStoreTest { +class InterfaceMetadataStoreTest { InterfaceMetadataStore store = InterfaceMetadataStore.one(); diff --git a/src/test/java/io/github/sashirestela/cleverclient/support/CleverClientSSETest.java b/src/test/java/io/github/sashirestela/cleverclient/support/CleverClientSSETest.java index 3b027f4..662e56f 100644 --- a/src/test/java/io/github/sashirestela/cleverclient/support/CleverClientSSETest.java +++ b/src/test/java/io/github/sashirestela/cleverclient/support/CleverClientSSETest.java @@ -42,7 +42,7 @@ void shouldReturnExpectedValueWhenRawDataHasDifferentValues() { @SuppressWarnings("unused") void shouldReturnTheActualDataWhenRawDataMeetsConditions() { CleverClientSSE event = new CleverClientSSE(new LineRecord("event: process", "data: This is the actual data. ")); - var rawData = event.getRecord(); + var rawData = event.getLineRecord(); var actualData = event.getActualData(); var expectedData = "This is the actual data."; assertEquals(expectedData, actualData); diff --git a/src/test/java/io/github/sashirestela/cleverclient/util/UnixTimestampDeserializerTest.java b/src/test/java/io/github/sashirestela/cleverclient/util/UnixTimestampDeserializerTest.java index 67f97d5..86282f7 100644 --- a/src/test/java/io/github/sashirestela/cleverclient/util/UnixTimestampDeserializerTest.java +++ b/src/test/java/io/github/sashirestela/cleverclient/util/UnixTimestampDeserializerTest.java @@ -14,7 +14,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; -public class UnixTimestampDeserializerTest { +class UnixTimestampDeserializerTest { @Test void testDeserialize() {