Skip to content

Commit

Permalink
fix: revert original http request
Browse files Browse the repository at this point in the history
  • Loading branch information
sattvikc committed Sep 12, 2024
1 parent d87769a commit 085e5c1
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 184 deletions.
115 changes: 16 additions & 99 deletions src/main/java/io/supertokens/httpRequest/HttpRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,22 @@

package io.supertokens.httpRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import io.supertokens.Main;

import java.io.*;
import java.net.*;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import io.supertokens.Main;

public class HttpRequest {

Expand Down Expand Up @@ -125,9 +130,8 @@ public static <T> T sendGETRequest(Main main, String requestID, String url, Map<
@SuppressWarnings("unchecked")
public static <T> T sendGETRequestWithResponseHeaders(Main main, String requestID, String url,
Map<String, String> params,
Map<String, String> headers,
int connectionTimeoutMS, int readTimeoutMS, Integer version,
Map<String, List<String>> responseHeaders, boolean followRedirects)
Map<String, String> responseHeaders)
throws IOException, HttpResponseException {
StringBuilder paramBuilder = new StringBuilder();

Expand All @@ -153,17 +157,12 @@ public static <T> T sendGETRequestWithResponseHeaders(Main main, String requestI
if (version != null) {
con.setRequestProperty("api-version", version + "");
}
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
}
con.setInstanceFollowRedirects(followRedirects);

int responseCode = con.getResponseCode();

con.getHeaderFields().forEach((key, value) -> {
if (key != null) {
responseHeaders.put(key, value);
responseHeaders.put(key, value.get(0));
}
});

Expand Down Expand Up @@ -268,93 +267,11 @@ public static <T> T sendJsonPUTRequest(Main main, String requestID, String url,
return sendJsonRequest(main, requestID, url, requestBody, connectionTimeoutMS, readTimeoutMS, version, "PUT");
}

public static <T> T sendJsonPATCHRequest(Main main, String url, JsonElement requestBody)
throws IOException, HttpResponseException, InterruptedException {

HttpClient client = null;

String body = requestBody.toString();
java.net.http.HttpRequest rawRequest = java.net.http.HttpRequest.newBuilder()
.uri(URI.create(url))
.method("PATCH", java.net.http.HttpRequest.BodyPublishers.ofString(body))
.build();
client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(rawRequest, HttpResponse.BodyHandlers.ofString());

int responseCode = response.statusCode();

if (responseCode < STATUS_CODE_ERROR_THRESHOLD) {
if (!isJsonValid(response.body().toString())) {
return (T) response.body().toString();
}
return (T) (new JsonParser().parse(response.body().toString()));
}
throw new HttpResponseException(responseCode, response.body().toString());
}

public static <T> T sendJsonDELETERequest(Main main, String requestID, String url, JsonElement requestBody,
int connectionTimeoutMS, int readTimeoutMS, Integer version)
throws IOException, HttpResponseException {
return sendJsonRequest(main, requestID, url, requestBody, connectionTimeoutMS, readTimeoutMS, version,
"DELETE");
}

public static <T> T sendFormPOSTRequest(Main main, String requestID, String url, Map<String, String> formData,
int connectionTimeoutMS, int readTimeoutMS, Integer version)
throws IOException, HttpResponseException {
StringBuilder formDataBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : formData.entrySet()) {
formDataBuilder.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)).append("&");
}
String formDataStr = formDataBuilder.toString();
if (!formDataStr.equals("")) {
formDataStr = formDataStr.substring(0, formDataStr.length() - 1);
}

URL obj = getURL(main, requestID, url);
HttpURLConnection con = null;
try {
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setConnectTimeout(connectionTimeoutMS);
con.setReadTimeout(readTimeoutMS);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
if (version != null) {
con.setRequestProperty("api-version", version + "");
}

con.setDoOutput(true);
try (OutputStream os = con.getOutputStream()) {
os.write(formDataStr.getBytes(StandardCharsets.UTF_8));
}

int responseCode = con.getResponseCode();
InputStream inputStream = null;
if (responseCode < STATUS_CODE_ERROR_THRESHOLD) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}

StringBuilder response = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
if (responseCode < STATUS_CODE_ERROR_THRESHOLD) {
if (!isJsonValid(response.toString())) {
return (T) response.toString();
}
return (T) (new JsonParser().parse(response.toString()));
}
throw new HttpResponseException(responseCode, response.toString());
} finally {
if (con != null) {
con.disconnect();
}
}
}
}
84 changes: 16 additions & 68 deletions src/test/java/io/supertokens/test/HttpRequestTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,32 @@

