1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package de.aikiit.spamprotector.converter;
19
20 import com.google.common.base.Strings;
21 import com.google.common.collect.Maps;
22 import lombok.AccessLevel;
23 import lombok.NoArgsConstructor;
24
25 import java.util.Map;
26
27
28
29
30 @NoArgsConstructor(access = AccessLevel.PRIVATE)
31 public final class SpamProtector {
32
33 private static final Map<String, CharacterConverter> ENCODED = Maps.newHashMap();
34 private static final Map<Character, CharacterConverter> PLAIN = Maps.newHashMap();
35
36 static {
37
38 for (CharacterConverter character : CharacterConverter.values()) {
39 ENCODED.put(character.getReplacement().toLowerCase(), character);
40 PLAIN.put(character.getPlain().charAt(0), character);
41 }
42 }
43
44
45
46
47
48
49
50 public static String toPlain(String input) {
51 if (!Strings.isNullOrEmpty(input)) {
52 String toTransform = input;
53 StringBuilder result = new StringBuilder();
54
55 while (!Strings.isNullOrEmpty(toTransform)) {
56 int lengthBeforeConversion = toTransform.length();
57
58 for(Map.Entry<String, CharacterConverter> entry : ENCODED.entrySet()) {
59
60 String prefix = entry.getKey();
61 if (toTransform.startsWith(prefix)) {
62 result.append(entry.getValue().getPlain());
63 toTransform = toTransform.substring(prefix.length(), toTransform.length());
64 }
65 }
66
67
68 if (toTransform.length() == lengthBeforeConversion) {
69 result.append(toTransform.charAt(0));
70 toTransform = toTransform.substring(1);
71 }
72 }
73
74 return result.toString();
75
76 }
77 return input;
78 }
79
80
81
82
83
84
85
86 public static String toEncoded(String input) {
87 if (!Strings.isNullOrEmpty(input)) {
88 StringBuilder result = new StringBuilder();
89
90 for (Character character : input.toCharArray()) {
91 result.append(PLAIN.containsKey(character) ? PLAIN.get(character).getReplacement() : character);
92 }
93
94 return result.toString();
95 }
96 return input;
97 }
98 }