You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.4 KiB

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<String, Command> commands = new HashMap<>();
private final Map<String, String> aliases = new HashMap<>();
private final ConsoleView view;
private final List<Article> articles;
private final List<String> 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<Article> 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();
}
}