diff --git a/client/src/test/java/com/sinch/sdk/e2e/domains/WebhooksHelper.java b/client/src/test/java/com/sinch/sdk/e2e/domains/WebhooksHelper.java new file mode 100644 index 00000000..0a3ea49f --- /dev/null +++ b/client/src/test/java/com/sinch/sdk/e2e/domains/WebhooksHelper.java @@ -0,0 +1,58 @@ +package com.sinch.sdk.e2e.domains; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +public class WebhooksHelper { + + public static Response callURL(URL url, Function parseEvent) + throws IOException { + + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + + byte[] buffer = new byte[1024]; + int bytesRead; + InputStream inputStream = con.getInputStream(); + while ((bytesRead = inputStream.read(buffer)) != -1) { + byteArrayOutputStream.write(buffer, 0, bytesRead); + } + Response response = new Response<>(); + response.headers = transformHeaders(con.getHeaderFields()); + response.rawPayload = byteArrayOutputStream.toString("UTF-8"); + response.event = parseEvent.apply(response.rawPayload); + return response; + } + + static Map transformHeaders(Map> headers) { + if (null == headers) { + return null; + } + HashMap newMap = new HashMap<>(); + headers.forEach((key, value) -> newMap.put(key, concatHeaderValues(value))); + return newMap; + } + + static String concatHeaderValues(List values) { + if (null == values) { + return null; + } + return values.stream() + .reduce(null, (previous, current) -> (null != previous ? previous + ";" : "") + current); + } + + public static class Response { + public Map headers; + public String rawPayload; + public T event; + } +}