private byte[] PostRootReturnUpdates(RestRequestParameters restInput, byte[] responseBytes, string responseProperties, out string newResponseProperties) { newResponseProperties = responseProperties; if (responseBytes == null) { return(Encoding.UTF8.GetBytes("{}")); } //reformatting the query response to comform that to the json specs when MapServer?returnUpdate=true IDictionary <string, object> output = new Dictionary <string, object>(); output.Add("timeExtent", null); string originalResponse = System.Text.Encoding.UTF8.GetString(responseBytes); JavaScriptSerializer sr = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue }; var jsonResObj = sr.DeserializeObject(originalResponse) as IDictionary <string, object>; var jsonFeatures = jsonResObj["features"] as object[]; var jsonFeat = jsonFeatures[0] as IDictionary <string, object>; var jsonAttr = jsonFeat["attributes"] as IDictionary <string, object>; var timeExtArray = new Int64[2]; timeExtArray[0] = Convert.ToInt64(jsonAttr["MIN_" + _timeFieldName]); timeExtArray[1] = Convert.ToInt64(jsonAttr["MAX_" + _timeFieldName]); output["timeExtent"] = timeExtArray; string outputJsonStr = sr.Serialize(output); sr = null; return(System.Text.Encoding.UTF8.GetBytes(outputJsonStr)); }
public static void RestRequest(IHttpRequest httpListenerRequest, RestRequestParameters parameters) { //Parameters = parameters; foreach (var key in httpListenerRequest.Query.AllKeys) { if (parameters[key] != null) { throw new Exception("Parameters of same name provided in request"); } parameters[key] = httpListenerRequest.Query[key]; } }
private RestRequestParameters PreRootReturnUpdates(RestRequestParameters restInput) { //redirecting the call to one of the layer's query operation //to compute full time extent very quickly restInput.ResourceName = "layers/" + _liveTimeLayerID; //_queryableLayerID; restInput.OperationName = "query"; //hardcoded json string restInput.OperationInput = string.Format("{{\"outStatistics\": [{{\"statisticType\": \"min\", \"onStatisticField\": \"{0}\"}}, {{\"statisticType\": \"max\", \"onStatisticField\": \"{0}\" }}]}}", _timeFieldName); return(restInput); }
public RestRequestHandler GetRequestHandler(string url, RestMethod method, out RestRequestParameters parameters) { var digestibleUrl = new RestDigestibleUri(url); parameters = new RestRequestParameters(); foreach (var node in m_handlerNodes) { if (node.MatchesUriPattern(digestibleUrl)) { return(node.GetRestRequestHandler(digestibleUrl, method, parameters)); } } return(null); }
private RestRequestParameters PreFilterExport(RestRequestParameters restInput) { JavaScriptSerializer sr = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; var operationInputJson = sr.DeserializeObject(restInput.OperationInput) as IDictionary <string, object>; //Bug: AGOL time-slider does not support time-stamp; it is a time-range always //while for map server, time-range is exlusive from both end; as a result the request goes to the //underline database looks like timeField >= startTime and timeField <= endTime //that makes it to return features for 2 time-steps. //also, on my database, i noticed that executing a query like "timeField = t1" is faster than "timeField >= t1 and timeField <= t2" //Workaround: removing the endTime from the time value. string timeParam = "time"; if (operationInputJson.ContainsKey(timeParam)) { //string timeValues = operationInputJson[timeParam].ToString(); //operationInputJson[timeParam] = timeValues.Split(',')[0]; string timeValues = operationInputJson[timeParam].ToString(); string[] timeValueArray = timeValues.Split(','); //check whether the values are null,null if (timeValueArray[0].Equals("null", StringComparison.CurrentCultureIgnoreCase) && timeValueArray[0].Equals("null", StringComparison.CurrentCultureIgnoreCase)) { operationInputJson[timeParam] = GetDefaultTimeWhenMissing(); } else { operationInputJson[timeParam] = timeValueArray[0]; } } else //when time is not passed in, use the time instant closest to NOW and draw features only for that time instant { operationInputJson.Add(timeParam, GetDefaultTimeWhenMissing()); } if (operationInputJson.ContainsKey("layers")) { operationInputJson["layers"] = ""; } restInput.OperationInput = sr.Serialize(operationInputJson); return(restInput); }
private byte[] FilterRESTRequest( RestHandlerOpCode opCode, RestRequestParameters restInput, out string responseProperties) { try { responseProperties = null; IRESTRequestHandler restRequestHandler = _restServiceSOI.FindRequestHandlerDelegate <IRESTRequestHandler>(); if (restRequestHandler == null) { throw new RestErrorException("Service handler not found"); } RestFilter restFilterOp = _restServiceSOI.GetFilter(opCode); if (null != restFilterOp && null != restFilterOp.PreFilter) { restInput = restFilterOp.PreFilter(restInput); } byte[] response = restRequestHandler.HandleRESTRequest(restInput.Capabilities, restInput.ResourceName, restInput.OperationName, restInput.OperationInput, restInput.OutputFormat, restInput.RequestProperties, out responseProperties); if (null == restFilterOp || null == restFilterOp.PostFilter) { return(response); } string newResponseProperties; var newResponse = restFilterOp.PostFilter(restInput, response, responseProperties, out newResponseProperties); responseProperties = newResponseProperties; return(newResponse); } catch (RestErrorException restException) { // pre- or post- filters can throw restException with the error JSON output in the Message property. // we catch them here and return JSON response. responseProperties = "{\"Content-Type\":\"text/plain;charset=utf-8\"}"; //catch and return a JSON error from the pre- or postFilter. return(System.Text.Encoding.UTF8.GetBytes(restException.Message)); } }
public byte[] HandleRESTRequest(string capabilities, string resourceName, string operationName, string operationInput, string outputFormat, string requestProperties, out string responseProperties) { try { responseProperties = null; _serverLog.LogMessage(ServerLogger.msgType.infoStandard, _soiName + ".HandleRESTRequest()", 200, "Request received in Layer Access SOI for handleRESTRequest"); var restInput = new RestRequestParameters { Capabilities = capabilities, ResourceName = resourceName, OperationName = operationName, OperationInput = operationInput, OutputFormat = outputFormat, RequestProperties = requestProperties }; //checking for 'returnUpdates at the root resources bool isAskingForReturnUpdates = false; if (restInput.OperationName == "") //((restInput.ResourceName == "") && (restInput.OperationName == "")) { JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue }; var inputJson = js.DeserializeObject(restInput.OperationInput) as IDictionary <string, object>; isAskingForReturnUpdates = inputJson.ContainsKey("returnUpdates"); js = null; } var opCode = GetHandlerOpCode(restInput.ResourceName, restInput.OperationName, isAskingForReturnUpdates); return(FilterRESTRequest(opCode, restInput, out responseProperties)); } catch (Exception e) { _serverLog.LogMessage(ServerLogger.msgType.error, _soiName + ".HandleRESTRequest()", 500, "Exception: " + e.Message + " in " + e.StackTrace); throw; } }
private HttpResponse processRequest(IHttpRequest req) { RestRequestParameters Parameters = new RestRequestParameters(); HttpRequestExtensions.RestRequest(req, Parameters); object obj = new JsonResponse(""); if (Parameters["trama"] != null) { ManagerDeviceProvider manager = new ManagerDeviceProvider(); manager.UDeviceProvider_OnDataReceived(Parameters["trama"]); LogFile.saveRegistro("SentByHand: " + Parameters["trama"], levels.debug); } if (Parameters["type"] != null && Parameters["type"] == "date") { obj = getShiolEvents(Parameters["date"]); } return(new JsonResponse(obj)); //new TextResponse(req.Query.GetValues(0).GetValue(0).ToString()); }
private RestRequestParameters PreFilterLayerQuery(RestRequestParameters restInput) { //redirecting all query calls to the one specific layer //and limiting to return only 1 stream with hightest streamOrder by default restInput.ResourceName = "layers/" + _queryableLayerID; JavaScriptSerializer sr = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue }; var jsonInputObj = sr.DeserializeObject(restInput.OperationInput) as IDictionary <string, object>; string timeParam = "time"; if (jsonInputObj.ContainsKey(timeParam)) { //string timeValues = jsonInputObj[timeParam].ToString(); //jsonInputObj[timeParam] = timeValues.Split(',')[0]; string timeValues = jsonInputObj[timeParam].ToString(); string[] timeValueArray = timeValues.Split(','); //check whether the values are null,null if (timeValueArray[0].Equals("null", StringComparison.CurrentCultureIgnoreCase) && timeValueArray[0].Equals("null", StringComparison.CurrentCultureIgnoreCase)) { jsonInputObj[timeParam] = GetDefaultTimeWhenMissing(); } else { jsonInputObj[timeParam] = timeValueArray[0]; } } else //when time is not passed in, use the time instant closest to NOW and draw features only for that time instant { jsonInputObj.Add(timeParam, GetDefaultTimeWhenMissing()); } //it is not meant to override user's inputs for OrderBy and ResultRecordCount //only adding defaults when user does not specify those parameters string orderByParam = "orderByFields"; if (jsonInputObj.ContainsKey(orderByParam)) { if (jsonInputObj[orderByParam].ToString().Trim() == "") { jsonInputObj[orderByParam] = _defaultOrderBy; } } else { jsonInputObj.Add(orderByParam, _defaultOrderBy); } string resultRecCountParam = "resultRecordCount"; if (jsonInputObj.ContainsKey(resultRecCountParam)) { if (jsonInputObj[resultRecCountParam].ToString().Trim() == "") { jsonInputObj[resultRecCountParam] = _defaultResultRecordCount; } } else { jsonInputObj.Add(resultRecCountParam, _defaultResultRecordCount); } //Note: since as of today (5/25/2016) field list from layer (where features are combined and generalized) does not match with // the bottm layer with detail streams, i'm always setting outFields to '*' // it's a temporay workaround if (jsonInputObj.ContainsKey("outFields")) { jsonInputObj["outFields"] = "*"; } restInput.OperationInput = sr.Serialize(jsonInputObj); sr = null; return(restInput); }
protected override void HandleParameters(RestDigestibleUri uri, RestRequestParameters parameters) { parameters[m_parameterName] = uri.GetCurrentNode(); }
protected override void HandleParameters(RestDigestibleUri uri, RestRequestParameters parameters) { }
/// <summary> /// /// </summary> /// <param name="restInput"></param> /// <param name="authorizedLayers"></param> /// <returns></returns> private RestRequestParameters PreFilterLayerQuery ( RestRequestParameters restInput) { JavaScriptSerializer sr = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; var operationInputJson = sr.DeserializeObject(restInput.OperationInput) as IDictionary<string, object>; var resName = restInput.ResourceName.TrimStart('/'); var rnameParts = resName.Split('/'); var requestedLayerId = rnameParts[1]; if (!_authorizedLayerSet.Contains(requestedLayerId)) { var errorReturn = new Dictionary<string, object> { {"error", new Dictionary<string, object> { {"code", 404}, {"message", "Access Denied"} } } }; throw new RestErrorException(sr.Serialize(errorReturn)); } restInput.OperationInput = sr.Serialize(operationInputJson); return restInput; }
/// <summary> /// /// </summary> /// <param name="restInput"></param> /// <param name="authorizedLayers"></param> /// <returns></returns> private RestRequestParameters PreFilterIdentify ( RestRequestParameters restInput ) { JavaScriptSerializer sr = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; var operationInputJson = sr.DeserializeObject(restInput.OperationInput) as IDictionary<string, object>; String requestedLayers = operationInputJson.ContainsKey("layers") ? operationInputJson["layers"].ToString() : ""; if (string.IsNullOrEmpty(requestedLayers) || requestedLayers.StartsWith("top") || requestedLayers.StartsWith("all")) { operationInputJson["layers"] = "visible:" + _authorizedLayerSet; } else if (requestedLayers.StartsWith("visible")) { var reqLayerParts = requestedLayers.Split(':'); var removeSpacesRegEx = new Regex("\\s+"); operationInputJson["layers"] = "visible:" + RemoveUnauthorizedLayersFromRequestedLayers( removeSpacesRegEx.Replace(reqLayerParts[1], ""), _authorizedLayerSet); } else { operationInputJson["layers"] = "visible:" + _authorizedLayerSet; } restInput.OperationInput = sr.Serialize(operationInputJson); return restInput; }
/// <summary> /// /// </summary> /// <param name="restInput"></param> /// <param name="authorizedLayers"></param> /// <returns></returns> private RestRequestParameters PreFilterFindAndKml ( RestRequestParameters restInput) { JavaScriptSerializer sr = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; var operationInputJson = sr.DeserializeObject(restInput.OperationInput) as IDictionary<string, object>; var removeSpacesRegEx = new Regex("\\s+"); String requestedLayers = operationInputJson.ContainsKey("layers") ? operationInputJson["layers"].ToString() : ""; requestedLayers = removeSpacesRegEx.Replace(requestedLayers, ""); operationInputJson["layers"] = RemoveUnauthorizedLayersFromRequestedLayers(requestedLayers, _authorizedLayerSet); restInput.OperationInput = sr.Serialize(operationInputJson); return restInput; }
/// <summary> /// /// </summary> /// <param name="restInput"></param> /// <param name="authorizedLayers"></param> /// <returns></returns> private RestRequestParameters PreFilterExport ( RestRequestParameters restInput ) { JavaScriptSerializer sr = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; var operationInputJson = sr.DeserializeObject(restInput.OperationInput) as IDictionary<string, object>; operationInputJson["layers"] = "show:" + String.Join(",", _authorizedLayerSet); restInput.OperationInput = sr.Serialize(operationInputJson); return restInput; }
/// <summary> /// /// </summary> /// <param name="capabilities"></param> /// <param name="resourceName"></param> /// <param name="operationName"></param> /// <param name="operationInput"></param> /// <param name="outputFormat"></param> /// <param name="requestProperties"></param> /// <param name="responseProperties"></param> /// <returns></returns> public byte[] HandleRESTRequest ( string capabilities, string resourceName, string operationName, string operationInput, string outputFormat, string requestProperties, out string responseProperties ) { try { responseProperties = null; _serverLog.LogMessage(ServerLogger.msgType.infoStandard, _soiName + ".HandleRESTRequest()", 200, "Request received in Layer Access SOI for handleRESTRequest"); _authorizedLayerSet = GetAuthorizedLayers(_restServiceSOI); var restInput = new RestRequestParameters { Capabilities = capabilities, ResourceName = resourceName, OperationName = operationName, OperationInput = operationInput, OutputFormat = outputFormat, RequestProperties = requestProperties }; var opCode = GetHandlerOpCode(restInput.ResourceName, restInput.OperationName); return FilterRESTRequest(opCode, restInput, out responseProperties); } catch (Exception e) { _serverLog.LogMessage(ServerLogger.msgType.error, _soiName + ".HandleRESTRequest()", 500, "Exception: " + e.Message + " in " + e.StackTrace); throw; } }
/// <summary> /// /// </summary> /// <param name="restFilterOp"></param> /// <param name="restInput"></param> /// <param name="authorizedLayers"></param> /// <param name="responseProperties"></param> /// <returns></returns> private byte[] FilterRESTRequest ( RestHandlerOpCode opCode, RestRequestParameters restInput, out string responseProperties ) { try { responseProperties = null; IRESTRequestHandler restRequestHandler = _restServiceSOI.FindRequestHandlerDelegate<IRESTRequestHandler>(); if (restRequestHandler == null) throw new RestErrorException("Service handler not found"); RestFilter restFilterOp = _restServiceSOI.GetFilter(opCode); if (null != restFilterOp && null != restFilterOp.PreFilter) restInput = restFilterOp.PreFilter(restInput); byte[] response = restRequestHandler.HandleRESTRequest(restInput.Capabilities, restInput.ResourceName, restInput.OperationName, restInput.OperationInput, restInput.OutputFormat, restInput.RequestProperties, out responseProperties); if (null == restFilterOp || null == restFilterOp.PostFilter) return response; string newResponseProperties; var newResponse = restFilterOp.PostFilter(restInput, response, responseProperties, out newResponseProperties); responseProperties = newResponseProperties; return newResponse; } catch (RestErrorException restException) { // pre- or post- filters can throw restException with the error JSON output in the Message property. // we catch them here and return JSON response. responseProperties = "{\"Content-Type\":\"text/plain;charset=utf-8\"}"; //catch and return a JSON error from the pre- or postFilter. return System.Text.Encoding.UTF8.GetBytes(restException.Message); } }
private byte[] PostFilterRESTRoot(RestRequestParameters restInput, byte[] responseBytes, string responseProperties, out string newResponseProperties) { newResponseProperties = responseProperties; string originalResponse = System.Text.Encoding.UTF8.GetString(responseBytes); JavaScriptSerializer sr = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue }; var jsonResObj = sr.DeserializeObject(originalResponse) as IDictionary <string, object>; var contentsJO = jsonResObj["contents"] as IDictionary <string, object>; //modifying light version of 'Layers' resources var layersJA = contentsJO["layers"] as object[]; //var jsLightLayer = layersJA[0] as IDictionary<string, object>; var jsLightLayer = layersJA.FirstOrDefault(j => { var d = j as Dictionary <string, object>; return(_queryableLayerID.Equals(d["id"].ToString())); }) as IDictionary <string, object>; jsLightLayer["minScale"] = 0; jsLightLayer["maxScale"] = 0; contentsJO["layers"] = new object[] { jsLightLayer }; //only returning the very first layer //modifying All Layer Resources var allResourcesJA = jsonResObj["resources"] as object[]; var layersRJO = allResourcesJA.FirstOrDefault(e => { var jo = e as IDictionary <string, object>; if (!jo.ContainsKey("name")) { return(false); } var name = jo["name"].ToString(); return("layers" == name); }) as IDictionary <string, object>; var layerResourceJA = layersRJO["resources"] as object[]; //we need to return only the first layer and remove visibility scale range from there. //var jsDetailLayer = layerResourceJA[0] as IDictionary<string, object>; //returning only the layer with detail streams i.e. the layerId = _querableLayerID var jsDetailLayer = layerResourceJA.FirstOrDefault(j => { var d = j as Dictionary <string, object>; var jsContent = d["contents"] as IDictionary <string, object>; return(_queryableLayerID.Equals(jsContent["id"].ToString(), StringComparison.CurrentCultureIgnoreCase)); }) as IDictionary <string, object>; var jsDetailLyrContent = jsDetailLayer["contents"] as IDictionary <string, object>; jsDetailLyrContent["minScale"] = 0; jsDetailLyrContent["maxScale"] = 0; layersRJO["resources"] = new object[] { jsDetailLayer }; //updating the queryableLayer's and root's timeExtent with the timeExtent from the very first layer //this is due to a bug in map server that makes the service to take really long time to compute a layer (when 1:M joined to a pretty large table) time's extent var jsDetailLayer0 = layerResourceJA[0] as IDictionary <string, object>; //the first layer var jsDetailLyrContent0 = jsDetailLayer0["contents"] as IDictionary <string, object>; var jsTimeInfoLyr0 = jsDetailLyrContent0["timeInfo"] as IDictionary <string, object>; //the timeInfor from the very first layer //var jsTimeExtentLyr0 = jsTimeInfoLyr0["timeExtent"] as object[]; var jsDetailLyrTimeInfo = jsDetailLyrContent["timeInfo"] as IDictionary <string, object>; jsDetailLyrTimeInfo["timeExtent"] = jsTimeInfoLyr0["timeExtent"]; //var jsDetailLyrTimeExtent = jsDetailLyrTimeInfo["timeExtent"] as object[]; //jsDetailLyrTimeExtent[0] = jsTimeExtentLyr0[0]; //jsDetailLyrTimeExtent[1] = jsTimeExtentLyr0[1]; //update time extent for the root resources var jsTimeInfoRoot = contentsJO["timeInfo"] as IDictionary <string, object>; jsTimeInfoRoot["timeExtent"] = jsTimeInfoLyr0["timeExtent"]; _defaultTimeInterval = (int)jsTimeInfoRoot["defaultTimeInterval"]; _defaultTimeIntervalUnits = (esriTimeUnits)Enum.Parse(typeof(esriTimeUnits), (string)jsTimeInfoRoot["defaultTimeIntervalUnits"]); //var jsTimeExtentRoot = jsTimeInfoRoot["timeExtent"] as object[]; //jsTimeExtentRoot[0] = jsTimeExtentLyr0[0]; //jsTimeExtentRoot[1] = jsTimeExtentLyr0[1]; //modifying legends var legendRJO = allResourcesJA.FirstOrDefault(e => { var jo = e as IDictionary <string, object>; if (!jo.ContainsKey("name")) { return(false); } var name = jo["name"].ToString(); return("legend" == name); }) as IDictionary <string, object>; var jsLegendLyrContent = legendRJO["contents"] as IDictionary <string, object>; var jsLgdLayers = jsLegendLyrContent["layers"] as object[]; //var jsLgdLyr = jsLgdLayers[0] as IDictionary<string, object>; var jsLgdLyr = jsLgdLayers.FirstOrDefault(j => { var d = j as Dictionary <string, object>; return(_queryableLayerID.Equals(d["layerId"].ToString(), StringComparison.CurrentCultureIgnoreCase)); }) as IDictionary <string, object>; jsLgdLyr["minScale"] = 0; jsLgdLyr["maxScale"] = 0; if (_customLegend != null) { jsLgdLyr["legend"] = _customLegend; //GetCustomLegend(); } jsLegendLyrContent["layers"] = new object[] { jsLgdLyr }; return(System.Text.Encoding.UTF8.GetBytes(sr.Serialize(jsonResObj))); }
/// <summary> /// /// Filter REST root service info response. /// IMPORTANT: the JSON structure returned by the REST handler root resource /// differs from what you usually see as the response from the service REST endpoint. /// /// </summary> /// <param name="restInput"></param> /// <param name="originalResponse"></param> /// <param name="authorizedLayerSet"></param> /// <returns>Filtered json</returns> private byte[] PostFilterRESTRoot (RestRequestParameters restInput, byte[] responseBytes, string responseProperties, out string newResponseProperties) { //modify these later as needed newResponseProperties = responseProperties; if (null == _authorizedLayerSet) return null; //Just returning null for brevity. In real production code, return error JSON and set proper responseProperties. //restInput is not used here, but may be used later as needed try { // Perform JSON filtering // Note: The JSON syntax can change and you might have to adjust this piece of code accordingly String originalResponse = System.Text.Encoding.UTF8.GetString(responseBytes); /* * Remove unauthorized layer information from 1. Under 'contents' tag 2. Under 'resources' tag * 2.1 'layers' 2.2 'tables' 2.3 'legend' */ JavaScriptSerializer sr = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; var jsonResObj = sr.DeserializeObject(originalResponse) as IDictionary<string, object>; // Filter for 'contents' tag var contentsJO = jsonResObj["contents"] as IDictionary<string, object>; var layersJA = contentsJO["layers"] as object[]; var updatedLayers = new List<object>(); foreach (var layerO in layersJA) { var layerJO = layerO as IDictionary<string, object>; var id = layerJO["id"].ToString(); if (_authorizedLayerSet.Contains(id)) { updatedLayers.Add(layerJO); } } contentsJO["layers"] = updatedLayers.ToArray(); // Filter for 'resources' tag, very simplified filtering, may fail if ordering changes var allResourcesJA = jsonResObj["resources"] as object[]; var layersRJO = allResourcesJA.FirstOrDefault(e => { var jo = e as IDictionary<string, object>; if (!jo.ContainsKey("name")) return false; var name = jo["name"].ToString(); return ("layers" == name); }) as IDictionary<string, object>; var tablesRJO = allResourcesJA.FirstOrDefault(e => { var jo = e as IDictionary<string, object>; if (!jo.ContainsKey("name")) return false; var name = jo["name"].ToString(); return ("tables" == name); }) as IDictionary<string, object>; var legendRJO = allResourcesJA.FirstOrDefault(e => { var jo = e as IDictionary<string, object>; if (!jo.ContainsKey("name")) return false; var name = jo["name"].ToString(); return ("legend" == name); }) as IDictionary<string, object>; //filter and replace layers var filteredLayerResourceJA = new List<object>(); if (null != layersRJO) { // Filter for 'resources -> layers -> resources' tag var layerResourceJA = layersRJO["resources"] as object[]; foreach (var lrJO in layerResourceJA) { var lrJODict = lrJO as IDictionary<string, object>; if (_authorizedLayerSet.Contains(lrJODict["name"].ToString())) { filteredLayerResourceJA.Add(lrJO); } } } layersRJO["resources"] = filteredLayerResourceJA.ToArray(); //filter and replace tables var filteredTableResourceJA = new List<object>(); if (null != tablesRJO) { // Filter for 'resources -> tables -> resources' tag var tableResourceJA = tablesRJO["resources"] as object[]; foreach (var tbJO in tableResourceJA) { var tbJODict = tbJO as IDictionary<string, object>; if (_authorizedLayerSet.Contains(tbJODict["name"].ToString())) { filteredTableResourceJA.Add(tbJO); } } } tablesRJO["resources"] = filteredTableResourceJA.ToArray(); //filter and replace legend layers var filteredLegendLayersRJA = new List<object>(); if (null != legendRJO) { // Filter for 'resources -> legend -> contents->layers' tag var legendContentsJO = legendRJO["contents"] as IDictionary<string, object>; var legendLayersJA = legendContentsJO["layers"] as object[]; foreach (var lgJO in legendLayersJA) { var lgJODict = lgJO as IDictionary<string, object>; if (_authorizedLayerSet.Contains(lgJODict["layerId"].ToString())) { filteredLegendLayersRJA.Add(lgJO); } } legendContentsJO["layers"] = filteredLegendLayersRJA.ToArray(); } // Return the filter response return System.Text.Encoding.UTF8.GetBytes(sr.Serialize(jsonResObj)); } catch (Exception ignore) { return null; } }
public RestRequestHandler GetRestRequestHandler(RestDigestibleUri uri, RestMethod method, RestRequestParameters parameters) { HandleParameters(uri, parameters); if (uri.IsLastNode || this is WildCardUriRequestHandlerNode) { switch (method) { case RestMethod.GET: return(HttpGetRequestHandler); case RestMethod.POST: return(HttpPostRequestHandler); default: throw new ApplicationException("Unknown REST method."); } } uri.NextNode(); foreach (var childNode in ChildNodes) { if (childNode.MatchesUriPattern(uri)) { return(childNode.GetRestRequestHandler(uri, method, parameters)); } } return(null); }
/// <summary> /// /// </summary> /// <param name="restInput"></param> /// <param name="originalResponse"></param> /// <param name="authorizedLayerSet"></param> /// <returns></returns> private byte[] PostFilterRootLegend(RestRequestParameters restInput, byte[] responseBytes, string responseProperties, out string newResponseProperties) { //modify these later as needed newResponseProperties = responseProperties; if (null == _authorizedLayerSet) return null; //Just returning null for brevity. In real production code, return error JSON and set proper responseProperties. //restInput is not used here, but may be used later as needed try { // Perform JSON filtering // Note: The JSON syntax can change and you might have to adjust this piece of code accordingly /* * Remove unauthorized layer information from 1. Under 'contents' tag 2. Under 'resources' tag * 2.1 'layers' 2.2 'tables' 2.3 'legend' */ string originalResponse = System.Text.Encoding.UTF8.GetString(responseBytes); JavaScriptSerializer sr = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; var jsonResObj = sr.DeserializeObject(originalResponse) as IDictionary<string, object>; // Filter for 'contents' tag var layersJA = jsonResObj["layers"] as object[]; var updatedLayers = new List<object>(); foreach (var layerO in layersJA) { var layerJO = layerO as IDictionary<string, object>; var id = layerJO["layerId"].ToString(); if (_authorizedLayerSet.Contains(id)) { updatedLayers.Add(layerJO); } } jsonResObj["layers"] = updatedLayers.ToArray(); // Return the filter response return System.Text.Encoding.UTF8.GetBytes(sr.Serialize(jsonResObj)); } catch (Exception ignore) { return null; } }
protected abstract void HandleParameters(RestDigestibleUri uri, RestRequestParameters parameters);