11package com .stubbornjava .examples .undertow .parameters ;
22
3+ import java .util .stream .LongStream ;
4+
5+ import org .slf4j .Logger ;
6+ import org .slf4j .LoggerFactory ;
7+
38import com .google .common .base .Strings ;
49import com .stubbornjava .common .undertow .Exchange ;
510import com .stubbornjava .common .undertow .SimpleServer ;
11+ import com .stubbornjava .examples .common .HashIds ;
612
713import io .undertow .server .HttpHandler ;
814import io .undertow .server .HttpServerExchange ;
915import io .undertow .server .RoutingHandler ;
1016
1117public class ParametersServer {
18+ private static final Logger log = LoggerFactory .getLogger (ParametersServer .class );
1219
1320 // {{start:handlers}}
1421 private static void queryParam (HttpServerExchange exchange ) {
@@ -24,15 +31,46 @@ private static void pathParam(HttpServerExchange exchange) {
2431 }
2532 // {{end:handlers}}
2633
34+ // {{start:obfuscatedRoute}}
35+ private static void obfuscatedId (HttpServerExchange exchange ) {
36+ // Using the above helper
37+ Long userId = ParametersServer .userId (exchange );
38+ // This is just to show the raw value.
39+ String rawUserIdParam = Exchange .pathParams ()
40+ .pathParam (exchange , "userId" )
41+ .orElse (null );
42+ Exchange .body ().sendText (exchange , "UserId: " + userId + " hashed: " + rawUserIdParam );
43+ }
44+ // {{end:obfuscatedRoute}}
45+
46+ // {{start:obfuscated}}
47+ /*
48+ * It's useful to create helpers for params you know you will use over and over.
49+ * It will reduce boilerpalte, typos, and ensure you use common defaults.
50+ * You could even add validation at this step if you wanted.
51+ */
52+ private static Long userId (HttpServerExchange exchange ) {
53+ return Exchange .pathParams ()
54+ .pathParam (exchange , "userId" )
55+ .map (HashIds ::decode )
56+ .orElse (null );
57+ }
58+ // {{end:obfuscated}}
59+
2760 // {{start:routes}}
2861 private static final HttpHandler ROUTES = new RoutingHandler ()
2962 .get ("/hello" , ParametersServer ::queryParam )
3063 .get ("/hello/{name}/{num}" , ParametersServer ::pathParam )
64+ .get ("/users/{userId}" , ParametersServer ::obfuscatedId )
3165 ;
3266 // {{end:routes}}
3367
3468 // {{start:server}}
3569 public static void main (String [] args ) {
70+ // Just some examples for obfuscated parameters.
71+ LongStream .range (100_000_000 , 100_000_003 ).forEach ( id -> {
72+ log .debug ("id: " + id + " hashed: " + HashIds .encode (id ));
73+ });
3674 SimpleServer server = SimpleServer .simpleServer (ROUTES );
3775 server .start ();
3876 }
0 commit comments