Skip to content

Commit 6a0786d

Browse files
committed
feat(http): Add Request static accessors for exchange attributes
1 parent 31753a6 commit 6a0786d

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.retailsvc.http;
2+
3+
import com.sun.net.httpserver.HttpExchange;
4+
import java.util.Map;
5+
6+
public final class Request {
7+
public static final String BODY = "body";
8+
public static final String PARSED_BODY = "parsed-body";
9+
public static final String OPERATION_ID = "operation-id";
10+
public static final String PATH_PARAMETERS = "path-parameters";
11+
12+
private Request() {}
13+
14+
public static byte[] bytes(HttpExchange e) {
15+
return (byte[]) e.getAttribute(BODY);
16+
}
17+
18+
public static Object parsed(HttpExchange e) {
19+
return e.getAttribute(PARSED_BODY);
20+
}
21+
22+
public static String operationId(HttpExchange e) {
23+
return (String) e.getAttribute(OPERATION_ID);
24+
}
25+
26+
@SuppressWarnings("unchecked")
27+
public static Map<String, String> pathParams(HttpExchange e) {
28+
return (Map<String, String>) e.getAttribute(PATH_PARAMETERS);
29+
}
30+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.retailsvc.http;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import com.sun.net.httpserver.HttpExchange;
6+
import java.util.Map;
7+
import org.junit.jupiter.api.Test;
8+
import org.mockito.Mockito;
9+
10+
class RequestTest {
11+
@Test
12+
void readsAttributes() {
13+
HttpExchange ex = Mockito.mock(HttpExchange.class);
14+
Mockito.when(ex.getAttribute("body")).thenReturn(new byte[] {1, 2, 3});
15+
Mockito.when(ex.getAttribute("parsed-body")).thenReturn(Map.of("k", "v"));
16+
Mockito.when(ex.getAttribute("operation-id")).thenReturn("get-x");
17+
Mockito.when(ex.getAttribute("path-parameters")).thenReturn(Map.of("id", "42"));
18+
19+
assertThat(Request.bytes(ex)).containsExactly(1, 2, 3);
20+
assertThat(Request.parsed(ex)).isEqualTo(Map.of("k", "v"));
21+
assertThat(Request.operationId(ex)).isEqualTo("get-x");
22+
assertThat(Request.pathParams(ex)).containsEntry("id", "42");
23+
}
24+
}

0 commit comments

Comments
 (0)