Skip to content

Commit

Permalink
Merge pull request #753 from chathurabuddi/cherry-pick-from-egw
Browse files Browse the repository at this point in the history
cherry picked EXTGW-626 from EGW
  • Loading branch information
aushaniU authored Jan 18, 2021
2 parents 5d614b5 + c7d437d commit 1d26704
Showing 1 changed file with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@
*/
package com.wso2telco.dep.responsefilter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wso2telco.core.dbutils.DbUtils;
import com.wso2telco.core.dbutils.util.DataSourceNames;
import lk.chathurabuddi.json.schema.constants.FreeFormAction;
Expand Down Expand Up @@ -51,7 +55,9 @@ public boolean mediate(MessageContext messageContext) {
String filterSchema = findFilterSchema(userId, appName, api, httpVerb, resource);
if (filterSchema != null) {
String filteredJson = new JsonSchemaFilter(filterSchema, jsonString, FreeFormAction.DETACH).filter();
JsonUtil.getNewJsonPayload(axis2MessageContext, filteredJson, true, true);
if (isNonEmptyJson(filteredJson) || isMatchingPayload(jsonString, filterSchema)) {
JsonUtil.getNewJsonPayload(axis2MessageContext, filteredJson, true, true);
}
}
}
} catch (Exception e) {
Expand All @@ -61,6 +67,31 @@ public boolean mediate(MessageContext messageContext) {
return true;
}

// compare the root elements of the payload according to the filter schema
private boolean isMatchingPayload(String jsonString, String filterSchema) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(jsonString);
JsonNode schema = mapper.readTree(filterSchema);
String rootElementType = schema.findPath("type").asText();
return !((json.isArray() && !"array".equals(rootElementType)) ||
("object".equals(rootElementType) && !rootElementsMatched(json, schema)));
}

private boolean rootElementsMatched(JsonNode json, JsonNode schema) {
Iterator<String> properties = schema.findPath("properties").fieldNames();
while (properties.hasNext()) {
String property = properties.next();
if (json.has(property)) {
return true;
}
}
return false;
}

private boolean isNonEmptyJson(String filteredJson) {
return filteredJson != null && !filteredJson.isEmpty() && !"{}".equals(filteredJson);
}

public String findFilterSchema(String sp, String application, String api, String httpVerb, String resource) throws Exception {
Connection connection = null;
PreparedStatement statement = null;
Expand Down

0 comments on commit 1d26704

Please sign in to comment.