package com.example.datacollect.controller; import com.example.datacollect.command.*; import com.example.datacollect.model.Article; import com.example.datacollect.view.ConsoleView; import java.util.*; import java.util.regex.Pattern; public class CrawlerController { private final Map commands = new HashMap<>(); private final Map aliases = new HashMap<>(); private final ConsoleView view; private final List
articles; private final List commandHistory; private final HistoryCommand historyCommand; private static final Pattern URL_PATTERN = Pattern.compile( "^(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})([/\\w.-]*)*(/?)" ); public CrawlerController(ConsoleView view, List
articles) { this.view = view; this.articles = articles; this.commandHistory = new ArrayList<>(); this.historyCommand = new HistoryCommand(view, commandHistory); register(new HelpCommand(view)); register(new ListCommand(view)); register(new CrawlCommand(view)); register(new ExitCommand(view)); register(historyCommand); registerAliases(); } private void register(Command command) { commands.put(command.getName(), command); } private void registerAliases() { aliases.put("c", "crawl"); aliases.put("ls", "list"); aliases.put("h", "help"); aliases.put("q", "exit"); } public void handle(String input) { String text = input == null ? "" : input.trim(); if (text.isEmpty()) { return; } commandHistory.add(text); String[] args = text.split("\\s+"); String cmdName = args[0].toLowerCase(); String actualCommand = aliases.getOrDefault(cmdName, cmdName); Command command = commands.get(actualCommand); if (command == null) { view.printError("Unknown command: " + cmdName); return; } if ("crawl".equals(actualCommand) && args.length >= 2) { if (!isValidUrl(args[1])) { view.printError("Invalid URL format: " + args[1]); return; } } command.execute(args, articles); } private boolean isValidUrl(String url) { if (url == null || url.isEmpty()) { return false; } return URL_PATTERN.matcher(url).matches(); } }