Skip to content

Commit

Permalink
Merge pull request #40669 from dilanSachi/http-issue
Browse files Browse the repository at this point in the history
[1.2.x] Update query param resolving implementation
  • Loading branch information
dilanSachi authored Jun 14, 2023
2 parents 56ad43c + 8fc4ded commit 61b5351
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public class HttpConstants {
public static final String DEFAULT_INTERFACE = "0.0.0.0:8080";
public static final String DEFAULT_BASE_PATH = "/";
public static final String DEFAULT_SUB_PATH = "/*";
public static final String QUERY_STRING_SEPARATOR = "\\?";

public static final String PROTOCOL_HTTP = "http";
public static final String PROTOCOL_PACKAGE_HTTP = "ballerina" + ORG_NAME_SEPARATOR + "http";
Expand Down Expand Up @@ -440,6 +441,7 @@ public class HttpConstants {
public static final String DOLLAR = "$";
public static final String SINGLE_SLASH = "/";
public static final String REGEX = "(?<!(http:|https:))//";
public static final String EMPTY = "";

public static final String HTTP_VERSION_1_1 = "1.1";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
import java.util.Map;

import static org.ballerinalang.net.http.HttpConstants.DEFAULT_HOST;
import static org.ballerinalang.net.http.HttpConstants.EMPTY;
import static org.ballerinalang.net.http.HttpConstants.QUERY_STRING_SEPARATOR;
import static org.ballerinalang.net.http.compiler.ResourceSignatureValidator.COMPULSORY_PARAM_COUNT;

/**
Expand Down Expand Up @@ -76,32 +78,36 @@ public static HttpService findService(HTTPServicesRegistry servicesRegistry, Htt
inboundReqMsg.setProperty(HttpConstants.TO, uriWithoutMatrixParams);
inboundReqMsg.setProperty(HttpConstants.MATRIX_PARAMS, matrixParams);

URI validatedUri = getValidatedURI(uriWithoutMatrixParams);
String[] rawPathAndQuery = new String[2];
String[] splittedUri = uriWithoutMatrixParams.split(QUERY_STRING_SEPARATOR);
rawPathAndQuery[0] = splittedUri[0];
rawPathAndQuery[1] = splittedUri.length > 1 ? splittedUri[1] : EMPTY;

String basePath = servicesRegistry.findTheMostSpecificBasePath(validatedUri.getRawPath(),
String basePath = servicesRegistry.findTheMostSpecificBasePath(rawPathAndQuery[0],
servicesOnInterface, sortedServiceURIs);

if (basePath == null) {
inboundReqMsg.setHttpStatusCode(404);
throw new BallerinaConnectorException("no matching service found for path : " +
validatedUri.getRawPath());
rawPathAndQuery[0]);
}

HttpService service = servicesOnInterface.get(basePath);
setInboundReqProperties(inboundReqMsg, validatedUri, basePath);
setInboundReqProperties(inboundReqMsg, rawPathAndQuery[0], basePath, rawPathAndQuery[1]);
return service;
} catch (Exception e) {
throw new BallerinaConnectorException(e.getMessage());
}
}

private static void setInboundReqProperties(HttpCarbonMessage inboundReqMsg, URI requestUri, String basePath) {
String subPath = URIUtil.getSubPath(requestUri.getRawPath(), basePath);
private static void setInboundReqProperties(HttpCarbonMessage inboundReqMsg, String rawPath,
String basePath, String rawQuery) {
String subPath = URIUtil.getSubPath(rawPath, basePath);
inboundReqMsg.setProperty(HttpConstants.BASE_PATH, basePath);
inboundReqMsg.setProperty(HttpConstants.SUB_PATH, subPath);
inboundReqMsg.setProperty(HttpConstants.QUERY_STR, requestUri.getQuery());
inboundReqMsg.setProperty(HttpConstants.QUERY_STR, rawQuery);
//store query params comes with request as it is
inboundReqMsg.setProperty(HttpConstants.RAW_QUERY_STR, requestUri.getRawQuery());
inboundReqMsg.setProperty(HttpConstants.RAW_QUERY_STR, rawQuery);
}

public static URI getValidatedURI(String uriStr) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,31 @@ public void testUrlTemplateWithMultipleQueryParamWithURIEncodeCharacterDispatchi
, "RegID variable not set properly.");
}

@Test(description = "Test dispatching with query params.")
public void testUrlTemplateWithQueryParamWithoutURIEncode() {
String path = "/ecommerceservice/productsQueryParam?products={%22p1%22:%22name1%22%2C%22p2%22:%22name2%22}";
HTTPTestRequest cMsg = MessageUtils.generateHTTPMessage(path, "GET");
HttpCarbonMessage response = Services.invoke(TEST_EP_PORT, cMsg);
Assert.assertNotNull(response, "Response message not found");
//Expected Json message : {"Products":{"p1":"name1","p2":"name2"}}
BValue bJson = JsonParser.parse(new HttpMessageDataStreamer(response).getInputStream());
Assert.assertEquals(((BMap<String, BValue>) bJson).get("Products").stringValue(),
"{\"p1\":\"name1\",\"p2\":\"name2\"}", "ProductID variable not set properly.");
}

@Test(description = "Test dispatching with nested json query params.")
public void testUrlTemplateWithNestedJsonQueryParamWithoutURIEncode() {
String path = "/ecommerceservice/productsQueryParam?products={%22products%22:[{%22productOneOf%22:" +
"{%22productId%22:%220123456789%22%2C%22productCategory%22:%22LargeProduct%22}}]}";
HTTPTestRequest cMsg = MessageUtils.generateHTTPMessage(path, "GET");
HttpCarbonMessage response = Services.invoke(TEST_EP_PORT, cMsg);
Assert.assertNotNull(response, "Response message not found");
//Expected Json message : {"Products":{"p1":"name1","p2":"name2"}}
BValue bJson = JsonParser.parse(new HttpMessageDataStreamer(response).getInputStream());
Assert.assertEquals(((BMap<String, BValue>) bJson).get("Products").stringValue(),
"{\"products\":[{\"productOneOf\":{\"productId\":\"0123456789\",\"productCategory\":\"LargeProduct\"}}]}",
"ProductID variable not set properly.");
}

@DataProvider(name = "validUrl")
public static Object[][] validUrl() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,24 @@ service Ecommerce on testEP {
checkpanic caller->respond(res);
}

@http:ResourceConfig {
methods:["GET"],
path:"/productsQueryParam"
}
resource function productsInfo7 (http:Caller caller, http:Request req) {
json responseJson;
map<string[]> params = req.getQueryParams();
string[]? productsArr = params["products"];
string products = productsArr is string[] ? productsArr[0] : "";
io:println ("Products " + products);
responseJson = {"Products": products};
io:println (responseJson.toString ());

http:Response res = new;
res.setJsonPayload(<@untainted json> responseJson);
checkpanic caller->respond(res);
}

@http:ResourceConfig {
path:""
}
Expand Down

0 comments on commit 61b5351

Please sign in to comment.