Skip to content

Commit

Permalink
Feat: Renamed File Parser to File Manager, and File Converter to File…
Browse files Browse the repository at this point in the history
… Parser
  • Loading branch information
tommyah committed May 25, 2026
1 parent 006979a commit 5fe81c2
Show file tree
Hide file tree
Showing 8 changed files with 353 additions and 353 deletions.
6 changes: 3 additions & 3 deletions src/main/java/edu/ntnu/idi/idatt2003/g40/mappe/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import edu.ntnu.idi.idatt2003.g40.mappe.engine.Exchange;
import edu.ntnu.idi.idatt2003.g40.mappe.model.Player;
import edu.ntnu.idi.idatt2003.g40.mappe.model.Stock;
import edu.ntnu.idi.idatt2003.g40.mappe.service.FileConverter;
import edu.ntnu.idi.idatt2003.g40.mappe.service.FileParser;
import edu.ntnu.idi.idatt2003.g40.mappe.service.FileManager;
import edu.ntnu.idi.idatt2003.g40.mappe.service.SaveGameService;
import edu.ntnu.idi.idatt2003.g40.mappe.service.event.EventManager;
import edu.ntnu.idi.idatt2003.g40.mappe.utils.ConfigValues;
Expand Down Expand Up @@ -86,9 +86,9 @@ public void start(final Stage stage) throws Exception {
ViewManager viewManager = new ViewManager(stage, eventManager);

List<Stock> stocksInFile;
FileParser parser1 = new FileParser("/sp500.csv");
FileManager parser1 = new FileManager("/sp500.csv");

FileConverter converter1 = new FileConverter();
FileParser converter1 = new FileParser();
stocksInFile = converter1.getStocksFromStrings(parser1.readFile());

Exchange exchange = new Exchange("Exchange", stocksInFile);
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
package edu.ntnu.idi.idatt2003.g40.mappe.service;

import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.function.Predicate;

/**
* Class used to parse (filter) valid stocks from a .txt file.
*
* <p style ="font-weight: bold;">Responsibilities:</p>
* <ul>
* <li>Read file and return a filtered list of string elements,
* where each element represents a valid stock line.</li>
*
* <li>Write a list of string representations of stock objects
* to file, each stock separated by a line.</li>
* </ul>
*
* <p>Used with {@link FileParser}</p>
*
* @see FileParser
* @author tohja
* @version 1.0.0
* */
public class FileManager {

/** The path name this parser is using.*/
private final String pathName;

/**
* Rule set for validating lines and strings.
*
* <p>Uses predicates.</p>
* */
private enum ParserRuleSet {

/**
* Rule for whether string is empty or not.
* */
NOT_EMPTY(s -> !s.trim().isEmpty()),

/**
* Rule for if string is comment or not.
* */
NOT_COMMENT(s -> !s.startsWith("#")),

/**
* Rule for if line is in valid format.
* */
VALID_FORMAT(NOT_EMPTY.rule.and(NOT_COMMENT.rule)),

/**
* Rule for if string is considered a valid company symbol.
* */
VALID_CODE(s -> s.matches("[A-Z]{4}")),

/**
* Rule for if string is a valid company name.
* */
VALID_NAME(s -> s.matches(".*")),

/**
* Rule for if string can be parsed to a {@link BigDecimal} object.
* */
CAN_PARSE_TO_BIG_DECIMAL(s -> {
try {
new BigDecimal(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}),

/**
* Rule for if string is in a valid price format.
* */
VALID_PRICE_FORMAT(s -> s.matches("[^a-zA-Z]+")),

/**
* Rule for if string is a valid price.
* */
VALID_PRICE(VALID_PRICE_FORMAT.rule.and(CAN_PARSE_TO_BIG_DECIMAL.rule));

/**
* The constants' rules as predicates with input of type string.
* */
private final Predicate<String> rule;

ParserRuleSet(final Predicate<String> rule) {
this.rule = rule;
}
}

/**
* Constructor.
*
* @param pathName the file path name to read.
* */
public FileManager(final String pathName) {
this.pathName = pathName;
}

/**
* Reads the file and returns a list element of all valid stocks as strings.
*
* <p>Uses {@link BufferedReader} for opening a file stream. </p>
*
* @return {@link List<String>} object of all valid stock strings in file.
*
* @throws IOException if path cannot be read.
*
* @see Path
* */

public List<String> readFile() throws IOException {
try (InputStream inputStream = getClass().getResourceAsStream(pathName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {

List<String> allLines = bufferedReader.readAllLines();
List<String> readableLines =
allLines.stream()
.filter(ParserRuleSet.VALID_FORMAT.rule).toList();

// Valid lines (following the correct regular expressions)
return readableLines.stream().filter(s -> {
String[] parts = s.trim().split(",");

if (parts.length != 3) {
return false;
}

boolean validCode = ParserRuleSet
.VALID_CODE.rule.test(parts[0].trim());

boolean validName = ParserRuleSet
.VALID_NAME.rule.test(parts[1].trim());

boolean validPrice = ParserRuleSet
.VALID_PRICE.rule.test(parts[2].trim());

return validCode && validName && validPrice;
}).toList();

} catch (IOException e) {
throw new IOException("File parser could not parse file!");
}
}

/**
* Writes a given lists of stocks to the file.
*
* <p>Uses {@link BufferedWriter}.</p>
*
* @param stringList list of strings representing stocks in the format
* SYMBOL, NAME, PRICE
*
* @throws IOException if writing process throws error.
* */
public void writeStocksToFile(final List<String> stringList)
throws IllegalArgumentException, IOException {
if (stringList == null || stringList.isEmpty()) {
throw new IllegalArgumentException("Empty or null list of stocks!");
} else {
Path path = Paths.get(pathName);

try (BufferedWriter writer = Files.newBufferedWriter(path,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND)) {

writer.newLine();

for (String line : stringList) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
throw new IOException("Error during buffered write", e);
}
}
}
}
Loading

0 comments on commit 5fe81c2

Please sign in to comment.