diff options
| author | Kostya <mail@sartin.in> | 2026-10-08 16:45:02 +0300 |
|---|---|---|
| committer | Kostya <mail@sartin.in> | 2026-10-08 16:45:30 +0300 |
| commit | 95eb4ff500defc4e34d043bbc096593ffcadecea (patch) | |
| tree | 65630fe3cb61260a5fedf7f63d969d27ccdb430b /service/src | |
| parent | 930eb953e8cb598a99002cb41f3b8f57d05f1fa7 (diff) | |
| download | guess-market-95eb4ff500defc4e34d043bbc096593ffcadecea.tar.gz guess-market-95eb4ff500defc4e34d043bbc096593ffcadecea.tar.xz guess-market-95eb4ff500defc4e34d043bbc096593ffcadecea.zip | |
catalog: add cumulative v3 XML loader and event mapper
Exercise 3 uploads arrive over HTTP and must never be written to the
server's disk, so load Schema v3 straight from an InputStream. Each
valid file is appended to the market rather than replacing it, and the
uploading user becomes the Market Maker of every event in it.
With no id in v3, the mapper keys events by their trimmed name, so the
repository's case-insensitive lookup finds them by name. Display ids
continue from the current market size.
The whole file is validated and mapped before anything is added, so a
rejected upload leaves the market as it was. Loading is synchronized
so two concurrent uploads cannot both pass the name-collision check.
DTDs and external entities are disabled on the parser, since the input
is untrusted and an XXE payload could otherwise read server files.
Check the loader against the course's Exercise 3 sample files, kept
with their schema under test-data/ex-3/.
Diffstat (limited to 'service/src')
3 files changed, 242 insertions, 0 deletions
diff --git a/service/src/main/java/market/guess/service/catalog/infrastructure/mapper/v3/EventMapperV3.java b/service/src/main/java/market/guess/service/catalog/infrastructure/mapper/v3/EventMapperV3.java new file mode 100644 index 0000000..7fd8112 --- /dev/null +++ b/service/src/main/java/market/guess/service/catalog/infrastructure/mapper/v3/EventMapperV3.java | |||
| @@ -0,0 +1,62 @@ | |||
| 1 | package market.guess.service.catalog.infrastructure.mapper.v3; | ||
| 2 | |||
| 3 | import java.util.ArrayList; | ||
| 4 | import java.util.List; | ||
| 5 | import market.guess.model.event.CommissionTiming; | ||
| 6 | import market.guess.model.event.EventStatus; | ||
| 7 | import market.guess.service.catalog.model.v3.GMEvent; | ||
| 8 | import market.guess.service.catalog.model.v3.GMLMSR; | ||
| 9 | import market.guess.service.catalog.model.v3.GMOrderBook; | ||
| 10 | import market.guess.service.domain.Event; | ||
| 11 | import market.guess.service.domain.Market; | ||
| 12 | import market.guess.service.mechanism.LmsrTradingMechanism; | ||
| 13 | import market.guess.service.mechanism.OrderBookTradingMechanism; | ||
| 14 | import market.guess.service.mechanism.TradingMechanism; | ||
| 15 | |||
| 16 | public final class EventMapperV3 { | ||
| 17 | |||
| 18 | public Event toDomain(GMEvent source, int displayId, String marketMaker) { | ||
| 19 | var key = source.getName().trim(); | ||
| 20 | return new Event( | ||
| 21 | key, | ||
| 22 | displayId, | ||
| 23 | key, | ||
| 24 | source.getDescription(), | ||
| 25 | source.getCommission().getValue(), | ||
| 26 | getTiming(source.getCommission().getType()), | ||
| 27 | getMechanism(source, source.getGMOptions().getGMOption().size()), | ||
| 28 | EventStatus.DRAFT, | ||
| 29 | getOptions(key, source.getGMOptions().getGMOption()), | ||
| 30 | marketMaker); | ||
| 31 | } | ||
| 32 | |||
| 33 | private static CommissionTiming getTiming(String type) { | ||
| 34 | return switch (type.toLowerCase().trim()) { | ||
| 35 | case "on-close" -> CommissionTiming.ON_CLOSE; | ||
| 36 | case "on-purchase" -> CommissionTiming.ON_PURCHASE; | ||
| 37 | default -> throw new IllegalArgumentException("Unknown commission type: " + type); | ||
| 38 | }; | ||
| 39 | } | ||
| 40 | |||
| 41 | private static TradingMechanism getMechanism(GMEvent source, int optionCount) { | ||
| 42 | if (source.getGMMethod().getGMLMSR() instanceof GMLMSR lmsr) { | ||
| 43 | return new LmsrTradingMechanism(lmsr.getB(), optionCount); | ||
| 44 | } | ||
| 45 | if (source.getGMMethod().getGMOrderBook() instanceof GMOrderBook orderBook) { | ||
| 46 | return new OrderBookTradingMechanism( | ||
| 47 | "true".equalsIgnoreCase(orderBook.getAllowMint()), | ||
| 48 | orderBook.getInitial(), | ||
| 49 | orderBook.getD(), | ||
| 50 | optionCount); | ||
| 51 | } | ||
| 52 | throw new IllegalArgumentException("Unknown trading method for event: " + source.getName()); | ||
| 53 | } | ||
| 54 | |||
| 55 | private static List<Market> getOptions(String key, List<String> raw) { | ||
| 56 | var ret = new ArrayList<Market>(raw.size()); | ||
| 57 | for (var i = 0; i < raw.size(); i++) { | ||
| 58 | ret.add(new Market(key + ":" + i, raw.get(i).trim())); | ||
| 59 | } | ||
| 60 | return ret; | ||
| 61 | } | ||
| 62 | } | ||
diff --git a/service/src/main/java/market/guess/service/catalog/infrastructure/provider/v3/XMLLoaderV3.java b/service/src/main/java/market/guess/service/catalog/infrastructure/provider/v3/XMLLoaderV3.java new file mode 100644 index 0000000..59aa3ad --- /dev/null +++ b/service/src/main/java/market/guess/service/catalog/infrastructure/provider/v3/XMLLoaderV3.java | |||
| @@ -0,0 +1,78 @@ | |||
| 1 | package market.guess.service.catalog.infrastructure.provider.v3; | ||
| 2 | |||
| 3 | import jakarta.xml.bind.JAXBContext; | ||
| 4 | import jakarta.xml.bind.JAXBException; | ||
| 5 | import java.io.InputStream; | ||
| 6 | import java.util.ArrayList; | ||
| 7 | import javax.xml.stream.XMLInputFactory; | ||
| 8 | import javax.xml.stream.XMLStreamException; | ||
| 9 | import market.guess.api.LoadResult; | ||
| 10 | import market.guess.api.Result; | ||
| 11 | import market.guess.service.catalog.infrastructure.mapper.v3.EventMapperV3; | ||
| 12 | import market.guess.service.catalog.infrastructure.repository.EventRepository; | ||
| 13 | import market.guess.service.catalog.model.v3.GMEvent; | ||
| 14 | import market.guess.service.catalog.model.v3.GuessMarket; | ||
| 15 | |||
| 16 | public final class XMLLoaderV3 { | ||
| 17 | private final JAXBContext contextV3; | ||
| 18 | private final XMLInputFactory xmlInput; | ||
| 19 | private final EventRepository eventRepository; | ||
| 20 | private final EventMapperV3 mapperV3; | ||
| 21 | private final XMLValidatorV3 validatorV3; | ||
| 22 | |||
| 23 | public XMLLoaderV3( | ||
| 24 | EventRepository eventRepository, EventMapperV3 mapperV3, XMLValidatorV3 validatorV3) { | ||
| 25 | this.eventRepository = eventRepository; | ||
| 26 | this.mapperV3 = mapperV3; | ||
| 27 | this.validatorV3 = validatorV3; | ||
| 28 | try { | ||
| 29 | this.contextV3 = JAXBContext.newInstance(GuessMarket.class); | ||
| 30 | } catch (JAXBException e) { | ||
| 31 | throw new IllegalStateException("Failed to initialize JAXB context: " + e.getMessage(), e); | ||
| 32 | } | ||
| 33 | this.xmlInput = XMLInputFactory.newFactory(); | ||
| 34 | xmlInput.setProperty(XMLInputFactory.SUPPORT_DTD, false); | ||
| 35 | xmlInput.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); | ||
| 36 | } | ||
| 37 | |||
| 38 | public synchronized Result<LoadResult> load(InputStream in, String source, String uploader) { | ||
| 39 | if (in == null) { | ||
| 40 | return Result.error("INVALID_INPUT", "No file content was provided."); | ||
| 41 | } | ||
| 42 | if (uploader == null || uploader.isBlank()) { | ||
| 43 | return Result.error("INVALID_UPLOADER", "An upload must come from a logged-in user."); | ||
| 44 | } | ||
| 45 | |||
| 46 | GuessMarket seed; | ||
| 47 | try { | ||
| 48 | var reader = xmlInput.createXMLStreamReader(in); | ||
| 49 | try { | ||
| 50 | seed = (GuessMarket) contextV3.createUnmarshaller().unmarshal(reader); | ||
| 51 | } finally { | ||
| 52 | reader.close(); | ||
| 53 | } | ||
| 54 | } catch (JAXBException e) { | ||
| 55 | var cause = | ||
| 56 | e.getLinkedException() != null ? e.getLinkedException().getMessage() : e.getMessage(); | ||
| 57 | return Result.error( | ||
| 58 | "XML_PARSE_ERROR", | ||
| 59 | "The XML file is malformed or invalid: " + (cause != null ? cause : e.getMessage())); | ||
| 60 | } catch (XMLStreamException e) { | ||
| 61 | return Result.error("XML_PARSE_ERROR", "The XML file is malformed: " + e.getMessage()); | ||
| 62 | } | ||
| 63 | |||
| 64 | var validation = validatorV3.validate(seed, eventRepository); | ||
| 65 | if (!validation.isSuccess()) { | ||
| 66 | return Result.error(validation.getMessage(), validation.getDetails()); | ||
| 67 | } | ||
| 68 | |||
| 69 | var nextId = eventRepository.getAll().size() + 1; | ||
| 70 | var mapped = new ArrayList<market.guess.service.domain.Event>(); | ||
| 71 | for (GMEvent e : seed.getGMEvents().getGMEvent()) { | ||
| 72 | mapped.add(mapperV3.toDomain(e, nextId++, uploader.trim())); | ||
| 73 | } | ||
| 74 | mapped.forEach(eventRepository::add); | ||
| 75 | |||
| 76 | return Result.ok(new LoadResult(source, mapped.size())); | ||
| 77 | } | ||
| 78 | } | ||
diff --git a/service/src/test/java/market/guess/service/Ex3LoaderTest.java b/service/src/test/java/market/guess/service/Ex3LoaderTest.java new file mode 100644 index 0000000..745b1fd --- /dev/null +++ b/service/src/test/java/market/guess/service/Ex3LoaderTest.java | |||
| @@ -0,0 +1,102 @@ | |||
| 1 | package market.guess.service; | ||
| 2 | |||
| 3 | import static market.guess.service.Ex3ValidatorTest.lmsr; | ||
| 4 | import static market.guess.service.Ex3ValidatorTest.market; | ||
| 5 | import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| 6 | import static org.junit.jupiter.api.Assertions.assertFalse; | ||
| 7 | import static org.junit.jupiter.api.Assertions.assertTrue; | ||
| 8 | |||
| 9 | import java.io.ByteArrayInputStream; | ||
| 10 | import java.io.InputStream; | ||
| 11 | import java.nio.charset.StandardCharsets; | ||
| 12 | import java.nio.file.Files; | ||
| 13 | import java.nio.file.Path; | ||
| 14 | import market.guess.model.event.EventStatus; | ||
| 15 | import market.guess.service.catalog.infrastructure.mapper.v3.EventMapperV3; | ||
| 16 | import market.guess.service.catalog.infrastructure.provider.v3.XMLLoaderV3; | ||
| 17 | import market.guess.service.catalog.infrastructure.provider.v3.XMLValidatorV3; | ||
| 18 | import market.guess.service.catalog.infrastructure.repository.InMemoryEventRepository; | ||
| 19 | import org.junit.jupiter.api.BeforeEach; | ||
| 20 | import org.junit.jupiter.api.Test; | ||
| 21 | |||
| 22 | class Ex3LoaderTest { | ||
| 23 | private InMemoryEventRepository eventRepo; | ||
| 24 | private XMLLoaderV3 loader; | ||
| 25 | |||
| 26 | @BeforeEach | ||
| 27 | void setUp() { | ||
| 28 | eventRepo = new InMemoryEventRepository(); | ||
| 29 | loader = new XMLLoaderV3(eventRepo, new EventMapperV3(), new XMLValidatorV3()); | ||
| 30 | } | ||
| 31 | |||
| 32 | private static InputStream stream(String xml) { | ||
| 33 | return new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); | ||
| 34 | } | ||
| 35 | |||
| 36 | @Test | ||
| 37 | void uploadsAccumulateAndUploaderBecomesMarketMaker() { | ||
| 38 | var first = loader.load(stream(market(lmsr("Rain"), lmsr("Snow"))), "a.xml", "alice"); | ||
| 39 | assertTrue(first.isSuccess(), first.getDetails()); | ||
| 40 | assertEquals(2, first.getData().eventsLoaded()); | ||
| 41 | |||
| 42 | var second = loader.load(stream(market(lmsr("Hail"))), "b.xml", "bob"); | ||
| 43 | assertTrue(second.isSuccess(), second.getDetails()); | ||
| 44 | assertEquals(3, eventRepo.getAll().size()); | ||
| 45 | |||
| 46 | var rain = eventRepo.get("rain").orElseThrow(); | ||
| 47 | assertEquals("Rain", rain.getName()); | ||
| 48 | assertEquals("alice", rain.getMarketMaker()); | ||
| 49 | assertEquals(EventStatus.DRAFT, rain.getState()); | ||
| 50 | assertEquals("bob", eventRepo.get("Hail").orElseThrow().getMarketMaker()); | ||
| 51 | } | ||
| 52 | |||
| 53 | @Test | ||
| 54 | void loadsCourseSampleFilesCumulatively() throws Exception { | ||
| 55 | try (var small = Files.newInputStream(Path.of("test-data/ex-3/small.xml")); | ||
| 56 | var multiple = Files.newInputStream(Path.of("test-data/ex-3/multiple.xml"))) { | ||
| 57 | var first = loader.load(small, "small.xml", "alice"); | ||
| 58 | assertTrue(first.isSuccess(), first.getDetails()); | ||
| 59 | var second = loader.load(multiple, "multiple.xml", "bob"); | ||
| 60 | assertTrue(second.isSuccess(), second.getDetails()); | ||
| 61 | assertEquals(3, second.getData().eventsLoaded()); | ||
| 62 | } | ||
| 63 | assertEquals(4, eventRepo.getAll().size()); | ||
| 64 | assertEquals("alice", eventRepo.get("Mujtaba is Dead").orElseThrow().getMarketMaker()); | ||
| 65 | assertEquals("bob", eventRepo.get("World Cap Winner").orElseThrow().getMarketMaker()); | ||
| 66 | |||
| 67 | try (var again = Files.newInputStream(Path.of("test-data/ex-3/small.xml"))) { | ||
| 68 | assertEquals("NAME_TAKEN", loader.load(again, "small.xml", "carol").getMessage()); | ||
| 69 | } | ||
| 70 | assertEquals(4, eventRepo.getAll().size()); | ||
| 71 | } | ||
| 72 | |||
| 73 | @Test | ||
| 74 | void collisionRejectsWholeFileAndKeepsMarket() { | ||
| 75 | loader.load(stream(market(lmsr("Rain"))), "a.xml", "alice"); | ||
| 76 | |||
| 77 | var res = loader.load(stream(market(lmsr("Fog"), lmsr("rain"))), "b.xml", "bob"); | ||
| 78 | assertFalse(res.isSuccess()); | ||
| 79 | assertEquals("NAME_TAKEN", res.getMessage()); | ||
| 80 | assertEquals(1, eventRepo.getAll().size()); | ||
| 81 | assertTrue(eventRepo.get("Fog").isEmpty()); | ||
| 82 | } | ||
| 83 | |||
| 84 | @Test | ||
| 85 | void rejectsMalformedXmlAndMissingUploader() { | ||
| 86 | assertEquals( | ||
| 87 | "XML_PARSE_ERROR", loader.load(stream("<Guess-Market>"), "x.xml", "alice").getMessage()); | ||
| 88 | assertEquals( | ||
| 89 | "INVALID_UPLOADER", loader.load(stream(market(lmsr("Rain"))), "x.xml", " ").getMessage()); | ||
| 90 | assertTrue(eventRepo.getAll().isEmpty()); | ||
| 91 | } | ||
| 92 | |||
| 93 | @Test | ||
| 94 | void refusesDtdsSoExternalEntitiesCannotBeRead() { | ||
| 95 | var xxe = | ||
| 96 | "<?xml version=\"1.0\"?><!DOCTYPE Guess-Market [<!ENTITY x SYSTEM \"file:///etc/passwd\">]>" | ||
| 97 | + market(lmsr("&x;")); | ||
| 98 | var res = loader.load(stream(xxe), "x.xml", "alice"); | ||
| 99 | assertEquals("XML_PARSE_ERROR", res.getMessage()); | ||
| 100 | assertTrue(eventRepo.getAll().isEmpty()); | ||
| 101 | } | ||
| 102 | } | ||