This implementation of onAdd watches for responses, and immediately sends them out to the
appropriate exchange/queue for routing to the necessary client application(s)
13304
@Override
	public void onAdd(Response response) {
		String message = gson.toJson(response);
		
		try {
			RabbitMqUtils.sendMessage(message, buildQueueNames(response), environment);
		} catch (IOException e) {
			logger.error("Failed to send response message to output queue.", e);
		}
	}
1342191
def process_response(self, request, response):
        
        if hasattr(threadlocal, 'actionslog'):
            pre_save.disconnect(sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'])

        return response
806597
protected void handleAppendResponseOk(RaftMemberContext member, AppendRequest request, AppendResponse response) {
    // Reset the member failure count and update the member's availability status if necessary.
    succeedAttempt(member);

    // If replication succeeded then trigger commit futures.
    if (response.succeeded()) {
      updateMatchIndex(member, response);

      // If there are more entries to send then attempt to send another commit.
      if (request.prevLogIndex() != response.lastLogIndex() && hasMoreEntries(member)) {
        appendEntries(member);
      }
    }
    // If we've received a greater term, update the term and transition back to follower.
    else if (response.term() > raft.getTerm()) {
      raft.setTerm(response.term());
      raft.setLeader(null);
      raft.transition(RaftServer.Role.FOLLOWER);
    }
    // If the response failed, the follower should have provided the correct last index in their log. This helps
    // us converge on the matchIndex faster than by simply decrementing nextIndex one index at a time.
    else {
      resetMatchIndex(member, response);
      resetNextIndex(member, response);

      // If there are more entries to send then attempt to send another commit.
      if (response.lastLogIndex() != request.prevLogIndex() && hasMoreEntries(member)) {
        appendEntries(member);
      }
    }
  }
947552
public void addResponseCommitListener(final ResponseCommitListener listener) {

        //technically it is possible to modify the exchange after the response conduit has been created
        //as the response channel should not be retrieved until it is about to be written to
        //if we get complaints about this we can add support for it, however it makes the exchange bigger and the connectors more complex
        addResponseWrapper(new ConduitWrapper<StreamSinkConduit>() {
            @Override
            public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) {
                listener.beforeCommit(exchange);
                return factory.create();
            }
        });
    }
789594
Exchange newExchange(Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
    synchronized (connectionPool) {
      if (noMoreExchanges) {
        throw new IllegalStateException("released");
      }
      if (exchange != null) {
        throw new IllegalStateException("cannot make a new request because the previous response "
            + "is still open: please call response.close()");
      }
    }

    ExchangeCodec codec = exchangeFinder.find(client, chain, doExtensiveHealthChecks);
    Exchange result = new Exchange(this, call, eventListener, exchangeFinder, codec);

    synchronized (connectionPool) {
      this.exchange = result;
      this.exchangeRequestDone = false;
      this.exchangeResponseDone = false;
      return result;
    }
  }
434614
def on_request(self, ch, method_frame, props, body):
        
        LOGGER.debug("rabbitmq.Service.on_request - request " + str(props) + " received")
        try:
            properties = props.headers.copy()
            properties['app_id'] = props.app_id
            properties['cluster_id'] = props.cluster_id
            properties['content_encoding'] = props.content_encoding
            properties['content_type'] = props.content_type
            properties['correlation_id'] = props.correlation_id
            properties['delivery_mode'] = props.delivery_mode
            properties['expiration'] = props.expiration
            properties['message_id'] = props.message_id
            properties['priority'] = props.priority
            properties['reply_to'] = props.reply_to
            properties['timestamp'] = props.timestamp
            properties['type'] = props.type
            properties['user_id'] = props.user_id
            self.cb(properties, body)
        except Exception as e:
            LOGGER.warn("rabbitmq.Service.on_request - Exception raised while treating msg {" +
                        str(props) + "," + str(body) + "}")
        LOGGER.debug("rabbitmq.Service.on_request - request " + str(props) + " treated")
        ch.basic_ack(delivery_tag=method_frame.delivery_tag)
        LOGGER.debug("rabbitmq.Service.on_request - request " + str(props) + " acked")
972850
def execute_watch(self, id=None, body=None, params=None):
        
        return self.transport.perform_request(
            "PUT",
            _make_path("_watcher", "watch", id, "_execute"),
            params=params,
            body=body,
        )
