JsonClient.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Text;
  9. using InABox.Core;
  10. using RestSharp;
  11. //using InABox.Logging;
  12. namespace InABox.Clients
  13. {
  14. public class CompressedResponse
  15. {
  16. public CompressedResponse()
  17. {
  18. Headers = new Dictionary<string, string>();
  19. Options = new Dictionary<string, string>();
  20. }
  21. public string ContentType { get; set; }
  22. public Dictionary<string, string> Headers { get; set; }
  23. public int Status { get; set; }
  24. public string StatusCode { get; set; }
  25. public string Response { get; set; }
  26. public Dictionary<string, string> Options { get; set; }
  27. }
  28. public class JsonClient<TEntity> : RemoteClient<TEntity> where TEntity : Entity, new()
  29. {
  30. private readonly bool _compression = true;
  31. public JsonClient(string url, int port, bool useSimpleEncryption, bool compression) : base(url, port, useSimpleEncryption)
  32. {
  33. _compression = compression;
  34. }
  35. public JsonClient(string url, int port, bool useSimpleEncryption) : this(url, port, useSimpleEncryption, true)
  36. {
  37. }
  38. public JsonClient(string url, int port) : this(url, port, false, true)
  39. {
  40. }
  41. //private static void CheckSecuritySettings()
  42. //{
  43. // Boolean platformSupportsTls12 = false;
  44. // foreach (SecurityProtocolType protocol in Enum.GetValues(typeof(SecurityProtocolType)))
  45. // platformSupportsTls12 = platformSupportsTls12 || (protocol.GetHashCode() == 3072);
  46. // if (!ServicePointManager.SecurityProtocol.HasFlag((SecurityProtocolType)3072) && platformSupportsTls12)
  47. // ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
  48. // if (ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Ssl3))
  49. // System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
  50. //}
  51. protected override TResponse SendRequest<TRequest, TResponse>(TRequest request, string Action, bool includeEntity = true)
  52. {
  53. //DateTime now = DateTime.Now;
  54. //Log(" * {0}{1}() Starting..", Action, typeof(TEntity).Name);
  55. //Stopwatch sw = new Stopwatch();
  56. //sw.Start();
  57. //CheckSecuritySettings();
  58. var result = default(TResponse);
  59. long length = 0;
  60. if (string.IsNullOrEmpty(URL))
  61. {
  62. result = (TResponse)Activator.CreateInstance(typeof(TResponse));
  63. result.Status = StatusCode.BadServer;
  64. result.Messages.Add("Server URL not set!");
  65. return result;
  66. }
  67. //sw.Restart();
  68. var json = Serialization.Serialize(request);
  69. var deserialized = Serialization.Deserialize<TRequest>(json);
  70. //Log(" * {0}{1}() Serializing data took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, json.Length);
  71. //sw.Restart();
  72. var uri = new Uri(string.Format("{0}:{1}", URL, Port));
  73. var cli = new RestClient(uri);
  74. var cmd = string.Format(
  75. "{0}{1}?format=json{2}",
  76. Action,
  77. includeEntity ? typeof(TEntity).Name : "",
  78. ""
  79. );
  80. var req = new RestRequest(cmd, Method.POST)
  81. {
  82. Timeout = Timeout.Milliseconds
  83. };
  84. //Log(" * {0}{1}() Creating Uri, Client and RestRequest took {2}ms", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds);
  85. //sw.Restart();
  86. req.AdvancedResponseWriter = (stream, response) =>
  87. {
  88. //Log(" * {0}{1}() Response from Server took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, response.ContentLength);
  89. //length = response.ContentLength;
  90. //sw.Restart();
  91. //var str = new StreamReader(stream);//.ReadToEnd();
  92. try
  93. {
  94. result = Serialization.Deserialize<TResponse>(stream, true);
  95. }
  96. catch (Exception e)
  97. {
  98. Logger.Send(LogType.Information, "", $"Error deserializing response: {e.Message}");
  99. }
  100. //Log(" * {0}{1}() Deserializing Stream took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, response.ContentLength);
  101. };
  102. //result = new TResponse();
  103. req.AddOrUpdateParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
  104. req.RequestFormat = DataFormat.Json;
  105. try
  106. {
  107. //sw.Restart();
  108. var res = cli.Execute(req);
  109. //Log(" * {0}{1}() returns {2} bytes in {3}ms", Action, typeof(TEntity).Name, res.ContentLength, sw.ElapsedMilliseconds);
  110. if (result == null)
  111. {
  112. if (res.ErrorException == null)
  113. {
  114. if (res.StatusCode != HttpStatusCode.OK)
  115. throw new Exception(String.Format("HTTP Request returns {0} {1}" + (int)res.StatusCode, CoreUtils.SplitCamelCase(res.StatusCode.ToString())));
  116. try
  117. {
  118. var data = "";
  119. if (_compression)
  120. {
  121. //sw.Restart();
  122. var comp = Serialization.Deserialize<CompressedResponse>(res.Content, true);
  123. var bytes = Convert.FromBase64String(comp.Response);
  124. var ms = new MemoryStream(bytes);
  125. using (var resultDeCompressedStream = new MemoryStream())
  126. {
  127. using (var decompressionStream = new DeflateStream(ms, CompressionMode.Decompress))
  128. {
  129. decompressionStream.CopyTo(resultDeCompressedStream);
  130. data = Encoding.UTF8.GetString(resultDeCompressedStream.ToArray(), 0,
  131. Convert.ToInt32(resultDeCompressedStream.Length));
  132. }
  133. }
  134. //Log(" * {0}{1}() Decompressing {2} -> {3} ({4:F2}%) bytes took {5}ms", Action, typeof(TEntity).Name, res.ContentLength, data.Length, ((double)data.Length *100.0F / (double)res.ContentLength), sw.ElapsedMilliseconds);
  135. }
  136. else
  137. {
  138. data = res.Content;
  139. }
  140. //sw.Restart();
  141. result = Serialization.Deserialize<TResponse>(data, true);
  142. //Log(" * {0}{1}() Deserializing data took {2}ms", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds);
  143. //sw.Stop();
  144. }
  145. catch (Exception eDeserialize)
  146. {
  147. throw new Exception(string.Format("Unable to deserialize response!\n\n{0}\n\n{1}", eDeserialize.Message, res.Content));
  148. }
  149. }
  150. else
  151. {
  152. // Connectivity
  153. result = new TResponse();
  154. result.Status = StatusCode.BadServer;
  155. result.Messages.Add(res.ErrorMessage);
  156. }
  157. }
  158. }
  159. catch (Exception err)
  160. {
  161. result = new TResponse();
  162. result.Status = StatusCode.BadServer;
  163. result.Messages.Add(err.Message);
  164. if (err.InnerException != null)
  165. result.Messages.Add("- " + err.InnerException.Message);
  166. }
  167. req = null;
  168. cli = null;
  169. //double elapsed = (DateTime.Now - now).TotalMilliseconds;
  170. //Log(" * {0}{1}() completed in {2:F0}ms", Action, typeof(TEntity).Name, elapsed);
  171. return result;
  172. }
  173. // SupportedTypes() function fallback for if the server is running on ServiceStack
  174. private void SupportedTypesOld(RestClient cli, List<string> result)
  175. {
  176. var req = new RestRequest("/operations/metadata?format=csv", Method.GET) { Timeout = 20000 };
  177. try
  178. {
  179. var res = cli.Execute(req);
  180. if (res.ErrorException == null)
  181. {
  182. var lines = res.Content.Split('\n').Skip(1);
  183. foreach (var line in lines)
  184. {
  185. var fields = line.Split(',');
  186. var svc = fields[2];
  187. if (!result.Contains(svc)) result.Add(svc);
  188. //if (svc.Equals("Comal_Classes_Login"))
  189. // result.Add("InABox_Core_Login");
  190. }
  191. }
  192. }
  193. catch (Exception e)
  194. {
  195. }
  196. req = null;
  197. cli = null;
  198. }
  199. // This code is duplicated in InABox.Clients.Remote.MsgPack
  200. // This should stay as-is, and work to remove RestSharp from MsgPack Client
  201. public override IEnumerable<string> SupportedTypes()
  202. {
  203. var result = new List<string>();
  204. var uri = new Uri(string.Format("{0}:{1}", URL, Port));
  205. var cli = new RestClient(uri);
  206. var req = new RestRequest("/classes", Method.GET) { Timeout = 20000 };
  207. try
  208. {
  209. var res = cli.Execute(req);
  210. if (res.StatusCode != HttpStatusCode.OK)
  211. {
  212. SupportedTypesOld(cli, result);
  213. }
  214. else if (res.ErrorException == null)
  215. {
  216. var list = res.Content.Trim('[', ']').Split(',');
  217. foreach (var operation in list)
  218. {
  219. var trimmed = operation.Trim('"');
  220. if (!result.Contains(trimmed)) result.Add(trimmed);
  221. //if (svc.Equals("Comal_Classes_Login"))
  222. // result.Add("InABox_Core_Login");
  223. }
  224. }
  225. }
  226. catch (Exception e)
  227. {
  228. }
  229. req = null;
  230. cli = null;
  231. return result.ToArray();
  232. }
  233. public override DatabaseInfo Info()
  234. {
  235. var uri = new Uri(string.Format("{0}:{1}", URL, Port));
  236. var cli = new RestClient(uri);
  237. var req = new RestRequest("/info", Method.GET) { Timeout = 20000 };
  238. try
  239. {
  240. var res = cli.Execute(req);
  241. if (res.StatusCode != HttpStatusCode.OK)
  242. {
  243. return new DatabaseInfo();
  244. }
  245. else if (res.ErrorException == null)
  246. {
  247. var info = Core.Serialization.Deserialize<InfoResponse>(res.Content);
  248. return info.Info;
  249. }
  250. }
  251. catch (Exception e)
  252. {
  253. return new DatabaseInfo();
  254. }
  255. return new DatabaseInfo();
  256. }
  257. }
  258. }