1
1
package modern .challenge ;
2
2
3
- import java .util .List ;
3
+ import com .fasterxml .jackson .databind .JsonNode ;
4
+ import com .fasterxml .jackson .databind .ObjectMapper ;
5
+ import java .io .IOException ;
6
+ import java .util .regex .Pattern ;
4
7
5
8
public class Main {
6
9
7
- public static void main (String [] args ) {
8
-
9
- PhoneProcessor pp = new PhoneProcessor ();
10
-
11
- List <String > names = List .of ("Arita Ion" , "Mark Jurg" , "Paul Istrate" );
12
- List <String > phones = List .of ("244-815-0089" , "0721-825-8892" , "(045)655-9230" );
13
-
14
- StringBuilder xmlMessage = new StringBuilder ();
15
- for (int i = 0 ; i < names .size (); i ++) {
16
-
17
- xmlMessage .append (pp ."""
18
- <name>\{names .get (i )}</name>
19
- <phone>\{phones .get (i )}</phone>
20
- """ );
21
- }
10
+ private static final Pattern PHONE_PATTERN = Pattern .compile (
11
+ "\\ d{10}|(?:\\ d{3}-){2}\\ d{4}|\\ (\\ d{3}\\ )\\ d{3}-?\\ d{4}" );
12
+
13
+ public static void main (String [] args ) throws IOException {
14
+
15
+ StringTemplate .Processor <JsonNode , IllegalArgumentException > pp
16
+ = (StringTemplate st ) -> {
17
+
18
+ var values = st .values ().stream ()
19
+ .map (value -> {
20
+ if (!PHONE_PATTERN .matcher ((CharSequence ) value ).matches ()) {
21
+ return "Invalid phone number" ;
22
+ }
23
+
24
+ return value ;
25
+ }).toList ();
26
+
27
+ ObjectMapper mapper = new ObjectMapper ();
28
+
29
+ try {
30
+ return mapper .readTree (StringTemplate .interpolate (
31
+ st .fragments (), values ));
32
+ } catch (IOException ex ) {
33
+ throw new RuntimeException (ex );
34
+ }
35
+ };
36
+
37
+ String workPhone = "072-825-90095" ; // not valid
38
+ String homePhone = "(040)234-9670" ;
39
+
40
+ JsonNode jsonMessage = pp .
41
+ """
42
+ { "contact": {
43
+ "work": "\{workPhone }",
44
+ "home": "\{homePhone }"
45
+ }
46
+ }
47
+ """ ;
22
48
23
- System .out .println (xmlMessage );
49
+ System .out .println (jsonMessage );
24
50
}
25
51
}
0 commit comments