Skip to content

Commit

Permalink
FINERACT-1724: Sonar fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
abraham-menyhart authored and adamsaghy committed Aug 10, 2023
1 parent 33c1aa7 commit d6c10e8
Show file tree
Hide file tree
Showing 31 changed files with 113 additions and 276 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
* specific language governing permissions and limitations
* under the License.
*/
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.batch.repeat.RepeatStatus.FINISHED;

import com.acme.fineract.loan.job.AcmeNoopJobTasklet;
import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -47,7 +48,7 @@ public void setUp() {
@Test
public void testJobExecution() throws Exception {
resultStatus = underTest.execute(stepContribution, chunkContext);
assertEquals(resultStatus, RepeatStatus.FINISHED);
assertEquals(FINISHED, resultStatus);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package org.apache.fineract.client.util;

import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import retrofit2.Call;
import retrofit2.Response;

Expand All @@ -27,6 +28,7 @@
*
* @author Michael Vorburger.ch
*/
@Slf4j
public class CallFailedRuntimeException extends RuntimeException {

private final Call<?> call;
Expand All @@ -46,17 +48,17 @@ public <T> CallFailedRuntimeException(Call<T> call, Response<T> response) {

private static String message(Call<?> call, Response<?> response) {
StringBuilder sb = new StringBuilder("HTTP failed: " + call.request() + "; " + response);
if (response.message() != null && !response.message().isEmpty()) {
sb.append("; message: " + response.message());
if (null != response.message() && !response.message().isEmpty()) {
sb.append("; message: ").append(response.message());
}
String errorBody;
try {
errorBody = response.errorBody().string();
errorBody = response.errorBody() != null ? response.errorBody().string() : null;
if (errorBody != null) {
sb.append("; errorBody: " + errorBody);
sb.append("; errorBody: ").append(errorBody);
}
} catch (IOException e) {
// Ignore.
log.error("Exception during creating the {} message:", CallFailedRuntimeException.class.getSimpleName(), e);
}
return sb.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.google.gson.TypeAdapter;
import com.google.gson.internal.bind.util.ISO8601Utils;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import io.gsonfire.GsonFireBuilder;
import java.io.IOException;
Expand All @@ -35,10 +36,12 @@
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.apache.fineract.client.models.ExternalId;
import org.apache.fineract.client.util.adapter.ExternalIdAdapter;
import org.jetbrains.annotations.NotNull;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
Expand Down Expand Up @@ -212,25 +215,28 @@ public void write(JsonWriter out, Date date) throws IOException {
@Override
public Date read(JsonReader in) throws IOException {
try {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return dateFormat.parse(date);
}
return ISO8601Utils.parse(date, new ParsePosition(0));
} catch (ParseException e) {
throw new JsonParseException(e);
}
if (Objects.requireNonNull(in.peek()) == JsonToken.NULL) {
in.nextNull();
return null;
}
String date = in.nextString();
return parseDate(date);
} catch (IllegalArgumentException e) {
throw new JsonParseException(e);
}
}

@NotNull
private Date parseDate(String date) {
try {
if (null != dateFormat) {
return dateFormat.parse(date);
}
return ISO8601Utils.parse(date, new ParsePosition(0));
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}

// The following is not from the generated JSON class, but from the original generated ApiClient.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
public class FineractClientTechnicalTest {

@Test
@Disabled // TODO remove Ignore once https://issues.apache.org/jira/browse/FINERACT-1221 is fixed
@Disabled("remove Ignore once https://issues.apache.org/jira/browse/FINERACT-1221 is fixed")
void testInvalidOperations() {
FineractClient.Builder builder = FineractClient.builder().baseURL("http://test/").tenant("default").basicAuth("mifos", "password");
builder.getRetrofitBuilder().validateEagerly(true); // see FINERACT-1221
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,8 @@

import jakarta.ws.rs.core.MultivaluedMap;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.fineract.infrastructure.core.serialization.JsonParserHelper;
Expand Down Expand Up @@ -148,16 +145,4 @@ public static boolean genericResultSet(final MultivaluedMap<String, String> quer
public static boolean genericResultSetPassed(final MultivaluedMap<String, String> queryParams) {
return queryParams.getFirst("genericResultSet") != null;
}

public static Map<String, String> asMap(final MultivaluedMap<String, String> queryParameters) {

final Map<String, String> map = new HashMap<>(queryParameters.size());

for (final String parameterName : queryParameters.keySet()) {
final List<String> values = queryParameters.get(parameterName);
map.put(parameterName, values.get(0));
}

return map;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ public class FineractProperties {
private FineractTemplateProperties template;
private FineractJpaProperties jpa;

private FineractDatabaseProperties database;
private FineractQueryProperties query;
private FineractApiProperties api;
private FineractSecurityProperties security;
Expand Down Expand Up @@ -398,6 +399,13 @@ public static class FineractJpaProperties {
private boolean statementLoggingEnabled;
}

@Getter
@Setter
public static class FineractDatabaseProperties {

private String defaultMasterPassword;
}

@Getter
@Setter
public static class FineractQueryProperties {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
*/
package org.apache.fineract.infrastructure.core.data;

import static java.util.stream.Collectors.toList;

import com.google.common.base.Splitter;
import com.google.gson.JsonArray;
import java.math.BigDecimal;
Expand Down Expand Up @@ -176,13 +174,10 @@ public DataValidatorBuilder notSameAsParameter(final String linkedParameterName,
return this;
}

/*** FIXME: Vishwas, why does this method have a parameter? Seems wrong ***/
/*
* This method is not meant for validation, if you have mandatory boolean param and if it has invalid value or value
* not passed then call this method, this method is always used with input as false
*/
public DataValidatorBuilder trueOrFalseRequired1(final boolean trueOfFalseFieldProvided) {
if (!trueOfFalseFieldProvided && !this.ignoreNullValue) {
public DataValidatorBuilder trueOrFalseRequired(final Object trueOfFalseField) {

if (trueOfFalseField != null && !trueOfFalseField.toString().equalsIgnoreCase("true")
&& !trueOfFalseField.toString().equalsIgnoreCase("false")) {
final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".")
.append(this.parameter).append(".must.be.true.or.false");
final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter `").append(this.parameter)
Expand All @@ -191,22 +186,6 @@ public DataValidatorBuilder trueOrFalseRequired1(final boolean trueOfFalseFieldP
defaultEnglishMessage.toString(), this.parameter);
this.dataValidationErrors.add(error);
}
return this;
}

public DataValidatorBuilder trueOrFalseRequired(final Object trueOfFalseField) {

if (trueOfFalseField != null) {
if (!trueOfFalseField.toString().equalsIgnoreCase("true") && !trueOfFalseField.toString().equalsIgnoreCase("false")) {
final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".")
.append(this.parameter).append(".must.be.true.or.false");
final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter `").append(this.parameter)
.append("` must be set as true or false.");
final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(),
defaultEnglishMessage.toString(), this.parameter);
this.dataValidationErrors.add(error);
}
}

return this;
}
Expand Down Expand Up @@ -320,7 +299,7 @@ public DataValidatorBuilder isOneOfTheseValues(final Object... values) {
final List<Object> rawValuesList = Arrays.asList(values);

if (this.value == null || !rawValuesList.contains(this.value)) {
final List<String> valuesList = Arrays.stream(values).map(Object::toString).collect(toList());
final List<String> valuesList = Arrays.stream(values).map(Object::toString).toList();
final String valuesListStr = String.join(", ", valuesList);
final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".")
.append(this.parameter).append(".is.not.one.of.expected.enumerations");
Expand Down Expand Up @@ -349,7 +328,7 @@ public DataValidatorBuilder isOneOfTheseStringValues(final Object... values) {
final List<Object> rawValuesList = Arrays.asList(values);

if (this.value == null || !rawValuesList.contains(this.value.toString().toLowerCase())) {
final List<String> valuesList = Arrays.stream(values).map(Object::toString).collect(toList());
final List<String> valuesList = Arrays.stream(values).map(Object::toString).toList();
final String valuesListStr = String.join(", ", valuesList);
final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".")
.append(this.parameter).append(".is.not.one.of.expected.enumerations");
Expand Down Expand Up @@ -397,7 +376,7 @@ public DataValidatorBuilder isNotOneOfTheseValues(final Object... values) {
final List<Object> rawValuesList = Arrays.asList(values);

if (rawValuesList.contains(this.value)) {
final List<String> valuesList = Arrays.stream(values).map(Object::toString).collect(toList());
final List<String> valuesList = Arrays.stream(values).map(Object::toString).toList();
final String valuesListStr = String.join(", ", valuesList);
final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".")
.append(this.parameter).append(".is.one.of.unwanted.enumerations");
Expand Down Expand Up @@ -879,17 +858,15 @@ public DataValidatorBuilder notGreaterThanMax(final BigDecimal max) {
}

public DataValidatorBuilder compareMinAndMaxOfTwoBigDecmimalNos(final BigDecimal min, final BigDecimal max) {
if (min != null && max != null) {
if (max.compareTo(min) < 0) {
final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".")
.append(this.parameter).append(".is.not.within.expected.range");
final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(" min number ").append(min)
.append(" should less than max number ").append(max).append(".");
final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(),
defaultEnglishMessage.toString(), this.parameter, min, max);
this.dataValidationErrors.add(error);
return this;
}
if (min != null && max != null && max.compareTo(min) < 0) {
final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".")
.append(this.parameter).append(".is.not.within.expected.range");
final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(" min number ").append(min)
.append(" should less than max number ").append(max).append(".");
final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(),
defaultEnglishMessage.toString(), this.parameter, min, max);
this.dataValidationErrors.add(error);
return this;
}
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ public class DatabasePasswordEncryptor implements PasswordEncryptor {

public static final String DEFAULT_ENCRYPTION = "AES/CBC/PKCS5Padding";

public static final String DEFAULT_MASTER_PASSWORD = "fineract";

private final FineractProperties fineractProperties;

@SuppressWarnings("checkstyle:regexpsinglelinejava")
Expand All @@ -54,7 +52,8 @@ public static void main(String[] args) {
@Override
public String encrypt(String plainPassword) {
String masterPassword = Optional.ofNullable(fineractProperties.getTenant())
.map(FineractProperties.FineractTenantProperties::getMasterPassword).orElse(DEFAULT_MASTER_PASSWORD);
.map(FineractProperties.FineractTenantProperties::getMasterPassword)
.orElse(fineractProperties.getDatabase().getDefaultMasterPassword());
String encryption = Optional.ofNullable(fineractProperties.getTenant())
.map(FineractProperties.FineractTenantProperties::getEncryption).orElse(DEFAULT_ENCRYPTION);
return EncryptionUtil.encryptToBase64(encryption, masterPassword, plainPassword);
Expand All @@ -63,7 +62,8 @@ public String encrypt(String plainPassword) {
@Override
public String decrypt(String encryptedPassword) {
String masterPassword = Optional.ofNullable(fineractProperties.getTenant())
.map(FineractProperties.FineractTenantProperties::getMasterPassword).orElse(DEFAULT_MASTER_PASSWORD);
.map(FineractProperties.FineractTenantProperties::getMasterPassword)
.orElse(fineractProperties.getDatabase().getDefaultMasterPassword());
String encryption = Optional.ofNullable(fineractProperties.getTenant())
.map(FineractProperties.FineractTenantProperties::getEncryption).orElse(DEFAULT_ENCRYPTION);
return EncryptionUtil.decryptFromBase64(encryption, masterPassword, encryptedPassword);
Expand All @@ -73,15 +73,15 @@ public String getMasterPasswordHash() {
String masterPassword = Optional.ofNullable(fineractProperties) //
.map(FineractProperties::getTenant) //
.map(FineractProperties.FineractTenantProperties::getMasterPassword) //
.orElse(DEFAULT_MASTER_PASSWORD);
.orElse(fineractProperties.getDatabase().getDefaultMasterPassword());
return BCrypt.hashpw(masterPassword.getBytes(StandardCharsets.UTF_8), BCrypt.gensalt());
}

public boolean isMasterPasswordHashValid(String hashed) {
String masterPassword = Optional.ofNullable(fineractProperties) //
.map(FineractProperties::getTenant) //
.map(FineractProperties.FineractTenantProperties::getMasterPassword) //
.orElse(DEFAULT_MASTER_PASSWORD);
.orElse(fineractProperties.getDatabase().getDefaultMasterPassword());
return BCrypt.checkpw(masterPassword, hashed);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ public static void updateWorkingDayIfRepaymentDateIsNonWorkingDay(final Adjusted
adjustedDateDetailsDTO.setChangedScheduleDate(changedScheduleDate);
}

public static RepaymentRescheduleType getRepaymentRescheduleType(final WorkingDays workingDays, final LocalDate date) {
RepaymentRescheduleType rescheduleType = RepaymentRescheduleType.fromInt(workingDays.getRepaymentReschedulingType());
return rescheduleType;
public static RepaymentRescheduleType getRepaymentRescheduleType(final WorkingDays workingDays) {
return RepaymentRescheduleType.fromInt(workingDays.getRepaymentReschedulingType());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -377,30 +377,16 @@ private CalendarData(final Long id, final Long calendarInstanceId, final Long en
}

public boolean isStartDateBeforeOrEqual(final LocalDate compareDate) {
if (this.startDate != null && compareDate != null) {
if (this.startDate.isBefore(compareDate) || this.startDate.equals(compareDate)) {
return true;
}
}
return false;
return this.startDate != null && compareDate != null
&& (this.startDate.isBefore(compareDate) || this.startDate.equals(compareDate));
}

public boolean isEndDateAfterOrEqual(final LocalDate compareDate) {
if (this.endDate != null && compareDate != null) {
if (this.endDate.isAfter(compareDate) || this.endDate.isEqual(compareDate)) {
return true;
}
}
return false;
return this.endDate != null && compareDate != null && (this.endDate.isAfter(compareDate) || this.endDate.isEqual(compareDate));
}

public boolean isBetweenStartAndEndDate(final LocalDate compareDate) {
if (isStartDateBeforeOrEqual(compareDate)) {
if (this.endDate == null || isEndDateAfterOrEqual(compareDate)) {
return true;
}
}
return false;
return isStartDateBeforeOrEqual(compareDate) && (this.endDate == null || isEndDateAfterOrEqual(compareDate));
}

public boolean isValidRecurringDate(final LocalDate compareDate, final Boolean isSkipMeetingOnFirstDay, final Integer numberOfDays) {
Expand Down
Loading

0 comments on commit d6c10e8

Please sign in to comment.