public async Task<MonitorInformation> GetMonitorInformationAsync(List<int> rblList, IHttpClient client=null)
        {
            if (null == rblList || !rblList.Any())
            {
                return new MonitorInformation(MonitorInformationErrorCode.RblNotSpecified);
            }

            var rbls = String.Join("&", rblList.Select(rbl => String.Format("rbl={0}", rbl)));
            var url = String.Format(MonitorApiUrl, rbls, _apiKey, GenerateVrtNoCacheParameterValue());

            if (null == client)
                client = new DefaultHttpClient();

            var response = await client.GetStringAsync(url).ConfigureAwait(false);

            if (null == response)
            {
                return new MonitorInformation(MonitorInformationErrorCode.DownloadingFailed);
            }

            try
            {
                return ParseMonitorResponse(response);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return
                new MonitorInformation(MonitorInformationErrorCode.ResponseParsingFailed);
        }
Exemple #2
0
        protected HttpResponse execute(HttpUriRequest request)
        {
            DefaultHttpClient httpclient = new DefaultHttpClient();

            try {
                // Execute the request
                HttpResponse response = httpclient.execute(request);
                return response;

            }catch (UnknownHostException e){
                throw e;
            } catch (ClientProtocolException e) {
                e.PrintStackTrace();
            } catch (IOException e) {
                e.PrintStackTrace();
            } catch (IllegalArgumentException e) {
                e.PrintStackTrace();
            } catch (IllegalStateException e) {
                e.PrintStackTrace();
            }

            return null;
        }
		public virtual HttpClient GetHttpClient()
		{
			// workaround attempt for issue #81
			// it does not seem like _not_ using the ThreadSafeClientConnManager actually
			// caused any problems, but it seems wise to use it "just in case", since it provides
			// extra safety and there are no observed side effects.
			BasicHttpParams @params = new BasicHttpParams();
			SchemeRegistry schemeRegistry = new SchemeRegistry();
			schemeRegistry.Register(new Apache.Http.Conn.Scheme.Scheme("http", PlainSocketFactory
				.GetSocketFactory(), 80));
			SSLSocketFactory sslSocketFactory = SSLSocketFactory.GetSocketFactory();
			schemeRegistry.Register(new Apache.Http.Conn.Scheme.Scheme("https", this.sslSocketFactory
				 == null ? sslSocketFactory : this.sslSocketFactory, 443));
			ClientConnectionManager cm = new ThreadSafeClientConnManager(@params, schemeRegistry
				);
			DefaultHttpClient client = new DefaultHttpClient(cm, @params);
			// synchronize access to the cookieStore in case there is another
			// thread in the middle of updating it.  wait until they are done so we get their changes.
			lock (this)
			{
				client.SetCookieStore(cookieStore);
			}
			return client;
		}
			public override void Run()
			{
				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response;
				string responseString = null;
				try
				{
					HttpPut post = new HttpPut(pathToDoc1.ToExternalForm());
					StringEntity se = new StringEntity(docJson.ToString());
					se.SetContentType(new BasicHeader("content_type", "application/json"));
					post.SetEntity(se);
					response = httpclient.Execute(post);
					StatusLine statusLine = response.GetStatusLine();
					Log.D(ReplicationTest.Tag, "Got response: " + statusLine);
					NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScCreated);
				}
				catch (ClientProtocolException e)
				{
					NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
						(), e);
				}
				catch (IOException e)
				{
					NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
				}
				httpRequestDoneSignal.CountDown();
			}
			public override void Run()
			{
				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response;
				string responseString = null;
				try
				{
					response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
					StatusLine statusLine = response.GetStatusLine();
					Log.D(ReplicationTest.Tag, "statusLine " + statusLine);
					NUnit.Framework.Assert.AreEqual(HttpStatus.ScNotFound, statusLine.GetStatusCode()
						);
				}
				catch (ClientProtocolException e)
				{
					NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
						(), e);
				}
				catch (IOException e)
				{
					NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
				}
				finally
				{
					httpRequestDoneSignal.CountDown();
				}
			}
			public override void Run()
			{
				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response;
				string responseString = null;
				try
				{
					response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
					StatusLine statusLine = response.GetStatusLine();
					NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScOk);
					if (statusLine.GetStatusCode() == HttpStatus.ScOk)
					{
						ByteArrayOutputStream @out = new ByteArrayOutputStream();
						response.GetEntity().WriteTo(@out);
						@out.Close();
						responseString = @out.ToString();
						NUnit.Framework.Assert.IsTrue(responseString.Contains(doc1Id));
						Log.D(ReplicationTest.Tag, "result: " + responseString);
					}
					else
					{
						response.GetEntity().GetContent().Close();
						throw new IOException(statusLine.GetReasonPhrase());
					}
				}
				catch (ClientProtocolException e)
				{
					NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
						(), e);
				}
				catch (IOException e)
				{
					NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
				}
				httpRequestDoneSignal.CountDown();
			}
 /// <exception cref="System.UriFormatException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 private HttpResponse GetRemoteDoc(Uri pathToDoc)
 {
     HttpClient httpclient = new DefaultHttpClient();
     HttpResponse response = null;
     string responseString = null;
     response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
     StatusLine statusLine = response.GetStatusLine();
     if (statusLine.GetStatusCode() != HttpStatus.ScOk)
     {
         throw new RuntimeException("Did not get 200 status doing GET to URL: " + pathToDoc
             );
     }
     return response;
 }
 /// <exception cref="System.Exception"></exception>
 public virtual void TestRemoteConflictResolution()
 {
     // Create a document with two conflicting edits.
     Document doc = database.CreateDocument();
     SavedRevision rev1 = doc.CreateRevision().Save();
     SavedRevision rev2a = CreateRevisionWithRandomProps(rev1, false);
     SavedRevision rev2b = CreateRevisionWithRandomProps(rev1, true);
     // make sure we can query the db to get the conflict
     Query allDocsQuery = database.CreateAllDocumentsQuery();
     allDocsQuery.SetAllDocsMode(Query.AllDocsMode.OnlyConflicts);
     QueryEnumerator rows = allDocsQuery.Run();
     bool foundDoc = false;
     NUnit.Framework.Assert.AreEqual(1, rows.GetCount());
     for (IEnumerator<QueryRow> it = rows; it.HasNext(); )
     {
         QueryRow row = it.Next();
         if (row.GetDocument().GetId().Equals(doc.GetId()))
         {
             foundDoc = true;
         }
     }
     NUnit.Framework.Assert.IsTrue(foundDoc);
     // Push the conflicts to the remote DB.
     Replication push = database.CreatePushReplication(GetReplicationURL());
     RunReplication(push);
     NUnit.Framework.Assert.IsNull(push.GetLastError());
     // Prepare a bulk docs request to resolve the conflict remotely. First, advance rev 2a.
     JSONObject rev3aBody = new JSONObject();
     rev3aBody.Put("_id", doc.GetId());
     rev3aBody.Put("_rev", rev2a.GetId());
     // Then, delete rev 2b.
     JSONObject rev3bBody = new JSONObject();
     rev3bBody.Put("_id", doc.GetId());
     rev3bBody.Put("_rev", rev2b.GetId());
     rev3bBody.Put("_deleted", true);
     // Combine into one _bulk_docs request.
     JSONObject requestBody = new JSONObject();
     requestBody.Put("docs", new JSONArray(Arrays.AsList(rev3aBody, rev3bBody)));
     // Make the _bulk_docs request.
     HttpClient client = new DefaultHttpClient();
     string bulkDocsUrl = GetReplicationURL().ToExternalForm() + "/_bulk_docs";
     HttpPost request = new HttpPost(bulkDocsUrl);
     request.SetHeader("Content-Type", "application/json");
     string json = requestBody.ToString();
     request.SetEntity(new StringEntity(json));
     HttpResponse response = client.Execute(request);
     // Check the response to make sure everything worked as it should.
     NUnit.Framework.Assert.AreEqual(201, response.GetStatusLine().GetStatusCode());
     string rawResponse = IOUtils.ToString(response.GetEntity().GetContent());
     JSONArray resultArray = new JSONArray(rawResponse);
     NUnit.Framework.Assert.AreEqual(2, resultArray.Length());
     for (int i = 0; i < resultArray.Length(); i++)
     {
         NUnit.Framework.Assert.IsTrue(((JSONObject)resultArray.Get(i)).IsNull("error"));
     }
     WorkaroundSyncGatewayRaceCondition();
     // Pull the remote changes.
     Replication pull = database.CreatePullReplication(GetReplicationURL());
     RunReplication(pull);
     NUnit.Framework.Assert.IsNull(pull.GetLastError());
     // Make sure the conflict was resolved locally.
     NUnit.Framework.Assert.AreEqual(1, doc.GetConflictingRevisions().Count);
 }
		/// <exception cref="System.Exception"></exception>
		public virtual void TestRemoteConflictResolution()
		{
			// Create a document with two conflicting edits.
			Document doc = database.CreateDocument();
			SavedRevision rev1 = doc.CreateRevision().Save();
			SavedRevision rev2a = rev1.CreateRevision().Save();
			SavedRevision rev2b = rev1.CreateRevision().Save(true);
			// Push the conflicts to the remote DB.
			Replication push = database.CreatePushReplication(GetReplicationURL());
			RunReplication(push);
			// Prepare a bulk docs request to resolve the conflict remotely. First, advance rev 2a.
			JSONObject rev3aBody = new JSONObject();
			rev3aBody.Put("_id", doc.GetId());
			rev3aBody.Put("_rev", rev2a.GetId());
			// Then, delete rev 2b.
			JSONObject rev3bBody = new JSONObject();
			rev3bBody.Put("_id", doc.GetId());
			rev3bBody.Put("_rev", rev2b.GetId());
			rev3bBody.Put("_deleted", true);
			// Combine into one _bulk_docs request.
			JSONObject requestBody = new JSONObject();
			requestBody.Put("docs", new JSONArray(Arrays.AsList(rev3aBody, rev3bBody)));
			// Make the _bulk_docs request.
			HttpClient client = new DefaultHttpClient();
			string bulkDocsUrl = GetReplicationURL().ToExternalForm() + "/_bulk_docs";
			HttpPost request = new HttpPost(bulkDocsUrl);
			request.SetHeader("Content-Type", "application/json");
			string json = requestBody.ToString();
			request.SetEntity(new StringEntity(json));
			HttpResponse response = client.Execute(request);
			// Check the response to make sure everything worked as it should.
			NUnit.Framework.Assert.AreEqual(201, response.GetStatusLine().GetStatusCode());
			string rawResponse = IOUtils.ToString(response.GetEntity().GetContent());
			JSONArray resultArray = new JSONArray(rawResponse);
			NUnit.Framework.Assert.AreEqual(2, resultArray.Length());
			for (int i = 0; i < resultArray.Length(); i++)
			{
				NUnit.Framework.Assert.IsTrue(((JSONObject)resultArray.Get(i)).IsNull("error"));
			}
			WorkaroundSyncGatewayRaceCondition();
			// Pull the remote changes.
			Replication pull = database.CreatePullReplication(GetReplicationURL());
			RunReplication(pull);
			// Make sure the conflict was resolved locally.
			NUnit.Framework.Assert.AreEqual(1, doc.GetConflictingRevisions().Count);
		}
