-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
test (E2E): Create WebhooksHelper class
- Loading branch information
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
client/src/test/java/com/sinch/sdk/e2e/domains/WebhooksHelper.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 <T> Response<T> callURL(URL url, Function<String, T> 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<T> response = new Response<>(); | ||
response.headers = transformHeaders(con.getHeaderFields()); | ||
response.rawPayload = byteArrayOutputStream.toString("UTF-8"); | ||
response.event = parseEvent.apply(response.rawPayload); | ||
return response; | ||
} | ||
|
||
static Map<String, String> transformHeaders(Map<String, List<String>> headers) { | ||
if (null == headers) { | ||
return null; | ||
} | ||
HashMap<String, String> newMap = new HashMap<>(); | ||
headers.forEach((key, value) -> newMap.put(key, concatHeaderValues(value))); | ||
return newMap; | ||
} | ||
|
||
static String concatHeaderValues(List<String> values) { | ||
if (null == values) { | ||
return null; | ||
} | ||
return values.stream() | ||
.reduce(null, (previous, current) -> (null != previous ? previous + ";" : "") + current); | ||
} | ||
|
||
public static class Response<T> { | ||
public Map<String, String> headers; | ||
public String rawPayload; | ||
public T event; | ||
} | ||
} |