package io.supertokens.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import io.supertokens.ProcessState;
import io.supertokens.httpRequest.HttpRequest;
import io.supertokens.httpRequest.HttpResponseException;
import io.supertokens.webserver.Webserver;
import io.supertokens.webserver.WebserverAPI;
import jakarta.servlet.http.Cookie;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import static org.junit.Assert.*;

public class HttpRequestTest {

@Rule
Expand Down Expand Up @@ -739,56 +739,4 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO
process.kill();
assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED));
}

@Test
public void getRequestTestWithHeaders() throws Exception {
String[] args = {"../"};

TestingProcessManager.TestingProcess process = TestingProcessManager.start(args);
assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED));

// api to check getRequestWithParams
Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") {

private static final long serialVersionUID = 1L;

@Override
protected boolean checkAPIKey(HttpServletRequest req) {
return false;
}

@Override
public String getPath() {
return "/getTestWithHeaders";
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Cookie cookie1 = new Cookie("someValue", "value");
Cookie cookie2 = new Cookie("someValue2", "value2");
resp.setHeader("SomeNameForHeader", "someValueForHeader");
resp.addCookie(cookie1);
resp.addCookie(cookie2);
super.sendTextResponse(200, "200", resp);
}

});

HashMap<String, List<String>> responseHeaders = new HashMap<>();

{
String response = HttpRequest.sendGETRequestWithResponseHeaders(process.getProcess(), "",
"http://localhost:3567/getTestWithHeaders", new HashMap<>(), null, 1000, 1000, null, responseHeaders, true);
assertEquals(response, "200");
assertTrue(responseHeaders.containsKey("SomeNameForHeader"));
assertEquals(responseHeaders.get("SomeNameForHeader"), Collections.singletonList("someValueForHeader"));
assertTrue(responseHeaders.containsKey("Set-Cookie"));
assertEquals(2, responseHeaders.get("Set-Cookie").size());
assertTrue(responseHeaders.get("Set-Cookie").contains("someValue=value"));
assertTrue(responseHeaders.get("Set-Cookie").contains("someValue2=value2"));
}

process.kill();
assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED));
}
}
37 changes: 20 additions & 17 deletions src/test/java/io/supertokens/test/JWKSPublicAPITest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,26 @@

package io.supertokens.test;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import io.supertokens.ProcessState;
import io.supertokens.httpRequest.HttpRequest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import static org.junit.Assert.*;
import io.supertokens.ProcessState;
import io.supertokens.httpRequest.HttpRequest;

public class JWKSPublicAPITest {
@Rule
Expand Down Expand Up @@ -80,33 +83,33 @@ public void testCacheControlValue() throws Exception {
assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED));

// check regular output
Map<String, List<String>> responseHeaders = new HashMap<>();
Map<String, String> responseHeaders = new HashMap<>();
JsonObject response = HttpRequest.sendGETRequestWithResponseHeaders(process.getProcess(), "",
"http://localhost:3567/.well-known/jwks.json", null, new HashMap<>(),
1000, 1000, null, responseHeaders, true);
"http://localhost:3567/.well-known/jwks.json", null,
1000, 1000, null, responseHeaders);

assertEquals(response.entrySet().size(), 1);

assertTrue(response.has("keys"));
JsonArray keys = response.get("keys").getAsJsonArray();
assertEquals(keys.size(), 2);

long maxAge = getMaxAgeValue(responseHeaders.get("Cache-Control").get(0));
long maxAge = getMaxAgeValue(responseHeaders.get("Cache-Control"));
assertTrue(maxAge >= 3538 && maxAge <= 3540);

Thread.sleep(2000);

response = HttpRequest.sendGETRequestWithResponseHeaders(process.getProcess(), "",
"http://localhost:3567/.well-known/jwks.json", null, new HashMap<>(),
1000, 1000, null, responseHeaders, true);
"http://localhost:3567/.well-known/jwks.json", null,
1000, 1000, null, responseHeaders);

assertEquals(response.entrySet().size(), 1);

assertTrue(response.has("keys"));
keys = response.get("keys").getAsJsonArray();
assertEquals(keys.size(), 2);

long newMaxAge = getMaxAgeValue(responseHeaders.get("Cache-Control").get(0));
long newMaxAge = getMaxAgeValue(responseHeaders.get("Cache-Control"));
assertTrue(maxAge - newMaxAge >= 2 && maxAge - newMaxAge <= 3);

process.kill();
Expand Down

0 comments on commit 085e5c1

Please sign in to comment.