Skip to content

Commit

Permalink
fix remaining "assignment" checker framework warn
Browse files Browse the repository at this point in the history
  • Loading branch information
vananiev committed Nov 2, 2024
1 parent c4c2856 commit 98606ae
Show file tree
Hide file tree
Showing 21 changed files with 65 additions and 45 deletions.
2 changes: 1 addition & 1 deletion src/main/java/ru/investbook/report/DerivativeEvents.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class DerivativeEvents {
@Builder
public static class DerivativeDailyEvents {
private final @Nullable SecurityEventCashFlow dailyProfit;
private final @Nullable LinkedHashMap<Transaction, Map<CashFlowType, TransactionCashFlow>> dailyTransactions;
private final LinkedHashMap<Transaction, Map<CashFlowType, TransactionCashFlow>> dailyTransactions;
private final BigDecimal totalProfit;
private final int position;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ private Optional<org.decampo.xirr.Transaction> castToXirrTransaction(SecurityQuo
}

private Optional<BigDecimal> getTransactionValue(Transaction t, String toCurrency) {
BigDecimal value = null;
@Nullable BigDecimal value = null;
if (t.getId() != null) { // bond redemption, accounted by other way, skipping
value = transactionCashFlowRepository.findByTransactionId(t.getId())
.stream()
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/ru/investbook/report/PaidInterest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spacious_team.broker.pojo.CashFlowType;
import org.spacious_team.broker.pojo.SecurityEventCashFlow;
import org.spacious_team.broker.pojo.Transaction;
Expand Down Expand Up @@ -49,7 +50,7 @@ Map<Position, List<SecurityEventCashFlow>> get(CashFlowType type) {
}

public List<SecurityEventCashFlow> get(CashFlowType payType, Position position) {
List<SecurityEventCashFlow> value = this.get(payType).get(position);
@Nullable List<SecurityEventCashFlow> value = this.get(payType).get(position);
return (value != null) ? value : Collections.emptyList();
}

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/ru/investbook/report/PaidInterestFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spacious_team.broker.pojo.CashFlowType;
import org.spacious_team.broker.pojo.Portfolio;
import org.spacious_team.broker.pojo.Security;
Expand Down Expand Up @@ -125,7 +126,7 @@ private Instant getBookClosureDate(Deque<PositionHistory> positionHistories, Sec
Iterator<PositionHistory> it = positionHistories.descendingIterator();
// дата перечисления дивидендов/купонов Эмитентом (дата фиксации реестра акционеров)
// с точностью до временного интервала между 2-мя соседними транзакции
Instant bookClosureDate = null;
@Nullable Instant bookClosureDate = null;
while (it.hasNext()) {
PositionHistory positionHistory = it.next();
Instant pastInstant = positionHistory.getInstant();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spacious_team.broker.pojo.CashFlowType;
import org.spacious_team.broker.pojo.EventCashFlow;
import org.spacious_team.broker.pojo.Portfolio;
Expand Down Expand Up @@ -100,21 +101,21 @@ private void appendCurrencyInfo(Portfolio portfolio, Table table) {

public void appendCashBalance(Portfolio portfolio, Table table) {
Map<String, BigDecimal> currencyToValues = getCashBalances(portfolio);
Table.Record rubCashBalanceRecord = null;
Table.@Nullable Record rubCashBalanceRecord = null;
for (Table.Record record : table) {
String currency = Optional.ofNullable((String) record.get(CURRENCY_NAME))
@Nullable String currency = Optional.ofNullable((String) record.get(CURRENCY_NAME))
.map(String::toUpperCase)
.orElse(null);
if (currency != null) {
BigDecimal value = currencyToValues.get(currency);
@Nullable BigDecimal value = currencyToValues.get(currency);
record.put(CASH_BALANCE, value);
} else {
rubCashBalanceRecord = record;
break;
}
}
// print RUB after all already printed currencies
BigDecimal rubCash = currencyToValues.get("RUB");
@Nullable BigDecimal rubCash = currencyToValues.get("RUB");
if (rubCash != null) {
if (rubCashBalanceRecord == null) {
rubCashBalanceRecord = new Table.Record();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.decampo.xirr.NewtonRaphson;
import org.decampo.xirr.Transaction;
import org.decampo.xirr.Xirr;
Expand Down Expand Up @@ -123,14 +124,14 @@ private double getXirrProfitInPercent(Table table, BigDecimal liquidationValueRu
}

private Optional<Transaction> castRecordToXirrTransaction(Table.Record record) {
Object cash = record.get(CASH);
Object currency = record.get(CURRENCY);
Double cashInRub = null;
@Nullable Object cash = record.get(CASH);
@Nullable Object currency = record.get(CURRENCY);
@Nullable Double cashInRub = null;
if (cash instanceof Number n && currency instanceof String cur) {
cashInRub = n.doubleValue() * foreignExchangeRateService.getExchangeRateToRub(cur).doubleValue();
}
Object date = record.get(DATE);
Transaction transaction = (cashInRub != null && date instanceof Instant instant) ?
@Nullable Object date = record.get(DATE);
@Nullable Transaction transaction = (cashInRub != null && date instanceof Instant instant) ?
new Transaction(cashInRub, LocalDate.ofInstant(instant, ZoneId.systemDefault())) :
null;
return Optional.ofNullable(transaction);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package ru.investbook.report.excel;

import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spacious_team.broker.pojo.CashFlowType;
import org.spacious_team.broker.pojo.Portfolio;
import org.spacious_team.broker.pojo.Security;
Expand Down Expand Up @@ -94,6 +95,7 @@ private Table getContractProfit(Security contract, DerivativeEvents derivativeEv
Table.Record record = new Table.Record();
contractProfit.add(record);
LinkedHashMap<Transaction, Map<CashFlowType, TransactionCashFlow>> dailyTransactions = dailyEvents.getDailyTransactions();
//noinspection ConstantValue
if (dailyTransactions != null) {
boolean isFirstRowOfDay = true;
for (Map.Entry<Transaction, Map<CashFlowType, TransactionCashFlow>> e : dailyTransactions.entrySet()) {
Expand Down Expand Up @@ -126,7 +128,7 @@ record = new Table.Record();
isFirstRowOfDay = false;
}
}
SecurityEventCashFlow dailyProfit = dailyEvents.getDailyProfit();
@Nullable SecurityEventCashFlow dailyProfit = dailyEvents.getDailyProfit();
if (dailyProfit != null) {
record.put(DATE, dailyProfit.getTimestamp());
record.put(DERIVATIVE_PROFIT_DAY, dailyProfit.getValue());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public <T extends Enum<T> & TableHeader> void createSheet(Portfolio portfolio,
Row row = sheet.createRow(++rowNum);
TableHeader[] tableHeader = requireNonNull(headerType.getEnumConstants());
for (TableHeader header : tableHeader) {
Object value = tableRow.get(header);
@Nullable Object value = tableRow.get(header);
if (value == null) {
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,8 @@ private Table.Record getClosedPositionProfit(ClosedPosition position) {
Transaction transaction = position.getCloseTransaction();
double multiplier = Math.abs(1d * position.getCount() / transaction.getCount());
row.put(CLOSE_DATE, transaction.getTimestamp());
BigDecimal closeAmount;
@Nullable BigDecimal closeAmount;
if (position.getClosingEvent() == CashFlowType.PRICE) {
//noinspection DataFlowIssue
closeAmount = getTransactionCashFlow(transaction, CashFlowType.PRICE, multiplier);
} else {
throw new IllegalArgumentException("ЦБ " + transaction.getSecurity() +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spacious_team.broker.pojo.CashFlowType;
import org.spacious_team.broker.pojo.EventCashFlow;
import org.spacious_team.broker.pojo.Portfolio;
Expand Down Expand Up @@ -86,7 +87,7 @@ private Table getTable(List<EventCashFlow> cashFlows) {
table.add(new Table.Record());
Table.Record monthTotalRecord = new Table.Record();
table.add(monthTotalRecord);
Month month = null;
@Nullable Month month = null;
int sumRowCount = 0;
for (EventCashFlow cash : cashFlows) {
Instant timestamp = cash.getTimestamp();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spacious_team.broker.pojo.EventCashFlow;
import org.spacious_team.broker.pojo.Portfolio;
import org.spacious_team.broker.pojo.PortfolioCash;
Expand Down Expand Up @@ -174,12 +175,12 @@ private void addAssetsColumns(LinkedHashMap<Instant, BigDecimal> totalAssets, Ta
private void addAssetsGrowthColumn(Table table) {
try {
double usdToRubExchangeRate = foreignExchangeRateService.getExchangeRateToRub("USD").doubleValue();
Double divider = null;
@Nullable Double divider = null;
double investmentUsd = 0;
Double prevAssetsGrownValue = null;
@Nullable Double prevAssetsGrownValue = null;
for (Table.Record record : table) {
investmentUsd += getInvestmentUsd(record, usdToRubExchangeRate);
Number assetsRub = (Number) record.get(ASSETS_RUB);
@Nullable Number assetsRub = (Number) record.get(ASSETS_RUB);
if (assetsRub != null) {
double assetsUsd = assetsRub.doubleValue() / usdToRubExchangeRate;
divider = updateDivider(divider, assetsUsd, investmentUsd, prevAssetsGrownValue);
Expand All @@ -196,7 +197,7 @@ private void addAssetsGrowthColumn(Table table) {
}

private double getInvestmentUsd(Table.Record record, double usdToRubExchangeRate) {
BigDecimal investment = (BigDecimal) record.get(INVESTMENT_AMOUNT);
@Nullable BigDecimal investment = (BigDecimal) record.get(INVESTMENT_AMOUNT);
if (investment != null) {
String fromCurrency = record.get(INVESTMENT_CURRENCY).toString();
if (Objects.equals(fromCurrency, "RUB")) {
Expand All @@ -211,7 +212,7 @@ private double getInvestmentUsd(Table.Record record, double usdToRubExchangeRate
return 0;
}

private Double updateDivider(Double divider, double assetsUsd, double investmentUsd, Double prevAssetsGrowth) {
private @Nullable Double updateDivider(@Nullable Double divider, double assetsUsd, double investmentUsd, @Nullable Double prevAssetsGrowth) {
if (divider == null) {
if (prevAssetsGrowth == null) {
// начинаем график роста активов с нулевой отметки
Expand All @@ -232,8 +233,8 @@ private Double updateDivider(Double divider, double assetsUsd, double investment
private static void addSp500GrowthColumn(Map<LocalDate, BigDecimal> sp500, Table table) {
boolean isSp500ValueKnown = false;
for (Table.Record record : table) {
LocalDate date = (LocalDate) record.get(DATE);
BigDecimal value = sp500.get(date);
@Nullable LocalDate date = (LocalDate) record.get(DATE);
@Nullable BigDecimal value = sp500.get(date);
if (value != null) {
isSp500ValueKnown = true;
record.put(SP500, value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ private Table getTable(List<SecurityEventCashFlow> cashFlows) {
table.add(new Table.Record());
Table.Record monthTotalRecord = new Table.Record();
table.add(monthTotalRecord);
Month month = null;
@Nullable Month month = null;
int sumRowCount = 0;
for (SecurityEventCashFlow cash : cashFlows) {
Instant timestamp = cash.getTimestamp();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

package ru.investbook.report.excel;

import org.checkerframework.checker.nullness.qual.Nullable;
import ru.investbook.report.Table;

import java.math.BigDecimal;
Expand Down Expand Up @@ -75,7 +76,7 @@ private static boolean isDerivativeCurrencyPairOrCashBalance(Table.Record record
}

private static boolean isDerivativeOrCurrencyPair(Table.Record record) {
Object type = record.get(TYPE);
@Nullable Object type = record.get(TYPE);
return Objects.equals(type, DERIVATIVE.getDescription()) ||
Objects.equals(type, CURRENCY_PAIR.getDescription());
}
Expand Down
11 changes: 7 additions & 4 deletions src/main/java/ru/investbook/report/html/HtmlView.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import java.io.OutputStream;
import java.util.concurrent.ExecutionException;

import static java.util.Objects.requireNonNull;
import static ru.investbook.report.html.ExcelFormulaEvaluatorHelper.evaluateFormulaCells;

@Component
Expand Down Expand Up @@ -101,8 +102,9 @@ private void addCssStyle(Document htmlDocument) {
}

private void addReportFileDownloadLink(Document htmlDocument) {
Node body = htmlDocument.getFirstChild() // html
.getLastChild(); // body
Node body = requireNonNull(
htmlDocument.getFirstChild() // html
.getLastChild()); // body

Element div = htmlDocument.createElement("div");
div.setAttribute("style", "float: right");
Expand All @@ -124,8 +126,9 @@ private void addReportFileDownloadLink(Document htmlDocument) {
}

private void addHomeLink(Document htmlDocument) {
Node body = htmlDocument.getFirstChild() // html
.getLastChild(); // body
Node body = requireNonNull(
htmlDocument.getFirstChild() // html
.getLastChild()); // body

Element doc = htmlDocument.createElement("a");
doc.setTextContent("[Описание таблиц]");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spacious_team.broker.pojo.PortfolioCash;
import org.spacious_team.broker.pojo.PortfolioPropertyType;
import org.spacious_team.broker.pojo.SecurityType;
Expand Down Expand Up @@ -134,7 +135,7 @@ private Optional<BigDecimal> getTotalAssetsByCurrentOrLastTransactionQuoteEstima
try {
long t0 = nanoTime();
FifoPositionsFilter filter = FifoPositionsFilter.of(portfolio);
BigDecimal assetsInRub = securityRepository.findByTypeIn(stockBondAndAssetTypes)
@Nullable BigDecimal assetsInRub = securityRepository.findByTypeIn(stockBondAndAssetTypes)
.stream()
.map(securityConverter::fromEntity)
.map(security -> investmentProportionService
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,10 @@ private BigDecimal getStockOrBondPurchaseCost(FifoPositions positions, String to
.flatMap(Optional::stream)
.reduce(BigDecimal.ZERO, BigDecimal::add); // если ценная бумага не вводилась на счет, а была куплена (есть цена покупки)
for (ClosedPosition closedPosition : positions.getClosedPositions()) {
BigDecimal openAmount = getTransactionValue(closedPosition.getOpenTransaction(), CashFlowType.PRICE, toCurrency)
@Nullable BigDecimal openAmount = getTransactionValue(closedPosition.getOpenTransaction(), CashFlowType.PRICE, toCurrency)
.map(value -> getOpenAmount(value, closedPosition))
.orElse(null);
BigDecimal closeAmount = getTransactionValue(closedPosition.getCloseTransaction(), CashFlowType.PRICE, toCurrency)
@Nullable BigDecimal closeAmount = getTransactionValue(closedPosition.getCloseTransaction(), CashFlowType.PRICE, toCurrency)
.map(value -> getClosedAmount(value, closedPosition))
.orElse(null);
if (openAmount != null && closeAmount != null) {
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/ru/investbook/service/Sp500Service.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spacious_team.table_wrapper.api.PatternTableColumn;
import org.spacious_team.table_wrapper.api.TableColumn;
import org.spacious_team.table_wrapper.api.TableHeaderColumn;
Expand Down Expand Up @@ -61,15 +62,15 @@ public class Sp500Service {
public void update() {
try {
long t0 = System.nanoTime();
Resource resource = restTemplate.getForObject(uri, Resource.class);
@Nullable Resource resource = restTemplate.getForObject(uri, Resource.class);
updateBy(resource);
log.info("Индекс S&P 500 обновлен за {}", Duration.ofNanos(System.nanoTime() - t0));
} catch (Exception e) {
throw new RuntimeException("Не смог обновить значения индекса S&P 500", e);
}
}

private void updateBy(Resource resource) throws IOException {
private void updateBy(@Nullable Resource resource) throws IOException {
Objects.requireNonNull(resource, () -> "Не удалось скачать S&P 500 с адреса " + uri);
Workbook book = new HSSFWorkbook(resource.getInputStream());
new ExcelSheet(book.getSheetAt(0))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spacious_team.broker.pojo.ForeignExchangeRate;
import org.spacious_team.table_wrapper.api.PatternTableColumn;
import org.spacious_team.table_wrapper.api.TableColumn;
Expand Down Expand Up @@ -60,7 +61,7 @@ public CbrForeignExchangeRateServiceExcelImpl(ForeignExchangeRateRepository fore
@SneakyThrows
@Override
protected void updateCurrencyRate(String currencyPair, String currencyId, LocalDate fromDate) {
Resource resource = restTemplate.getForObject(
@Nullable Resource resource = restTemplate.getForObject(
uri,
Resource.class,
Map.of("currency", currencyId,
Expand All @@ -69,12 +70,13 @@ protected void updateCurrencyRate(String currencyPair, String currencyId, LocalD
updateBy(resource, currencyPair);
}

private void updateBy(Resource resource, String currencyPair) throws IOException {
private void updateBy(@Nullable Resource resource, String currencyPair) throws IOException {
Objects.requireNonNull(resource, () -> "Не удалось скачать курсы валют");
Workbook book = new XSSFWorkbook(resource.getInputStream());
new ExcelSheet(book.getSheetAt(0))
.createNameless("data", TableHeader.class)
.stream()
.filter(Objects::nonNull)
.map(row -> getRate(row, currencyPair))
.forEach(this::save);
}
Expand Down
Loading

0 comments on commit 98606ae

Please sign in to comment.