public static RequestPacket CreateImagePacket(string uid, string url, RequestPacketOwners owner, IResponseHandler analisisModuleResponse = null, IResponseHandler offlineModuleResponse = null, IResponseHandler onlineModuleResponse = null) { var r = new RequestPacket() { RequestType = RequestPacketRequestTypes.Img, Uid = uid, Url = url, Owner = owner }; if (analisisModuleResponse != null) { r.AnalisisModuleResponse = analisisModuleResponse; } if (offlineModuleResponse != null) { r.OfflineModuleResponse = offlineModuleResponse; } if (onlineModuleResponse != null) { r.OnlineModuleResponse = onlineModuleResponse; } Android.Util.Log.Debug("RequestPacket", $"Created {++MyGlobal.requestPacketCount}"); return(r); }
/// <summary> /// Constructor with DI. /// </summary> /// <param name="requestHandler">Request handler implementation.</param> /// <param name="responseHandler">Response handler implementation.</param> /// <param name="logger">Logger implementation.</param> public RequestPerformer( IRequestHandler requestHandler, IResponseHandler responseHandler, ILogger logger) { throw new NotImplementedException(); }
public void RequestData(RequestPacket requestPacket, IResponseHandler responseHandler) { MyLog.Log(this, nameof(RequestData) + requestPacket.Url + "..."); requestPacket.OfflineModuleResponse = responseHandler; pendingRequest.Enqueue(requestPacket); MyLog.Log(this, nameof(RequestData) + requestPacket.Url + "...Done"); }
public SlackBot(ISlackClientFactory slackClientFactory, IResponseHandler responseHandler, ILogger logger, string slackToken) { this.slackClientFactory = slackClientFactory; this.slackToken = slackToken; this.responseHandler = responseHandler; this.logger = logger; }
public ListTodoItems( IResponseHandler <Response> outputHandler, ITodoItemGateway todoItemGateway) { _outputHandler = outputHandler; _todoItemGateway = todoItemGateway; }
/// <summary> /// Constructs a new <see cref="BaseRequest"/>. /// </summary> /// <param name="requestUrl">The URL for the request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">The header and query options for the request.</param> public BaseRequest( string requestUrl, IBaseClient client, IEnumerable <Option> options = null) { this.Method = "GET"; this.Client = client; this.responseHandler = new ResponseHandler(client.HttpProvider.Serializer); this.Headers = new List <HeaderOption>(); this.QueryOptions = new List <QueryOption>(); this.MiddlewareOptions = new Dictionary <string, IMiddlewareOption>(); this.RequestUrl = this.InitializeUrl(requestUrl); if (options != null) { var headerOptions = options.OfType <HeaderOption>(); if (headerOptions != null) { ((List <HeaderOption>) this.Headers).AddRange(headerOptions); } var queryOptions = options.OfType <QueryOption>(); if (queryOptions != null) { ((List <QueryOption>) this.QueryOptions).AddRange(queryOptions); } } // Adds the default authentication provider for this request. // This can be changed by the user by calling WithPerRequestAuthProvider extension method. this.WithDefaultAuthProvider(); }
public void AddResponseHandler(IResponseHandler handler) { if (handler != null) { globalResponseHandlers.Add(handler); } }
public void AutoTamperResponseAfter(Session oSession) { if (!((ClientChatter)oSession.oRequest).host.Equals("ffrk.denagames.com", StringComparison.CurrentCultureIgnoreCase) && !((ClientChatter)oSession.oRequest).host.Equals("dff.sp.mbga.jp", StringComparison.CurrentCultureIgnoreCase)) { return; } string requestPath = ((ClientChatter)oSession.oRequest).headers.RequestPath; Log.LogFormat(requestPath); IResponseHandler Handler = this.mResponseHandlers.FirstOrDefault <IResponseHandler>((Func <IResponseHandler, bool>)(x => x.CanHandle(oSession))); this.mHistory.AddItem(oSession, Handler); if (this.OnFFRKResponse != null) { this.OnFFRKResponse(requestPath); } if (Handler == null) { return; } try { Handler.Handle(oSession); } catch (Exception ex) { Log.LogFormat("An error occurred processing the response from {0}. {1}", (object)requestPath, (object)ex.Message); } }
public void AutoTamperResponseAfter(Session oSession) { if (!oSession.oRequest.host.Equals("ffrk.denagames.com", StringComparison.CurrentCultureIgnoreCase)) { return; } string RequestPath = oSession.oRequest.headers.RequestPath; Utility.Log.LogFormat(RequestPath); IResponseHandler handler = mResponseHandlers.FirstOrDefault(x => x.CanHandle(oSession)); mHistory.AddItem(oSession, handler); if (OnFFRKResponse != null) { OnFFRKResponse(RequestPath); } if (handler != null) { try { handler.Handle(oSession); } catch (Exception ex) { Utility.Log.LogFormat("An error occurred processing the response from {0}. {1}", RequestPath, ex.Message); } } return; }
/// <summary> /// Asynchronously handles responding to a request. /// </summary> /// <param name="connection">The connection.</param> /// <param name="request">A request message.</param> /// <param name="responseHandler">A response handler.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns>A task that represents the asynchronous operation.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="connection" /> /// is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="request" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="responseHandler" /> /// is <c>null</c>.</exception> public Task HandleResponseAsync( IConnection connection, Message request, IResponseHandler responseHandler, CancellationToken cancellationToken) { if (connection == null) { throw new ArgumentNullException(nameof(connection)); } if (request == null) { throw new ArgumentNullException(nameof(request)); } if (responseHandler == null) { throw new ArgumentNullException(nameof(responseHandler)); } cancellationToken.ThrowIfCancellationRequested(); _plugin.Close(); return(Task.FromResult(0)); }
public T RequestStruct <T>(IResponseHandler responseHandler, string firstQuestion) where T : struct { responseHandler.WriteLine(firstQuestion); var input = ReadLine(); while (true) { if (input.Equals("x", StringComparison.InvariantCultureIgnoreCase)) { throw new NoChoiceException(); } try { T result = (T)Convert.ChangeType(input, typeof(T)); return(result); } catch { } responseHandler.WriteLine($"Type a {typeof(T).Name} please:"); input = Console.ReadLine(); } }
public Client(IResponseHandler responseHandler, Dictionary <string, FunctionInfo> functions = null) { this.requester = new TRequester(); this.ResponseHandler = responseHandler; this.serializer = new TSerializer(); Functions = functions; }
public IndexManager(IDependencyResolver resolver, IClientFactory clientFactory, IResponseHandler responseHandler, ITypeToIndexMapperManager typeToIndexMapperManager) { this._resolver = resolver; this._clientFactory = clientFactory; this._responseHandler = responseHandler; this._typeToIndexMapperManager = typeToIndexMapperManager; }
public List( IResponseHandler <Response> responseHandler, IAccountGateway accountGateway) { _responseHandler = responseHandler; _accountGateway = accountGateway; }
public async Task DispatchAsync(IMessage responseMessage) { Type responseType = responseMessage.Body.GetType(); IResponseHandler handler = _handlers.Where(pair => pair.Key.IsAssignableFromEx(responseType)).Select(pair => pair.Value).FirstOrDefault(); if (handler == null) { if (FallbackHandler != null) { handler = FallbackHandler; } else { Log.WarningWithData( string.Format("No handler found for response of type '{0}' and there is no fallback handler. Message was ignored.", responseType.Name)); return; } } try { await handler.HandleAsync(responseMessage); } catch (Exception e) { Log.Error(e, "Error while handling a message."); } }
private void ActivateResponseHandler(int sequenceNumber, IResponseHandler responseHandler) { lock (Controller.Instance.responseLock) { Controller.Instance.responseHandlers.Add(sequenceNumber, responseHandler); } }
public void SetUp() { _repository = new MockRepository(); _messageDispatcher = _repository.DynamicMock <IMessageDispatcher>(); _channel = _repository.DynamicMock <IOutputChannel>(); _responseHandler = _repository.DynamicMock <IResponseHandler>(); }
public List( IResponseHandler <Response> responseHandler, IItemGateway itemGateway) { _responseHandler = responseHandler; _itemGateway = itemGateway; }
/// <summary> /// ProcessRequests runs async in separate thread until Stop() or received a quit request /// The IResponseHandler will be called on the original calling thread after each request processed /// </summary> public async void ProcessRequestsAsync(IResponseHandler handler) { while (_active) { HttpServiceResponse hostResponse = null; await Task.Run(async() => { try { hostResponse = await GetContextAsync(); } catch (Exception err) { } }).ConfigureAwait(true); // calls handler to process the response handler?.Process(hostResponse); // stop the loop if quit requested if (_quitRequestHandler.GetAndResetQuitRequested) { break; } } Stop(); }
public async Task HandleResponseAsync( IConnection connection, Message message, IResponseHandler responseHandler, CancellationToken cancellationToken) { var response = _responses.Take(); if (message.Type == MessageType.Request) { switch (message.Method) { case MessageMethod.Initialize: { var initializeRequest = JsonSerializationUtilities.ToObject <InitializeRequest>(message.Payload); _plugin.Connection.Options.SetRequestTimeout(initializeRequest.RequestTimeout); } break; case MessageMethod.Close: _cancellationTokenSource.Cancel(); break; default: break; } } await responseHandler.SendResponseAsync(message, response.Payload, cancellationToken); }
/// <summary> /// Removed the specified response handler. /// </summary> /// <param name="h">the response handler</param> public void RemoveResponseHandler(IResponseHandler h) { lock (this) { handlers.Remove(h); } }
private void SendDurable(IMethodInvocation invocation, IResponseHandler handler, RemoteExecutionPolicy policy) { var sent = true; var timeout = policy.Timeout; while (true) { if (sent) { sent = SendMessage(invocation, handler); } var tokenSource = _tokenSource; handler.WaitForResponse(timeout, tokenSource.Token); if (tokenSource.IsCancellationRequested) { if (tokenSource.Aborted) { throw new ConnectionOpenException("Connection was closed."); } sent = !sent; if (!tokenSource.Restored) { tokenSource.Restored = false; } continue; } if (!handler.HasValue) { // Cancellation not requested but value not received. This means that the operation timed out. throw new TimeoutException(); } break; } }
private void HandleFailure(ProcedureCallBatch request, IResponseHandler rh, bool voting) { Dictionary <string, bool> r0 = new Dictionary <string, bool>(); foreach (Call r1 in request.Batch) { r0.Add(r1.ID, false); } // (State state, bool b) s = CurrentState.Instance.Get_State; // bool call = voting && s.state == State.CANDIDATE; // Activate the responsehandler // if (call && (StateLog.Instance.Nodes.GetHeartbeat(ID) == Params.MAX_RETRIES || CurrentState.Instance.ReceviedVote )) rh.OnResponse(ID, request, Encoder.SerializeResponse(new Response() { Status = r0, Completed = null, Data = null })); Logger.Write(Logger.Tag.WARN, "Unable to connect to [node:" + ID + "][retries:" + StateLog.Instance.Nodes.GetHeartbeat(ID) + "]"); StateLog.Instance.Nodes.AccessHeartbeat(ID, (hb) => { hb.Increment(); }); _notified = true; // if (!call && StateLog.Instance.Nodes.GetHeartbeat(ID) < Params.MAX_RETRIES) StartClient(request, rh); }
/// <summary> /// Asynchronously starts processing a response for the inbound request. /// </summary> /// <param name="request">The request.</param> /// <param name="requestHandler">A request handler.</param> /// <param name="responseHandler">A response handler.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="request" /> /// is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="requestHandler" /> /// is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="responseHandler" /> /// is <c>null</c>.</exception> public void BeginResponseAsync( Message request, IRequestHandler requestHandler, IResponseHandler responseHandler) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (requestHandler == null) { throw new ArgumentNullException(nameof(requestHandler)); } if (responseHandler == null) { throw new ArgumentNullException(nameof(responseHandler)); } if (_logger.IsEnabled) { _logger.Write(new TaskLogMessage(_logger.Now, request.RequestId, request.Method, request.Type, TaskState.Queued)); } Func <Task> task = () => ProcessResponseAsync(requestHandler, request, responseHandler); _inboundRequestProcessingHandler.Handle(request.Method, task, _cancellationToken); }
/// <summary> /// Adds a response handler. /// </summary> /// <param name="h">the response handler</param> public void AddResponseHandler(IResponseHandler h) { lock (this) { handlers.Add(h); } }
public Task HandleResponseAsync( IConnection connection, Message request, IResponseHandler responseHandler, CancellationToken cancellationToken) { return(HandleResponseAsyncFunc(connection, request, responseHandler, cancellationToken)); }
public Task HandleResponseAsync( IConnection connection, Message request, IResponseHandler responseHandler, CancellationToken cancellationToken) { return(responseHandler.SendResponseAsync(request, _payload, cancellationToken)); }
public TcpClientAdapter(string hostName, int port, int chunkSizeBytes, IRequestHandler requestHandler, IResponseHandler responseHandler) { _client = new TcpClient(hostName, port); _chunkSizeBytes = chunkSizeBytes; _stream = _client.GetStream(); _requestHandler = requestHandler; _responseHandler = responseHandler; }
public InquiryCountService(Logger logger, IResponseHandler responseHandler, IUnitOfWork unitOfWork) { _logger = logger; _unitOfWork = unitOfWork;; _responseHandler = responseHandler; }
public QueueConnectionWorker(IQueueConnection queueConnection, string queueName) { _queueConnection = queueConnection; _queueName = queueName; var bl = new BusinessManager(); _responseHandler = bl.GetResponseActions(); }
public void AddItem(Session Session, IResponseHandler Handler) { HistoryItem data = new HistoryItem(); data.Timestamp = DateTime.Now; data.Session = Session; data.Handler = Handler; mResponseHistory.Add(data); }
public static Task<HttpResponseMessage> FollowLinkAsync( this System.Net.Http.HttpClient httpClient, IRequestFactory requestFactory, IResponseHandler handler = null) { var httpRequestMessage = requestFactory.CreateRequest(); httpRequestMessage.Properties[PropertyKeyLinkRelation] = requestFactory.LinkRelation; return httpClient.SendAsync(httpRequestMessage) .ApplyRepresentationToAsync(handler); }
public static async Task<HttpResponseMessage> ApplyRepresentationToAsync(this Task<HttpResponseMessage> task, IResponseHandler responseHandler) { // What do we do with exceptions that happen here? HttpResponseMessage response = await task; if (task.IsCompleted && responseHandler != null) { response = task.Result; string lr = "related"; if (response.RequestMessage.Properties.ContainsKey(HttpClientExtensions.PropertyKeyLinkRelation)) { lr = response.RequestMessage.Properties[HttpClientExtensions.PropertyKeyLinkRelation] as string; } response = await responseHandler.HandleResponseAsync(lr, response); } return response; }
public Producer RegisterResponseHandler(IResponseHandler responseHandler) { _responseHandler = responseHandler; return this; }
public void RegisterResponseHandler(IResponseHandler handler) { responseHandlers.Add(handler); }
public void RegisterResponseHandler(IResponseHandler renderer) { _responseHandlers.Add(renderer); }
public void UnregisterResponseHandler(IResponseHandler renderer) { if (_responseHandlers.Contains(renderer)) { _responseHandlers.Remove(renderer); } }
public AgentSession(IResponseHandler handler) { this.handler = handler; }
public void SendMessage(Message message, IResponseHandler responseHandler) { ensureConnection(); _htsConnection.sendMessage(message, responseHandler); }
public RdapRequestHandler(IResponseHandler responseHandler) { this.responseHandler = responseHandler; readParserStream = new FifoStream(); messageParser = new RdapMessageParser(readParserStream); }
public void Send( MessageType type, int? messageId, String method, IList<object> arguments, Action<SendingContext, Exception, bool> onMessageSent, IResponseHandler responseHandler ) { switch ( type ) { case MessageType.Request: case MessageType.Notification: { break; } default: { throw new ArgumentOutOfRangeException( "type", type, "'type' must be 'Request' or 'Notificatiion'." ); } } if ( method == null ) { throw new ArgumentNullException( "method" ); } if ( String.IsNullOrWhiteSpace( method ) ) { throw new ArgumentException( "'method' cannot be empty.", "method" ); } if ( arguments == null ) { throw new ArgumentNullException( "arguments" ); } if ( this._disposed ) { throw new ObjectDisposedException( this.ToString() ); } Contract.EndContractBlock(); var sendingContext = this.CreateNewSendingContext( messageId, onMessageSent ); RpcErrorMessage serializationError = this._requestSerializer.Serialize( messageId, method, arguments, sendingContext.SendingBuffer ); if ( !serializationError.IsSuccess ) { throw new RpcTransportException( serializationError.Error, serializationError.Detail ); } if ( messageId.HasValue ) { try { } finally { this._sessionTableLatch.AddCount(); if ( !this._sessionTable.TryAdd( messageId.Value, responseHandler ) ) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "Message ID:{0} is already used.", messageId.Value ) ); } } } // Must set BufferList here. sendingContext.SocketContext.BufferList = sendingContext.SendingBuffer.Chunks; this.SendCore( sendingContext ); }
internal void RemoveResponseEventHandler(IResponseHandler handler) { int hash = handler.Hash; if (hash != 0) lock (lockHandlers) if (responseEventHandlers.ContainsKey(hash)) responseEventHandlers.Remove(hash); }
private void AddResponseEventHandler(IResponseHandler handler) { lock (lockHandlers) responseEventHandlers[handler.Hash] = handler; }
private void AddResponseHandler(IResponseHandler handler) { lock (lockHandlers) { if (handler.Action is PingAction) pingHandlers[handler.Hash] = handler; else responseHandlers[handler.Hash] = handler; } }
public Producer RegisterResponseHandler(IResponseHandler responseHandler) { _remotingClient.RegisterResponseHandler((int)RequestCode.SendMessage, responseHandler); return this; }
public abstract void RemoveResponseHandler( ushort channel, IResponseHandler rh );
public SocketRemotingClient RegisterResponseHandler(int requestCode, IResponseHandler responseHandler) { _responseHandlerDict[requestCode] = responseHandler; return this; }
public void sendMessage(Message message, IResponseHandler responseHandler) { // loop the sequence number if (_seq == int.MaxValue) { _seq = int.MinValue; } else { _seq++; } // housekeeping verry old response handlers if (_responseHandlers.ContainsKey(_seq)) { _responseHandlers.Remove(_seq); } message.putField("seq", _seq); _messagesForSendQueue.Enqueue(message); _responseHandlers.Add(_seq, responseHandler); }