Skip to content

Commit

Permalink
test (E2E): Create WebhooksHelper class
Browse files Browse the repository at this point in the history
  • Loading branch information
JPPortier committed Oct 2, 2024
1 parent 146f1ee commit 043eb88
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions client/src/test/java/com/sinch/sdk/e2e/domains/WebhooksHelper.java
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;
}
}

0 comments on commit 043eb88

Please sign in to comment.