500100
function listen(self, address, port, addressType, backlog, exclusive) {
    /* TODO Index servers by a self-assigned identifier and the process
     * identifier so messages intended for previous instances do not pass
     * through. */
    servers[port] = self; // Index servers by port.
    self._port = port; // Remember the requested port for close.
    process.send({
        cmd: 'CLUSTER_LISTEN',
        port: port,
        address: address, // For confirmation purposes only.
        addressType: addressType, // We allow the supervisor to infer the address type.
        backlog: backlog, // Used to confirm uniformity of worker requests.
        exclusive: exclusive // TODO use this on the other end
    });
}
1254314
def bind(exchange, opts = {})
      check_queue_deleted!

      if exchange.respond_to?(:add_route)

        # we can do the binding ourselves
        exchange.add_route opts.fetch(:routing_key, @name), self
      else

        # we need the channel to lookup the exchange
        @channel.queue_bind self, opts.fetch(:routing_key, @name), exchange
      end
      self
    end
1742
function processWatches(items) {
  // queue up matches
  // { "member" : { "uri" : [ "match", "match" ] } }
  var toSend = {};
  GLOBAL.svc.indexer.retrieveWatches({}, function(err, res) {
    if (res.hits) {
      var watches = _.pluck(res.hits.hits, '_source');
      // for each hit
      items.forEach(function(item) {
        var matches = watchLib.matches(item, watches);
        if (matches.length) {
          matches.forEach(function(match) {
            toSend[match.member] = toSend[match.member] || {};
            toSend[match.member][item.uri] = toSend[match.member][item.uri] || [];
            toSend[match.member][item.uri].push(match.match);
          });
        }
      });
      send(toSend);
    }
  });
}
950237
public void processResponse(ResponseEvent responseEvent) {
		final ResponseEventExt responseEventExt = (ResponseEventExt) responseEvent;
		final Response response = responseEventExt.getResponse();

		if(logger.isDebugEnabled()) {
			logger.debug("Response " + response.toString());
		}

		final CSeqHeader cSeqHeader = (CSeqHeader)response.getHeader(CSeqHeader.NAME);
		//if this is a response to a cancel, the response is dropped
		if(Request.CANCEL.equalsIgnoreCase(cSeqHeader.getMethod())) {
			if(logger.isDebugEnabled()) {
				logger.debug("the response is dropped accordingly to JSR 289 " +
						"since this a response to a CANCEL");
			}
			return;
		}
		// self routing makes the application data cloned, so we make sure to nullify it
		((MessageExt)response).setApplicationData(null);

		updateResponseStatistics(response, true);
		ClientTransaction clientTransaction = responseEventExt.getClientTransaction();
		final Dialog dialog = responseEventExt.getDialog();
		final boolean isForkedResponse = responseEventExt.isForkedResponse();
		final boolean isRetransmission = responseEventExt.isRetransmission();
		final ClientTransactionExt originalTransaction = responseEventExt.getOriginalTransaction();
		if(logger.isDebugEnabled()) {
			logger.debug("is Forked Response " + isForkedResponse);
			logger.debug("is Retransmission " + isRetransmission);
			logger.debug("Client Transaction " + clientTransaction);
			logger.debug("Original Transaction " + originalTransaction);
			logger.debug("Dialog " + dialog);
			if(dialog != null) {
				logger.debug("Dialog State " + dialog.getState());
			}
		}
		// Issue 1468 : Handling forking
		if(isForkedResponse && originalTransaction != null && !responseEventExt.isRetransmission()) {
			final Dialog defaultDialog = originalTransaction.getDefaultDialog();
			final Dialog orginalTransactionDialog = originalTransaction.getDialog();
			if(logger.isDebugEnabled()) {
				logger.debug("Original Transaction Dialog " + orginalTransactionDialog);
				logger.debug("Original Transaction Default Dialog " + defaultDialog);
			}
			clientTransaction = originalTransaction;
		}

		// Transate the response to SipServletResponse
		final SipServletResponseImpl sipServletResponse = (SipServletResponseImpl) sipFactoryImpl.getMobicentsSipServletMessageFactory().createSipServletResponse(
				response,
				clientTransaction,
				null,
				dialog,
				true,
				isRetransmission);
		try {
			messageDispatcherFactory.getResponseDispatcher(sipServletResponse, this).
				dispatchMessage(((SipProvider)responseEvent.getSource()), sipServletResponse);
		} catch (Throwable e) {
			logger.error("An unexpected exception happened while routing the response " +  sipServletResponse, e);
			return;
		}
	}
490328
function onResponseFinished() {
			// Resolve the payload from the 'request' and 'response' objects,
			// and send it to the Jarmo server, catching any errors.
			var payload = config.resolve(req, res, Date.now() - start);

			if(!payload) {
				// If the payload is falsy we don't send the data. This allows
				// for some ad hoc filtering with custom resolve functions.
				return removeListeners();
			}

			return send(config.host, config.port, payload, function(err) {
				if(err) {
					config.error(err);
				}
				return removeListeners();
			});
		}
