Skip to content

Commit

Permalink
Add parse method for parse ApiPredicateItem from json string in Updat…
Browse files Browse the repository at this point in the history
…eGatewayApiDefinitionGroupCommandHandler
  • Loading branch information
cdfive authored and sczyh30 committed Jul 10, 2019
1 parent 817a41d commit eda7fdc
Showing 1 changed file with 33 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,21 @@

import java.net.URLDecoder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.command.CommandHandler;
import com.alibaba.csp.sentinel.command.CommandRequest;
import com.alibaba.csp.sentinel.command.CommandResponse;
import com.alibaba.csp.sentinel.command.annotation.CommandMapping;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
* @author Eric Zhao
Expand All @@ -52,10 +56,36 @@ public CommandResponse<String> handle(CommandRequest request) {
RecordLog.info("[API Server] Receiving data change (type: gateway API definition): {0}", data);

String result = SUCCESS_MSG;
List<ApiDefinition> apiDefinitions = JSONArray.parseArray(data, ApiDefinition.class);
GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<>(apiDefinitions));

Set<ApiDefinition> apiDefinitions = parseJson(data);
GatewayApiDefinitionManager.loadApiDefinitions(apiDefinitions);

return CommandResponse.ofSuccess(result);
}

private static final String SUCCESS_MSG = "success";

/**
* Parse json data to set of {@link ApiDefinition}.
*
* Since the predicateItems of {@link ApiDefinition} is set of interface,
* here we parse predicateItems to {@link ApiPathPredicateItem} temporarily.
*/
private Set<ApiDefinition> parseJson(String data) {
Set<ApiDefinition> apiDefinitions = new HashSet<>();
JSONArray array = JSON.parseArray(data);
for (Object obj : array) {
JSONObject o = (JSONObject)obj;
ApiDefinition apiDefinition = new ApiDefinition((o.getString("apiName")));
Set<ApiPredicateItem> predicateItems = new HashSet<>();
JSONArray itemArray = o.getJSONArray("predicateItems");
if (itemArray != null) {
predicateItems.addAll(itemArray.toJavaList(ApiPathPredicateItem.class));
}
apiDefinition.setPredicateItems(predicateItems);
apiDefinitions.add(apiDefinition);
}

return apiDefinitions;
}
}

0 comments on commit eda7fdc

Please sign in to comment.