Skip to content

Commit

Permalink
[MODFIN - 232] - Loggin improvement (#230)
Browse files Browse the repository at this point in the history
* [MODFIN-232] - Logging improvement
  • Loading branch information
azizbekxm authored Feb 5, 2024
1 parent 2ea60e7 commit a1db0b5
Show file tree
Hide file tree
Showing 26 changed files with 235 additions and 123 deletions.
7 changes: 4 additions & 3 deletions src/main/java/org/folio/rest/core/RestClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

public class RestClient {

private static final Logger log = LogManager.getLogger(RestClient.class);
private static final Logger log = LogManager.getLogger();
private static final ErrorConverter ERROR_CONVERTER = ErrorConverter.createFullBody(
result -> {
String errorResponse = result.response().bodyAsString();
Expand Down Expand Up @@ -82,7 +82,7 @@ protected MultiMap convertToCaseInsensitiveMap(Map<String, String> okapiHeaders)
.add("Accept", APPLICATION_JSON + ", " + TEXT_PLAIN);
}

public <T> Future<Void> put(String endpoint, T dataObject, RequestContext requestContext) {
public <T> Future<Void> put(String endpoint, T dataObject, RequestContext requestContext) {
log.info(REQUEST_MESSAGE_LOG_INFO, HttpMethod.PUT, endpoint);

var recordData = JsonObject.mapFrom(dataObject);
Expand Down Expand Up @@ -115,7 +115,7 @@ public Future<Void> delete(String endpointById, boolean skipError404, RequestCon
return promise.future();
}

private <T>void handleGetMethodErrorResponse(Promise<T> promise, Throwable t, boolean skipError404) {
private <T> void handleGetMethodErrorResponse(Promise<T> promise, Throwable t, boolean skipError404) {
if (skipError404 && t instanceof HttpException httpException && httpException.getCode() == 404) {
log.warn(t);
promise.complete();
Expand Down Expand Up @@ -177,6 +177,7 @@ protected WebClient getVertxWebClient(Context context) {

return WebClientFactory.getWebClient(context.owner(), options);
}

protected String buildAbsEndpoint(MultiMap okapiHeaders, String endpoint) {
var okapiURL = okapiHeaders.get(OKAPI_URL);
return okapiURL + endpoint;
Expand Down
28 changes: 4 additions & 24 deletions src/main/java/org/folio/rest/core/models/RequestEntry.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@
import java.util.Map;
import java.util.stream.Collectors;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.uri.UriTemplate;

@Setter
@Getter
public class RequestEntry {

private String baseEndpoint;
Expand Down Expand Up @@ -52,30 +56,6 @@ public RequestEntry withOffset(Integer offset) {
return this;
}

public String getBaseEndpoint() {
return baseEndpoint;
}

public void setBaseEndpoint(String baseEndpoint) {
this.baseEndpoint = baseEndpoint;
}

public Map<String, String> getPathParams() {
return pathParams;
}

public void setPathParams(Map<String, String> pathParams) {
this.pathParams = pathParams;
}

public Map<String, Object> getQueryParams() {
return queryParams;
}

public void setQueryParams(Map<String, Object> queryParams) {
this.queryParams = queryParams;
}

public String buildEndpoint() {
UriTemplate uriTemplate = new UriTemplate(baseEndpoint);
String endpoint = uriTemplate.createURI(pathParams);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/folio/rest/helper/AbstractHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

public abstract class AbstractHelper {

protected final Logger logger = LogManager.getLogger(this.getClass());
protected static final Logger log = LogManager.getLogger();
protected final Context ctx;
protected final Map<String, String> okapiHeaders;
private final Errors processingErrors = new Errors();
Expand Down Expand Up @@ -55,7 +55,7 @@ public void addProcessingError(Error error) {
}

protected int handleProcessingError(Throwable throwable) {
logger.error("Exception encountered", throwable);
log.error("Exception encountered", throwable);
if (getErrors().isEmpty()) {
final Errors errors = convertToErrors(throwable);
addProcessingError(errors);
Expand Down
17 changes: 13 additions & 4 deletions src/main/java/org/folio/rest/helper/ExchangeHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,45 @@
import javax.money.convert.MonetaryConversions;

import io.vertx.core.Context;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.folio.rest.exception.HttpException;
import org.folio.rest.jaxrs.model.ExchangeRate;
import org.javamoney.moneta.Money;

public class ExchangeHelper extends AbstractHelper {

private static final Logger log = LogManager.getLogger();

public ExchangeHelper(Context ctx) {
super(ctx);
}

public ExchangeRate getExchangeRate(String from, String to) {
log.debug("getExchangeRate:: Getting exchange rate from={}, to={}", from, to);
try {
double exchangeRate = MonetaryConversions.getExchangeRateProvider(IDENTITY, ECB)
.getExchangeRate(from, to)
.getFactor()
.doubleValue();

log.debug("getExchangeRate:: Fetched exchange rate={}", exchangeRate);
return new ExchangeRate().withFrom(from)
.withTo(to)
.withExchangeRate(exchangeRate);
} catch (CurrencyConversionException e) {
log.error("Failed to converse currency", e);
throw new HttpException(404, e.getMessage());
} catch (Exception e) {
log.error("Error while retrieving exchange rate", e);
throw new HttpException(400, e.getMessage());
}
}

public Double calculateExchange(String sourceCurrency, String targetCurrency, Number amount, Number customRate) {
var initialAmount = Money.of(amount, sourceCurrency);
var rate = customRate == null ? getExchangeRate(sourceCurrency, targetCurrency).getExchangeRate() : customRate;
public Double calculateExchange(String from, String to, Number amount, Number customRate) {
log.debug("calculateExchange:: Calculating exchange sourceCurrency from={}, to={}, amount={} and customRate={}", from, to, amount, customRate);
var initialAmount = Money.of(amount, from);
var rate = customRate == null ? getExchangeRate(from, to).getExchangeRate() : customRate;
log.debug("calculateExchange:: rate is {}", rate);

return initialAmount.multiply(rate)
.with(Monetary.getDefaultRounding())
Expand Down
19 changes: 18 additions & 1 deletion src/main/java/org/folio/rest/helper/FundsHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.folio.okapi.common.GenericCompositeFuture;
import org.folio.rest.core.RestClient;
import org.folio.rest.core.models.RequestContext;
Expand All @@ -43,6 +45,8 @@

public class FundsHelper extends AbstractHelper {

private static final Logger log = LogManager.getLogger();

@Autowired
private RestClient restClient;
@Autowired
Expand Down Expand Up @@ -86,17 +90,20 @@ public Future<CompositeFund> createFund(CompositeFund compositeFund, RequestCont
return ledgerDetailsService.getCurrentFiscalYear(compositeFund.getFund().getLedgerId(), new RequestContext(ctx, okapiHeaders))
.compose(fiscalYear -> {
if (Objects.isNull(fiscalYear)) {
log.error("createFund:: fiscalYear is not found for compositeFund with ledgerId={}", compositeFund.getFund().getLedgerId());
throw new HttpException(422, FISCAL_YEARS_NOT_FOUND);
}
return fundService.createFund(compositeFund.getFund(), requestContext)
.map(newFund -> {
compositeFund.getFund().withId(newFund.getId());
log.info("createFund:: fund with id '{}' is being created", compositeFund.getFund().getId());
return null;
})
.compose(compFund -> assignFundToGroups(compositeFund, fiscalYear.getId()));
})
.map(aVoid -> compositeFund);
}
log.info("createFund:: GroupIds is empty in compositeFund with ledgeId '{}'", compositeFund.getFund().getLedgerId());
return fundService.createFund(compositeFund.getFund(), requestContext)
.map(compositeFund::withFund);
}
Expand Down Expand Up @@ -176,25 +183,30 @@ private List<String> groupFundFiscalYearIdsForDeletion(List<GroupFundFiscalYear>
}

private Future<Void> createGroupFundFiscalYears(CompositeFund compositeFund, String currentFiscalYearId, List<String> groupIdsForCreation, RequestContext requestContext) {
log.debug("createGroupFundFiscalYears:: Creating group fiscal year for currentFiscalYearId={}", currentFiscalYearId);
if(CollectionUtils.isNotEmpty(groupIdsForCreation)) {
return groupService.getGroups(0, 0, convertIdsToCqlQuery(groupIdsForCreation), requestContext)
.compose(groupsCollection -> {
if(groupsCollection.getTotalRecords() == groupIdsForCreation.size()) {
String query = getBudgetsCollectionQuery(currentFiscalYearId, compositeFund.getFund().getId());
log.info("createGroupFundFiscalYears:: Retrieving budget by using the query={}", query);
return budgetService.getBudgets(query, 0, 1, new RequestContext(ctx, okapiHeaders))
.compose(budgetsCollection -> {
List<Budget> budgets = budgetsCollection.getBudgets();
String budgetId = null;
if(!budgets.isEmpty()) {
budgetId = budgets.get(0).getId();
}
log.info("createGroupFundFiscalYears:: assigning fund to groups with budgetId={}, currentFiscalYearId={}", budgetId, currentFiscalYearId);
return assignFundToGroups(buildGroupFundFiscalYears(compositeFund, budgetId, currentFiscalYearId, groupIdsForCreation));
});
} else {
log.error("createGroupFundFiscalYears:: groupsCollection size={} is not equal with groupsIdsForCreating size={}", groupsCollection.getTotalRecords(), groupIdsForCreation.size());
throw new HttpException(422, GROUP_NOT_FOUND);
}
});
} else {
log.warn("createGroupFundFiscalYears:: groupIdsForCreation is empty for compositeFund '{}'", compositeFund.getFund().getId());
return succeededFuture(null);
}
}
Expand All @@ -219,21 +231,26 @@ public Future<Void> updateFund(CompositeFund compositeFund, RequestContext reque
private Future<Void> updateFundGroups(CompositeFund compositeFund, RequestContext requestContext) {
Fund fund = compositeFund.getFund();
Set<String> groupIds = new HashSet<>(compositeFund.getGroupIds());
log.debug("updateFundGroups:: Updating fund groups for compositeFund with id={}", fund.getId());

return ledgerDetailsService.getCurrentFiscalYear(fund.getLedgerId(), new RequestContext(ctx, okapiHeaders))
.compose(currentFiscalYear-> {
if(Objects.nonNull(currentFiscalYear)) {
String currentFiscalYearId = currentFiscalYear.getId();
log.info("updateFundGroups:: Retrieving group fund fiscal years for fundId={}, currentFiscalYearId={}", fund.getId(), currentFiscalYearId);
return getGroupFundFiscalYearsThatFundBelongs(fund.getId(), currentFiscalYearId)
.compose(groupFundFiscalYearCollection -> {
List<String> groupIdsFromStorage = StreamEx.of(groupFundFiscalYearCollection).map(GroupFundFiscalYear::getGroupId).collect(Collectors.toList());

log.info("updateFundGroups:: Creating group fund fiscal years for new groups for compositeFund '{}'", fund.getId());
return createGroupFundFiscalYears(compositeFund, currentFiscalYearId, getSetDifference(groupIdsFromStorage, groupIds), requestContext)
.compose(vVoid -> deleteGroupFundFiscalYears(groupFundFiscalYearIdsForDeletion(
groupFundFiscalYearCollection, getSetDifference(groupIds, groupIdsFromStorage))));
});
} else if(groupIds.isEmpty()) {
log.warn("updateFundGroups:: GroupIds is empty in compositeFund '{}'", fund.getId());
return succeededFuture(null);
} else {
log.error("updateFundGroups:: No fiscal years found and groups exist for update in compositeFund '{}'", fund.getId());
throw new HttpException(422, FISCAL_YEARS_NOT_FOUND);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.folio.models.BudgetExpenseClassHolder;
import org.folio.okapi.common.GenericCompositeFuture;
import org.folio.rest.core.RestClient;
Expand All @@ -36,7 +38,9 @@

import io.vertx.core.Future;

public class BudgetExpenseClassService{
public class BudgetExpenseClassService {

private static final Logger log = LogManager.getLogger();

private final RestClient restClient;
private final CommonTransactionService transactionService;
Expand All @@ -47,6 +51,7 @@ public BudgetExpenseClassService(RestClient restClient, CommonTransactionService
}

public Future<List<BudgetExpenseClass>> getBudgetExpenseClasses(String budgetId, RequestContext requestContext) {
log.debug("getBudgetExpenseClasses:: Trying to get Budget expense classes by budgetId: {}", budgetId);
String query = String.format("budgetId==%s", budgetId);
var requestEntry = new RequestEntry(resourcesPath(BUDGET_EXPENSE_CLASSES))
.withQuery(query)
Expand Down Expand Up @@ -99,7 +104,9 @@ private BudgetExpenseClassHolder mapBudgetExpenseClassesByOperation(List<BudgetE
}

private Future<Void> deleteBudgetExpenseClasses(List<BudgetExpenseClass> deleteList, SharedBudget budget, RequestContext requestContext) {
log.debug("deleteBudgetExpenseClasses:: Trying to delete budget expense classes with budgetId '{}' and deleteList with size '{}'", budget.getId(), deleteList.size());
if (deleteList.isEmpty()) {
log.info("deleteBudgetExpenseClasses:: deleteList is empty");
return succeededFuture(null);
}
return checkNoTransactionsAssigned(deleteList, budget, requestContext)
Expand All @@ -110,11 +117,14 @@ private Future<Void> deleteBudgetExpenseClasses(List<BudgetExpenseClass> deleteL
}

private Future<Void> checkNoTransactionsAssigned(List<BudgetExpenseClass> deleteList, SharedBudget budget, RequestContext requestContext) {
log.debug("checkNoTransactionsAssigned:: Checking there is no transaction assigned for budget: {} and deleteList with size: {}", budget.getId(), deleteList.size());
return transactionService.retrieveTransactions(deleteList, budget, requestContext)
.map(transactions -> {
if (isNotEmpty(transactions)) {
log.error("checkNoTransactionsAssigned:: There is assigned transaction for budget: '{}'", budget.getId());
throw new HttpException(400, TRANSACTION_IS_PRESENT_BUDGET_EXPENSE_CLASS_DELETE_ERROR);
}
log.info("checkNoTransactionsAssigned:: Transaction is not found for budget: '{}'", budget.getId());
return null;
});
}
Expand All @@ -124,8 +134,8 @@ private Future<Void> updateBudgetExpenseClasses(List<BudgetExpenseClass> updateL
return succeededFuture(null);
}
return GenericCompositeFuture.all(updateList.stream()
.map(budgetExpenseClass -> restClient.put(resourceByIdPath(BUDGET_EXPENSE_CLASSES, budgetExpenseClass.getId()), budgetExpenseClass, requestContext))
.collect(Collectors.toList()))
.map(budgetExpenseClass -> restClient.put(resourceByIdPath(BUDGET_EXPENSE_CLASSES, budgetExpenseClass.getId()), budgetExpenseClass, requestContext))
.collect(Collectors.toList()))
.mapEmpty();
}

Expand Down Expand Up @@ -158,7 +168,7 @@ public Future<List<BudgetExpenseClass>> getBudgetExpenseClasses(List<String> bud
.collect(toList()));
}

public Future<List<BudgetExpenseClass>> getBudgetExpenseClassesByIds(List<String> ids, RequestContext requestContext) {
public Future<List<BudgetExpenseClass>> getBudgetExpenseClassesByIds(List<String> ids, RequestContext requestContext) {
String budgetId = "budgetId";
String query = convertIdsToCqlQuery(ids, budgetId);
var requestEntry = new RequestEntry(resourcesPath(BUDGET_EXPENSE_CLASSES))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public Future<BudgetExpenseClassTotalsCollection> getExpenseClassTotals(String b
return restClient.get(resourceByIdPath(BUDGETS_STORAGE, budgetId), Budget.class, requestContext)
.compose(budget -> expenseClassService.getExpenseClassesByBudgetId(budgetId, requestContext)
.compose(expenseClasses -> transactionService.retrieveTransactions(budget, requestContext)
.map(transactions -> buildBudgetExpenseClassesTotals(expenseClasses, transactions, budget))))
.map(transactions -> buildBudgetExpenseClassesTotals(expenseClasses, transactions, budget))))
.compose(budgetExpenseClassTotalsCollection -> budgetExpenseClassService.getBudgetExpenseClasses(budgetId, requestContext)
.map(budgetExpenseClasses -> updateExpenseClassStatus(budgetExpenseClassTotalsCollection, budgetExpenseClasses)));
}
Expand Down
Loading

0 comments on commit a1db0b5

Please sign in to comment.