/// <summary> /// Sends request to specified url /// </summary> /// <typeparam name="T">Some type for response deserialization</typeparam> /// <param name="jsonRpc">Request body</param> /// <param name="jsonSerializerSettings">Specifies json settings</param> /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param> /// <returns>Typed JsonRpcResponse</returns> public async Task <JsonRpcResponse <T> > ExecuteAsync <T>(IJsonRpcRequest jsonRpc, JsonSerializerSettings jsonSerializerSettings, CancellationToken token) { if (string.IsNullOrEmpty(UrlToConnect)) { return(null); } var stringResponse = string.Empty; try { var response = await RepeatPost(jsonRpc.Message, token, MaxRepeatRequest); response.EnsureSuccessStatusCode(); stringResponse = await response.Content.ReadAsStringAsync(); var prop = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(stringResponse, jsonSerializerSettings); prop.RawRequest = jsonRpc.Message; prop.RawResponse = stringResponse; return(prop); } catch (Exception e) { var resp = new JsonRpcResponse <T>(e) { RawRequest = jsonRpc.Message, RawResponse = stringResponse }; return(resp); } }
public static IJsonRpcRequest Parse(IHttpContext context) { IJsonRpcRequest request = Parse(context.Request); request.HttpContext = context; return(request); }
private async Task <JsonRpcResponse <T> > RepeatExecuteAsync <T>(IJsonRpcRequest jsonRpc, JsonSerializerSettings jsonSerializerSettings, byte loop, CancellationToken token) { if (string.IsNullOrEmpty(UrlToConnect)) { return new JsonRpcResponse <T>(new ArgumentNullException(nameof(UrlToConnect))) { RawRequest = jsonRpc.Message } } ; try { var content = new StringContent(jsonRpc.Message, Encoding.UTF8, "application/json"); var response = await HttpClient.PostAsync(UrlToConnect, content, loop, token).ConfigureAwait(false); var stringResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var prop = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(stringResponse, jsonSerializerSettings); prop.RawRequest = jsonRpc.Message; prop.RawResponse = stringResponse; return(prop); } catch (Exception ex) { return(new JsonRpcResponse <T>(ex) { RawRequest = jsonRpc.Message }); } } }
public JsonRpcResponse Execute(IJsonRpcRequest jsonRpc, CancellationToken token) { SendData(Socket, jsonRpc.Message); var responce = ReceiveData(Socket); var prop = JsonRpcResponse.FromString(responce, _jsonSerializerSettings); return(prop); }
public void ParseRequestWithoutIdShouldReturnNotification() { IRequest request = A.Fake <IRequest>(); A.CallTo <string>(() => request.HttpMethod).Returns("POST"); A.CallTo <Stream>(() => request.InputStream).Returns(GetNotificationStream()); IJsonRpcRequest msg = JsonRpcMessage.Parse(request); Expect.IsInstanceOfType <JsonRpcNotification>(msg); }
public void ParseRequestArrayShouldReturnRpcBatch() { IRequest request = A.Fake <IRequest>(); A.CallTo <string>(() => request.HttpMethod).Returns("POST"); A.CallTo <Stream>(() => request.InputStream).Returns(GetRequestBatch()); IJsonRpcRequest msg = JsonRpcMessage.Parse(request); Expect.IsInstanceOfType <JsonRpcBatch>(msg); }
/// <summary> /// Sends request to specified url /// </summary> /// <typeparam name="T">Some type for response deserialization</typeparam> /// <param name="jsonRpc">Request body</param> /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param> /// <returns>Typed JsonRpcResponse</returns> /// <exception cref="T:System.OperationCanceledException">The token has had cancellation requested.</exception> public JsonRpcResponse <T> Execute <T>(IJsonRpcRequest jsonRpc, CancellationToken token) { if (string.IsNullOrEmpty(_url)) { return(null); } var response = Execute(jsonRpc, token); return(response.ToTyped <T>(_jsonSerializerSettings)); }
protected internal static IJsonRpcRequest Parse(IRequest request) { IJsonRpcRequest result = null; using (StreamReader sr = new StreamReader(request.InputStream)) { string json = sr.ReadToEnd(); result = Parse(json); } return(result); }
protected override bool Post(IHttpContext context) { IJsonRpcRequest request = JsonRpcMessage.Parse(context); bool result = false; if (request != null) { JsonRpcResponse response = request.Execute(); IRenderer renderer = RendererFactory.CreateRenderer(context.Request); renderer.Render(response.GetOutput(), context.Response.OutputStream); } return(result); }
/// <summary> /// Sends request to specified url /// </summary> /// <param name="jsonRpc">Request body</param> /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param> /// <returns>JsonRpcResponse</returns> /// <exception cref="T:System.OperationCanceledException">The token has had cancellation requested.</exception> public JsonRpcResponse Execute(IJsonRpcRequest jsonRpc, CancellationToken token) { var waiter = new ManualResetEvent(false); lock (_manualResetEventDictionary) { _manualResetEventDictionary.Add(jsonRpc.Id, waiter); } if (!OpenIfClosed(token)) { return(new JsonRpcResponse(new SystemError(ErrorCodes.ConnectionTimeoutError))); } Debug.WriteLine($">>> {jsonRpc.Message}"); _webSocket.Send(jsonRpc.Message); WaitHandle.WaitAny(new[] { token.WaitHandle, waiter }, WaitResponceTimeout); lock (_manualResetEventDictionary) { if (_manualResetEventDictionary.ContainsKey(jsonRpc.Id)) { _manualResetEventDictionary.Remove(jsonRpc.Id); } waiter.Dispose(); } JsonRpcResponse response = null; lock (_responseDictionary) { if (_responseDictionary.ContainsKey(jsonRpc.Id)) { response = _responseDictionary[jsonRpc.Id]; _responseDictionary.Remove(jsonRpc.Id); } } token.ThrowIfCancellationRequested(); if (response == null) { return(new JsonRpcResponse(new SystemError(ErrorCodes.ResponseTimeoutError))); } return(response); }
/// <summary> /// Parse the Json as an RpcMessage the /// specific type of the message will depend /// on the json itself as described here http://www.jsonrpc.org/specification /// </summary> /// <returns></returns> protected internal static IJsonRpcRequest Parse(string json) { IJsonRpcRequest result = null; JToken parsed = JToken.Parse(json); JArray batch; if (parsed.Is <JObject>()) { result = ParseRequest(parsed, json); } else if (parsed.Is <JArray>(out batch)) { result = ParseBatch(batch); } return(result); }
public void ParseRequestWithOrderedParams() { IRequest request = A.Fake <IRequest>(); A.CallTo <string>(() => request.HttpMethod).Returns("POST"); A.CallTo <Stream>(() => request.InputStream).Returns(GetRequestWithOrderedParamsStream()); IJsonRpcRequest msg = JsonRpcMessage.Parse(request); Expect.IsInstanceOfType <JsonRpcRequest>(msg); JsonRpcRequest rpcRequest = (JsonRpcRequest)msg; Expect.IsTrue(rpcRequest.RpcParams.Ordered); Expect.IsTrue(rpcRequest.RpcParams.By.Position != null); Expect.IsFalse(rpcRequest.RpcParams.Named); Expect.IsTrue(rpcRequest.RpcParams.By.Name == null); Expect.IsNotNull(rpcRequest.Params); Expect.IsTrue(rpcRequest.Params.Is <JArray>(), "Params should have been a JArray"); }
public void ExecuteOrderedParamsTest() { Incubator inc = new Incubator(); inc.Set(new Echo()); string value = "hello there ".RandomLetters(8); object id = "some value"; string inputString = "{{'jsonrpc': '2.0', 'method': 'Send', 'id': '{0}', 'params': ['{1}']}}"._Format(id, value); IHttpContext context = GetPostContextWithInput(inputString); IJsonRpcRequest parsed = JsonRpcMessage.Parse(context); JsonRpcRequest request = (JsonRpcRequest)parsed; request.Incubator = inc; JsonRpcResponse response = request.Execute(); Expect.IsTrue(response.GetType().Equals(typeof(JsonRpcResponse))); Expect.AreEqual(value, response.Result); Expect.IsNull(response.Error); Expect.AreEqual(id, response.Id); }
/// <summary> /// Sends request to specified url /// </summary> /// <param name="jsonRpc">Request body</param> /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param> /// <returns>JsonRpcResponse</returns> /// <exception cref="T:System.OperationCanceledException">The token has had cancellation requested.</exception> public JsonRpcResponse Execute(IJsonRpcRequest jsonRpc, CancellationToken token) { if (string.IsNullOrEmpty(_url)) { return(null); } var content = new StringContent(jsonRpc.Message); var response = _client.PostAsync(_url, content, token).Result; if (response.StatusCode == HttpStatusCode.OK) { var stringResponse = response.Content.ReadAsStringAsync().Result; var prop = JsonRpcResponse.FromString(stringResponse, _jsonSerializerSettings); return(prop); } return(new JsonRpcResponse { Error = new HttpResponseError((int)response.StatusCode, "Http Error") }); }
/// <summary> /// Sends request to specified url /// </summary> /// <typeparam name="T">Some type for response deserialization</typeparam> /// <param name="jsonRpc">Request body</param> /// <param name="jsonSerializerSettings">Specifies json settings</param> /// <param name="token"></param> /// <returns>Typed JsonRpcResponse</returns> public Task <JsonRpcResponse <T> > ExecuteAsync <T>(IJsonRpcRequest jsonRpc, JsonSerializerSettings jsonSerializerSettings, CancellationToken token) { return(Task.Run(() => { if (!OpenIfClosed(token)) { if (token.IsCancellationRequested) { return new JsonRpcResponse <T>(new OperationCanceledException()) { RawRequest = jsonRpc.Message } } ; return new JsonRpcResponse <T>(new TimeoutException()) { RawRequest = jsonRpc.Message }; } var waiter = new ManualResetEvent(false); lock (_manualResetEventDictionary) { _manualResetEventDictionary.Add(jsonRpc.Id, waiter); } _webSocket.Send(jsonRpc.Message); WaitHandle.WaitAny(new[] { token.WaitHandle, waiter }, WaitResponceTimeout); lock (_manualResetEventDictionary) { if (_manualResetEventDictionary.ContainsKey(jsonRpc.Id)) { _manualResetEventDictionary.Remove(jsonRpc.Id); } waiter.Dispose(); } lock (_responseDictionary) { if (_responseDictionary.ContainsKey(jsonRpc.Id)) { var json = _responseDictionary[jsonRpc.Id]; _responseDictionary.Remove(jsonRpc.Id); var response = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json, jsonSerializerSettings); response.RawResponse = json; response.RawRequest = jsonRpc.Message; return response; } } if (token.IsCancellationRequested) { return new JsonRpcResponse <T>(new OperationCanceledException()) { RawRequest = jsonRpc.Message } } ; return new JsonRpcResponse <T>(new TimeoutException()) { RawRequest = jsonRpc.Message }; }, token)); }
/// <summary> /// Sends request to specified url /// </summary> /// <typeparam name="T">Some type for response deserialization</typeparam> /// <param name="jsonRpc">Request body</param> /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param> /// <returns>Typed JsonRpcResponse</returns> /// <exception cref="T:System.OperationCanceledException">The token has had cancellation requested.</exception> public JsonRpcResponse <T> Execute <T>(IJsonRpcRequest jsonRpc, CancellationToken token) { var response = Execute(jsonRpc, token); return(response.ToTyped <T>(_jsonSerializerSettings)); }
/// <summary> /// Sends request to specified url. /// </summary> /// <typeparam name="T">Some type for response deserialization</typeparam> /// <param name="jsonRpc">Request body</param> /// <param name="jsonSerializerSettings">Specifies json settings</param> /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param> /// <returns>Typed JsonRpcResponse</returns> public async Task <JsonRpcResponse <T> > RepeatExecuteAsync <T>(IJsonRpcRequest jsonRpc, JsonSerializerSettings jsonSerializerSettings, CancellationToken token) { return(await RepeatExecuteAsync <T>(jsonRpc, jsonSerializerSettings, HttpClient.MaxRequestRepeatCount, token).ConfigureAwait(false)); }
public Task<Response> SendRequestAsync(IJsonRpcRequest userJsonRpcRequest) { var jsonRpcRequest = JsonRpcRequest.Factory.CreateJsonRpcRequest(userJsonRpcRequest.GetCommand(), userJsonRpcRequest.GetContent()); var jsonRpcJObject = JObject.FromObject(jsonRpcRequest); var streamCommand = JObjectStreamCommand.Factory.Create(jsonRpcJObject); var requestTaskCompletionSource = new TaskCompletionSource<Response>(); _sendToClientQueue.Enqueue(streamCommand); if (!_incompleteJsonRpcRequests.TryAdd(jsonRpcRequest.Id, requestTaskCompletionSource)) { // this shouldn't throw throw new Exception(); } return requestTaskCompletionSource.Task; }