Exemple #10
0
        /// <summary>
        /// Start the hub connection - populate FunctionNamesToFullNames first
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync()
        {
            // stop any previous hub connection
            hubConnection?.Stop();
            hubConnection?.Dispose();

            // make a new hub connection
            hubConnection         = new HubConnection(ConnectionUrl, false);
            hubConnection.Closed += SocketClosed;

#if DEBUG
            //hubConnection.TraceLevel = TraceLevels.All;
            //hubConnection.TraceWriter = Console.Out;
#endif

            hubProxy = hubConnection.CreateHubProxy(HubName);
            if (hubProxy == null)
            {
                throw new APIException("CreateHubProxy - proxy is null, this should never happen");
            }

            // assign callbacks for events
            foreach (string key in FunctionNamesToFullNames.Keys)
            {
                hubProxy.On(key, async(string data) => await HandleResponse(key, data));
            }

            // create a custom transport, the default transport is really buggy
            DefaultHttpClient client = new DefaultHttpClient();
            customTransport = new WebsocketCustomTransport(client, ConnectInterval, KeepAlive);
            var autoTransport = new AutoTransport(client, new IClientTransport[] { customTransport });
            hubConnection.TransportConnectTimeout = hubConnection.DeadlockErrorTimeout = TimeSpan.FromSeconds(10.0);

            // setup connect event
            customTransport.WebSocket.Connected += async(ws) =>
            {
                try
                {
                    SignalrSocketConnection[] socketsCopy;
                    lock (sockets)
                    {
                        socketsCopy = sockets.ToArray();
                    }
                    foreach (SignalrSocketConnection socket in socketsCopy)
                    {
                        await socket.InvokeConnected();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Info(ex.ToString());
                }
            };

            // setup disconnect event
            customTransport.WebSocket.Disconnected += async(ws) =>
            {
                try
                {
                    SignalrSocketConnection[] socketsCopy;
                    lock (sockets)
                    {
                        socketsCopy = sockets.ToArray();
                    }
                    foreach (SignalrSocketConnection socket in socketsCopy)
                    {
                        await socket.InvokeDisconnected();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Info(ex.ToString());
                }
                try
                {
                    // tear down the hub connection, we must re-create it whenever a web socket disconnects
                    hubConnection?.Dispose();
                }
                catch (Exception ex)
                {
                    Logger.Info(ex.ToString());
                }
            };

            try
            {
                // it's possible for the hub connection to disconnect during this code if connection is crappy
                // so we simply catch the exception and log an info message, the disconnect/reconnect loop will
                // catch the close and re-initiate this whole method again
                await hubConnection.Start(autoTransport);

                // get list of listeners quickly to limit lock
                HubListener[] listeners;
                lock (this.listeners)
                {
                    listeners = this.listeners.Values.ToArray();
                }

                // re-call the end point to enable messages
                foreach (var listener in listeners)
                {
                    foreach (object[] p in listener.Param)
                    {
                        await hubProxy.Invoke <bool>(listener.FunctionFullName, p);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Info(ex.ToString());
            }
        }
 public DefaultYZClient()
 {
     this.defaultHttpClient = new DefaultHttpClient();
 }