89688
def handle_response(self, msg, address):
        """"""
        now = current_time_millis()

        sigs = []
        precache = []

        for record in msg.answers:
            if isinstance(record, DNSSignature):
                sigs.append(record)
            else:
                precache.append(record)

            for e in precache:
                for s in sigs:
                    if self.verify(e, s):
                        # print "DNS: %s verified with %s" % (e,s)

                        if self.adaptive and e.type == _TYPE_A:
                            if e.address == '\x00\x00\x00\x00':
                                e.address = socket.inet_aton(address)

                        if e in self.cache.entries():
                            if e.is_expired(now):
                                for i in self.hooks:
                                    try:
                                        i.remove(e)
                                    except:
                                        pass
                                self.cache.remove(e)
                                self.cache.remove(s)
                            else:
                                entry = self.cache.get(e)
                                sig = self.cache.get(s)
                                if (entry is not None) and (sig is not None):
                                    for i in self.hooks:
                                        try:
                                            i.update(e)
                                        except:
                                            pass
                                    entry.reset_ttl(e)
                                    sig.reset_ttl(s)
                        else:
                            e.rrsig = s
                            self.cache.add(e)
                            self.cache.add(s)
                            for i in self.hooks:
                                try:
                                    i.add(e)
                                except:
                                    pass

                        precache.remove(e)
                        sigs.remove(s)
                        self.update_record(now, record)

        if self.bypass:
            for e in precache:
                if e in self.cache.entries():
                    if e.is_expired(now):
                        for i in self.hooks:
                            try:
                                i.remove(e)
                            except:
                                pass
                        self.cache.remove(e)
                    else:
                        entry = self.cache.get(e)
                        if (entry is not None):
                            for i in self.hooks:
                                try:
                                    i.update(e)
                                except:
                                    pass
                            entry.reset_ttl(e)
                else:
                    self.cache.add(e)
                    for i in self.hooks:
                        try:
                            i.add(e)
                        except:
                            pass

                self.update_record(now, record)
1353251
def _handle_response(self, transaction):
        
        code = transaction.response.code
        utils.check_code(code)
        """
        VALID response:
        change the current cache value by switching the option set with the one provided
        also resets the timestamp
        if the request etag is different from the response, send the cached response
        """
        if code == Codes.VALID.number:
            logger.debug("received VALID")
            self.cache.validate(transaction.request, transaction.response)
            if transaction.request.etag != transaction.response.etag:
                element = self.cache.search_response(transaction.request)
                transaction.response = element.cached_response
            return transaction

        """
        CHANGED, CREATED or DELETED response:
        mark the requested resource as not fresh
        """
        if code == Codes.CHANGED.number or code == Codes.CREATED.number or code == Codes.DELETED.number:
            target = self.cache.search_related(transaction.request)
            if target is not None:
                for element in target:
                    self.cache.mark(element)
            return transaction

        """
        any other response code can be cached normally
        """
        self.cache.cache_add(transaction.request, transaction.response)
        return transaction
791275
function watch(watchOptions) {

      var watcher = chokidar.watch(watchOptions.dirs, {
        ignoreInitial: true,
        ignored: /[/\\]\./
      });

      watcher.on('add', function(pathFile) {
        onWatcher(pathFile);
      });

      watcher.on('change', function(pathFile) {
        onWatcher(pathFile);
      });

      watcher.on('unlink', function(pathFile) {
        onWatcher(pathFile);
      });

      var updating = false;
      var queued = null;

      function onWatcher(pathFile) {

        if (updating) {
          queued = pathFile;
          return;
        }

        queued = null;
        updating = true;

        return Promise.resolve()
          .then(function() {
            return watchOptions.onFile(pathFile);
          })
          .then(function() {
            return Promise.delay(1000);
          })
          .then(function() {
            updating = false;
            if (queued) {
              return onWatcher(queued);
            }
          });
      }
    }
550822
function(options, cb) {
    console.log('/watch/request', options);
    publish('/watch/request', options);
    fayeClient.subscribe('/watch/results/' + clientID, cb);
  }
7603
def on_headers(self, response, exc=None):
        ''''''

        if response.status_code == 101:
            connection = response.connection
            request = response.request
            handler = request.websocket_handler
            if not handler:
                handler = WS()
            parser = request.client.frame_parser(kind=1)
            consumer = partial(WebSocketClient.create,
                               response, handler, parser)
            connection.upgrade(consumer)
            response.event('post_request').fire()
            websocket = connection.current_consumer()
            response.request_again = lambda r: websocket