· 7 years ago · Oct 23, 2018, 02:26 AM
1import org.apache.commons.lang.StringUtils;
2import java.util.HashMap;
3import java.util.Map;
4
5public class App {
6 public static void main(String[] args) {
7
8 //all these prints out as expected.
9
10 String newEmail1 = getEmail("sample1");
11 System.out.println("Expected: some**@gmail.com | actual: " + newEmail1);
12
13 String newEmail2 = getEmail("sample2");
14 System.out.println("Expected: null | actual: " + newEmail2);
15
16 String newEmail3 = getEmail("short");
17 System.out.println("Expected: q**@gmail.com | actual: " + newEmail3);
18
19 String newEmail4 = getEmail("noname");
20 System.out.println("Expected: null | actual: " + newEmail4);
21 }
22
23 private static String getEmail(String param){
24 //added these solely for testing to show
25 Map<String, String> emails = new HashMap<>();
26 emails.put("sample1", "someone@gmail.com");
27 emails.put("short", "qw@gmail.com");
28 emails.put("noname", "@gmail.com");
29 //added these solely for testing to show
30
31 //I am looking for opinions from here onwards. <-- HERE -->
32 String emailAddress = emails.get(param);
33 if(emailAddress != null){
34 String emailAddressFront = StringUtils.substringBefore(emailAddress, "@");
35 String emailAddressBack = StringUtils.substringAfter(emailAddress, "@");
36
37 // i need to hide emails by only revealing first 4 characters.
38 // but also need to check in case email name is shorter than 4.
39 if(emailAddressFront.isEmpty()){
40 return null;
41 }
42 int shortenedLength = 4;
43 int emailNameLength = emailAddressFront.length();
44 if(emailNameLength < 4){
45 shortenedLength = emailNameLength - 1;
46 }
47 emailAddress = emailAddressFront.substring(0, shortenedLength) + "**@" + emailAddressBack;
48 }
49 return emailAddress;
50 //I am looking for opinions till here. <-- HERE -->
51 }
52}
53
54private static String getEmail(final String param){
55 final Map<String, String> emails = new HashMap<>();
56 emails.put("sample1", "someone@gmail.com");
57 emails.put("short", "qw@gmail.com");
58 emails.put("noname", "@gmail.com");
59
60 final String emailAddress = emails.get(param);
61 if (emailAddress == null) {
62 return null;
63 }
64
65 final int atIndex = emailAddress.indexOf('@');
66 if (atIndex == 0) {
67 return null;
68 }
69
70 final StringBuilder maskedEmailAddress = new StringBuilder(emailAddress);
71 if (atIndex < 4) {
72 maskedEmailAddress.replace(1, atIndex, "**");
73 } else {
74 maskedEmailAddress.replace(4, atIndex, "**");
75 }
76
77 return maskedEmailAddress.toString();
78}