Skip to content

Commit

Permalink
Improve Sonar quality gate
Browse files Browse the repository at this point in the history
  • Loading branch information
Sashir Estela committed Mar 19, 2024
1 parent ecded63 commit c72c2aa
Show file tree
Hide file tree
Showing 14 changed files with 95 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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<String, Object>) bodyObject);
var bodyBytes = HttpMultipart.toByteArrays((Map<String, Object>) 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<String, Object>) 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<String> 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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<AnnotationMetadata> annotations;
Expand Down Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ private List<ParameterMetadata> 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);
}
Expand All @@ -123,11 +123,9 @@ private List<ParameterMetadata> 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ public <S, T> 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));
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ public <S, T> 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));

Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> linesToCheck = null;

private LineRecord record;
private List<String> eventsToRead;
private LineRecord lineRecord;
private List<String> endsOfStream;
private List<String> 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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> eventsToRead;
@Getter
private List<String> endsOfStream;

private List<String> linesToCheck;
private boolean wasBuilt = false;

private Configurator() {
}

@Builder
public Configurator(@Singular("eventToRead") List<String> eventsToRead,
@Singular("endOfStream") List<String> 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<String> getLinesToCheck() {
if (linesToCheck == null) {
linesToCheck = eventsToRead.stream().filter(etr -> !etr.isEmpty()).map(etr -> (EVENT_HEADER + etr))
.collect(Collectors.toList());
linesToCheck.add(SEPARATOR);
}
return linesToCheck;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -49,23 +49,23 @@ public static Map<String, String> createMapString(String... keyValPairs) {
throw new IllegalArgumentException("It is expected an even number of elements.");
}
Map<String, String> 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;
}

public static List<String> mapToListOfString(Map<String, String> map) {
List<String> 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;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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 = "\\{(.*?)\\}";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import lombok.Getter;
import lombok.NoArgsConstructor;

public class UnixTimestampDeserializerTest {
class UnixTimestampDeserializerTest {

@Test
void testDeserialize() {
Expand Down

0 comments on commit c72c2aa

Please sign in to comment.