Skip to content

Commit

Permalink
feat: Portfolio-initialization share validity while loading with refl…
Browse files Browse the repository at this point in the history
…ection
  • Loading branch information
pawelsa committed May 14, 2026
1 parent 72fce32 commit 9392e55
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ public boolean removeShare(Share share) {
return shares.remove(share);
}

// TODO: JavaDocs, Junit
public void removeShares() {
shares.clear();
}

/**
* Getter for ArrayList shares.
*
Expand Down
18 changes: 18 additions & 0 deletions src/main/java/edu/ntnu/idi/idatt/storage/SessionManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
import com.google.gson.reflect.TypeToken;

import edu.ntnu.idi.idatt.model.Exchange;
import edu.ntnu.idi.idatt.model.market.Stock;
import edu.ntnu.idi.idatt.model.player.Player;
import edu.ntnu.idi.idatt.model.portfolio.Portfolio;
import edu.ntnu.idi.idatt.model.portfolio.Share;
import edu.ntnu.idi.idatt.model.transaction.Transaction;
import edu.ntnu.idi.idatt.service.transaction.TransactionCalculator;
import edu.ntnu.idi.idatt.session.UserSession;
Expand Down Expand Up @@ -104,6 +107,21 @@ public static boolean loadSession(String playerName) {
if (session.getPlayer().getName().equals(playerName)) {
UserSession.getInstance().setPlayer(session.getPlayer());
UserSession.getInstance().setExchange(session.getExchange());

// Reseed portfolio based on exchange's stock instances.
// This has to be done due to Gson loading via reflection.
Portfolio portfolio = UserSession.getInstance().getPlayer().getPortfolio();
ArrayList<Share> validatedShares = new ArrayList<>();

for (Share oldShare : portfolio.getShares()) { // Create new instances
Stock stock = UserSession.getInstance().getExchange().getStock(oldShare.getStock().getSymbol());
Share newShare = new Share(stock, oldShare.getQuantity(), oldShare.getPurchasePrice());
validatedShares.add(newShare);
}

portfolio.removeShares(); // Remove all old
validatedShares.forEach(share -> portfolio.addShare(share)); // Add new

return true;
}
}
Expand Down

0 comments on commit 9392e55

Please sign in to comment.