From f53e58a3b86fd9cf3c3357fccfb5bbb4d500696b Mon Sep 17 00:00:00 2001 From: Manuel Thalmann Date: Tue, 27 Sep 2022 13:05:36 +0200 Subject: [PATCH] Add a server for checking basic `XML` integrity --- .../nuth/zhaw/exbox/WellformedXmlServer.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 app/src/main/java/ch/nuth/zhaw/exbox/WellformedXmlServer.java diff --git a/app/src/main/java/ch/nuth/zhaw/exbox/WellformedXmlServer.java b/app/src/main/java/ch/nuth/zhaw/exbox/WellformedXmlServer.java new file mode 100644 index 0000000..860b728 --- /dev/null +++ b/app/src/main/java/ch/nuth/zhaw/exbox/WellformedXmlServer.java @@ -0,0 +1,30 @@ +package ch.nuth.zhaw.exbox; + +import java.util.regex.MatchResult; +import java.util.regex.Pattern; + +public class WellformedXmlServer implements CommandExecutor { + Pattern tagPattern = Pattern.compile("<(/?)(\\w+)( \\w+=\"[^\"]*\")*>"); + + @Override + public String execute(String command) throws Exception { + return Boolean.toString(checkWellformed(command)) + "\n"; + } + + public boolean checkWellformed(String code) { + ListStack openTags = new ListStack(); + Iterable results = () -> tagPattern.matcher(code).results().iterator(); + + for (MatchResult result : results) { + if (result.group(1).length() == 0) { + openTags.push(result.group(2)); + } else if (result.group(2).equals(openTags.peek())) { + openTags.pop(); + } else { + return false; + } + } + + return openTags.isEmpty(); + } +}