| 1 | package edu.ucsb.cs156.happiercows.services; | |
| 2 | ||
| 3 | import edu.ucsb.cs156.happiercows.entities.BannedWord; | |
| 4 | import edu.ucsb.cs156.happiercows.models.CensorResult; | |
| 5 | import edu.ucsb.cs156.happiercows.repositories.BannedWordRepository; | |
| 6 | import org.springframework.beans.factory.annotation.Autowired; | |
| 7 | import org.springframework.stereotype.Service; | |
| 8 | ||
| 9 | import java.util.List; | |
| 10 | import java.util.regex.Pattern; | |
| 11 | import java.util.stream.Collectors; | |
| 12 | import java.util.stream.StreamSupport; | |
| 13 | ||
| 14 | /** Replaces banned words in chat messages with asterisks. */ | |
| 15 | @Service | |
| 16 | public class ChatFilterService { | |
| 17 | ||
| 18 | // A match must not have a letter, digit, or underscore directly before or after it, | |
| 19 | // so banning "cow" does not censor "cowboy". | |
| 20 | private static final String NOT_WORD_CHAR_BEFORE = "(?<![\\p{L}\\p{N}_])"; | |
| 21 | private static final String NOT_WORD_CHAR_AFTER = "(?![\\p{L}\\p{N}_])"; | |
| 22 | ||
| 23 | @Autowired | |
| 24 | private BannedWordRepository bannedWordRepository; | |
| 25 | ||
| 26 | public CensorResult censor(String message) { | |
| 27 | List<String> words = StreamSupport | |
| 28 | .stream(bannedWordRepository.findAll().spliterator(), false) | |
| 29 | .map(BannedWord::getWord) | |
| 30 | .collect(Collectors.toList()); | |
| 31 | ||
| 32 |
1
1. censor : negated conditional → KILLED |
if (words.isEmpty()) { |
| 33 |
1
1. censor : replaced return value with null for edu/ucsb/cs156/happiercows/services/ChatFilterService::censor → KILLED |
return new CensorResult(message, false); |
| 34 | } | |
| 35 | ||
| 36 | String alternatives = words.stream() | |
| 37 | .map(Pattern::quote) | |
| 38 | .collect(Collectors.joining("|")); | |
| 39 | ||
| 40 | Pattern pattern = Pattern.compile( | |
| 41 | NOT_WORD_CHAR_BEFORE + "(?:" + alternatives + ")" + NOT_WORD_CHAR_AFTER, | |
| 42 | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); | |
| 43 | ||
| 44 |
1
1. censor : negated conditional → KILLED |
if (!pattern.matcher(message).find()) { |
| 45 |
1
1. censor : replaced return value with null for edu/ucsb/cs156/happiercows/services/ChatFilterService::censor → KILLED |
return new CensorResult(message, false); |
| 46 | } | |
| 47 | ||
| 48 | String censoredText = pattern.matcher(message) | |
| 49 |
1
1. lambda$censor$0 : replaced return value with "" for edu/ucsb/cs156/happiercows/services/ChatFilterService::lambda$censor$0 → KILLED |
.replaceAll(match -> "*".repeat(match.group().length())); |
| 50 |
1
1. censor : replaced return value with null for edu/ucsb/cs156/happiercows/services/ChatFilterService::censor → KILLED |
return new CensorResult(censoredText, true); |
| 51 | } | |
| 52 | } | |
Mutations | ||
| 32 |
1.1 |
|
| 33 |
1.1 |
|
| 44 |
1.1 |
|
| 45 |
1.1 |
|
| 49 |
1.1 |
|
| 50 |
1.1 |