package com.example.datacollect.repository; import com.example.datacollect.model.Article; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ArticleRepository { private static final Logger logger = LoggerFactory.getLogger(ArticleRepository.class); private final List
articles = new ArrayList<>(); // 新增:根据索引获取文章(防御索引越界) public Article get(int index) { logger.debug("Getting article at index: {}", index); if (index < 0 || index >= articles.size()) { String errorMsg = "Index out of bounds: index=" + index + ", size=" + articles.size(); logger.error(errorMsg); throw new IndexOutOfBoundsException(errorMsg); } return articles.get(index); } public void add(Article article) { logger.debug("Adding article: {}", article); if (article == null) { String errorMsg = "Article cannot be null"; logger.error(errorMsg); throw new IllegalArgumentException(errorMsg); } // 新增:防御重复添加(可选) if (articles.contains(article)) { logger.warn("Article already exists: {}", article); return; } articles.add(article); logger.info("Added article: {}", article.getTitle()); } // ★ 新增:批量添加方法以及注意防御 null public void addAll(List
articles) { logger.debug("Adding batch articles, size: {}", articles == null ? "null" : articles.size()); if (articles == null) { String errorMsg = "Articles list cannot be null"; logger.error(errorMsg); throw new IllegalArgumentException(errorMsg); } if (articles.isEmpty()) { logger.warn("Articles list is empty, skip addAll"); return; } int addedCount = 0; for (Article article : articles) { if (article == null) { logger.error("Skipping null article in batch add"); continue; // 或抛出异常,根据业务选择 } if (!this.articles.contains(article)) { this.articles.add(article); addedCount++; } } logger.info("Batch added {} articles (skipped duplicates/null)", addedCount); } public List
getAll() { List
unmodifiableList = Collections.unmodifiableList(articles); logger.debug("Getting all articles, size: {}", unmodifiableList.size()); return unmodifiableList; } public int size() { int size = articles.size(); logger.debug("Repository size: {}", size); return size; } // 新增:清空前校验 + 日志 public void clear() { logger.warn("Clearing all articles (current size: {})", articles.size()); if (articles.isEmpty()) { logger.info("Repository is already empty, skip clear"); return; } articles.clear(); logger.info("Cleared all articles successfully"); } // 新增:检查是否包含指定URL的文章(防御检查) public boolean containsUrl(String url) { logger.debug("Checking if repository contains url: {}", url); if (url == null || url.isBlank()) { logger.error("URL cannot be null/blank"); throw new IllegalArgumentException("URL cannot be null or blank"); } return articles.stream().anyMatch(article -> url.equals(article.getUrl())); } }