// dispatch triggers all of the relevant handlers when a webhook event is received.
775618
func (m *Messenger) dispatch(r Receive) {
	for _, entry := range r.Entry {
		for _, info := range entry.Messaging {
			a := m.classify(info, entry)
			if a == UnknownAction {
				fmt.Println("Unknown action:", info)
				continue
			}

			resp := &Response{
				to:    Recipient{info.Sender.ID},
				token: m.token,
			}

			switch a {
			case TextAction:
				for _, f := range m.messageHandlers {
					message := *info.Message
					message.Sender = info.Sender
					message.Recipient = info.Recipient
					message.Time = time.Unix(info.Timestamp/int64(time.Microsecond), 0)
					f(message, resp)
				}
			case DeliveryAction:
				for _, f := range m.deliveryHandlers {
					f(*info.Delivery, resp)
				}
			case ReadAction:
				for _, f := range m.readHandlers {
					f(*info.Read, resp)
				}
			case PostBackAction:
				for _, f := range m.postBackHandlers {
					message := *info.PostBack
					message.Sender = info.Sender
					message.Recipient = info.Recipient
					message.Time = time.Unix(info.Timestamp/int64(time.Microsecond), 0)
					f(message, resp)
				}
			case OptInAction:
				for _, f := range m.optInHandlers {
					message := *info.OptIn
					message.Sender = info.Sender
					message.Recipient = info.Recipient
					message.Time = time.Unix(info.Timestamp/int64(time.Microsecond), 0)
					f(message, resp)
				}
			case ReferralAction:
				for _, f := range m.referralHandlers {
					message := *info.ReferralMessage
					message.Sender = info.Sender
					message.Recipient = info.Recipient
					message.Time = time.Unix(info.Timestamp/int64(time.Microsecond), 0)
					f(message, resp)
				}
			case AccountLinkingAction:
				for _, f := range m.accountLinkingHandlers {
					message := *info.AccountLinking
					message.Sender = info.Sender
					message.Recipient = info.Recipient
					message.Time = time.Unix(info.Timestamp/int64(time.Microsecond), 0)
					f(message, resp)
				}
			}
		}
	}
}
493419
func (self *FSock) dispatchEvent(event string) {
	eventName := headerVal(event, "Event-Name")
	if eventName == "BACKGROUND_JOB" { // for bgapi BACKGROUND_JOB
		go self.doBackgroudJob(event)
		return
	}

	if eventName == "CUSTOM" {
		eventSubclass := headerVal(event, "Event-Subclass")
		if len(eventSubclass) != 0 {
			eventName += " " + urlDecode(eventSubclass)
		}
	}

	for _, handleName := range []string{eventName, "ALL"} {
		if _, hasHandlers := self.eventHandlers[handleName]; hasHandlers {
			// We have handlers, dispatch to all of them
			for _, handlerFunc := range self.eventHandlers[handleName] {
				go handlerFunc(event, self.connId)
			}
			return
		}
	}
	if self.logger != nil {
		fmt.Printf("No dispatcher, event name: %s, handlers: %+v\n", eventName, self.eventHandlers)
		self.logger.Warning(fmt.Sprintf("<FSock> No dispatcher for event: <%+v>", event))
	}
}
1302547
func (self *ServeMux) Dispatch(pattern string, dispatcher Dispatcher) {
	h := func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				fmt.Fprintf(os.Stderr, "++++++++++++ PANIC +++++++++++++++++++\n")
				fmt.Fprintf(os.Stderr, "++++++++++++ ORIGINAL ERROR: %v ++++++++++++n", err)
				buf := make([]byte, 16384)
				l := runtime.Stack(buf, false)
				fmt.Fprintf(os.Stderr, "%s\n", string(buf[:l]))
				fmt.Fprintf(os.Stderr, "++++++++++++++++++++++++++++++++++++++\n")

				if self.err != nil {
					self.err.PanicDispatch(err, w, r)
				} else {
					fmt.Fprintf(os.Stderr, "++++++++++++ FORCING ANOTHER PANIC: %v ++++++++++++\n", err)
					panic(err)
				}
			}
		}()
		w.Header().Add("Cache-Control", "no-cache, must-revalidate") //HTTP 1.1
		w.Header().Add("Pragma", "no-cache")                         //HTTP 1.0
		b := dispatcher.Dispatch(self, w, r)
		if b != nil {
			b.ServeHTTP(w, r)
		}
	}
	self.ServeMux.HandleFunc(pattern, h)
}
25052
func (c *Container) Dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request) {
	if httpWriter == nil {
		panic("httpWriter cannot be nil")
	}
	if httpRequest == nil {
		panic("httpRequest cannot be nil")
	}
	c.dispatch(httpWriter, httpRequest)
}
71955
func (ed *Dispatcher) EventCh() (chan<- interface{}, error) {
	state := ed.getState()
	if state == dispatcherStateStarted {
		return ed.eventch, nil
	}
	return nil, errors.Errorf("dispatcher not started - Current state [%d]", state)
}
897927
func (a *ArgoCDWebhookHandler) HandleEvent(payload interface{}, header webhooks.Header) {
	webURL, revision, touchedHead := affectedRevisionInfo(payload)
	// NOTE: the webURL does not include the .git extension
	if webURL == "" {
		log.Info("Ignoring webhook event")
		return
	}
	log.Infof("Received push event repo: %s, revision: %s, touchedHead: %v", webURL, revision, touchedHead)
	appIf := a.appClientset.ArgoprojV1alpha1().Applications(a.ns)
	apps, err := appIf.List(metav1.ListOptions{})
	if err != nil {
		log.Warnf("Failed to list applications: %v", err)
		return
	}
	urlObj, err := url.Parse(webURL)
	if err != nil {
		log.Warnf("Failed to parse repoURL '%s'", webURL)
		return
	}
	regexpStr := "(?i)(http://|https://|git@)" + urlObj.Host + "[:/]" + urlObj.Path[1:] + "(\\.git)?"
	repoRegexp, err := regexp.Compile(regexpStr)
	if err != nil {
		log.Warn("Failed to compile repoURL regexp")
		return
	}

	for _, app := range apps.Items {
		if !repoRegexp.MatchString(app.Spec.Source.RepoURL) {
			log.Debugf("%s does not match", app.Spec.Source.RepoURL)
			continue
		}
		targetRev := app.Spec.Source.TargetRevision
		if targetRev == "HEAD" || targetRev == "" {
			if !touchedHead {
				continue
			}
		} else if targetRev != revision {
			continue
		}
		_, err = argo.RefreshApp(appIf, app.ObjectMeta.Name, v1alpha1.RefreshTypeNormal)
		if err != nil {
			log.Warnf("Failed to refresh app '%s' for controller reprocessing: %v", app.ObjectMeta.Name, err)
			continue
		}
	}
}
1083127
func (d *eventDispatcher) DispatchEvent(e Event) {
	d.RLock()
	defer d.RUnlock()

	// Automatically set the event source.
	if e, ok := e.(*event); ok {
		e.source = d.source
	}

	// Dispatch the event to all listeners.
	for _, l := range d.listeners[e.Type()] {
		l(e)
	}
}
264036
func (s *Service) Dispatch(request []byte) []byte {
	msg := bytes.SplitN(request, []byte{' '}, 2)
	name := msg[0]

	// Trim NULL byte terminator
	name = bytes.TrimRight(name, "\x00")

	handler, ok := s.handlers[string(name)]

	if !ok {
		log.Printf("unknown command: %q\n", name)
		return []byte("Unknown Command")
	}

	var args []byte
	if len(msg) == 2 {
		args = msg[1]
	}

	response, err := handler(args)
	if err == nil {
		response = append([]byte("OK "), response...)
	} else {
		log.Printf("error calling %s: %s\n", name, err)
		response = append([]byte("ERR "), response...)
	}

	return response
}
984378
func listenAndDispatch(c *Client, em *clientEventMonitor, r *io.PipeReader, w *io.PipeWriter) {
	listener := make(chan *dockerclient.APIEvents)
	c.dc.AddEventListener(listener)
	for {
		evt := <-listener
		if evt != nil {
			em.dispatch(evt)
		}
	}
}
723567
func DispatchOnewayHandler(
	ctx context.Context,
	h OnewayHandler,
	req *Request,
) (err error) {
	return InvokeOnewayHandler(OnewayInvokeRequest{
		Context: ctx,
		Request: req,
		Handler: h,
	})
}
726151
func Dispatch(command commands.CommandResponse) {
	for _, f := range registry {
		if fn, ok := f.(func(cr commands.CommandResponse)); ok == true {
			go fn(command)
		}
		if handler, ok := f.(Handler); ok == true {
			go handler.Handle(command)
		}
	}
}
291736
func (cc *clientConn) dispatch(ctx context.Context, data []byte) error {
	span := opentracing.StartSpan("server.dispatch")
	ctx = opentracing.ContextWithSpan(ctx, span)

	ctx1, cancelFunc := context.WithCancel(ctx)
	cc.mu.Lock()
	cc.mu.cancelFunc = cancelFunc
	cc.mu.Unlock()

	t := time.Now()
	cmd := data[0]
	data = data[1:]
	cc.lastCmd = string(hack.String(data))
	token := cc.server.getToken()
	defer func() {
		cc.ctx.SetProcessInfo("", t, mysql.ComSleep)
		cc.server.releaseToken(token)
		span.Finish()
	}()

	if cmd < mysql.ComEnd {
		cc.ctx.SetCommandValue(cmd)
	}

	dataStr := string(hack.String(data))
	switch cmd {
	case mysql.ComPing, mysql.ComStmtClose, mysql.ComStmtSendLongData, mysql.ComStmtReset,
		mysql.ComSetOption, mysql.ComChangeUser:
		cc.ctx.SetProcessInfo("", t, cmd)
	case mysql.ComInitDB:
		cc.ctx.SetProcessInfo("use "+dataStr, t, cmd)
	}

	switch cmd {
	case mysql.ComSleep:
		// TODO: According to mysql document, this command is supposed to be used only internally.
		// So it's just a temp fix, not sure if it's done right.
		// Investigate this command and write test case later.
		return nil
	case mysql.ComQuit:
		return io.EOF
	case mysql.ComQuery: // Most frequently used command.
		// For issue 1989
		// Input payload may end with byte '\0', we didn't find related mysql document about it, but mysql
		// implementation accept that case. So trim the last '\0' here as if the payload an EOF string.
		// See http://dev.mysql.com/doc/internals/en/com-query.html
		if len(data) > 0 && data[len(data)-1] == 0 {
			data = data[:len(data)-1]
			dataStr = string(hack.String(data))
		}
		return cc.handleQuery(ctx1, dataStr)
	case mysql.ComPing:
		return cc.writeOK()
	case mysql.ComInitDB:
		if err := cc.useDB(ctx1, dataStr); err != nil {
			return err
		}
		return cc.writeOK()
	case mysql.ComFieldList:
		return cc.handleFieldList(dataStr)
	case mysql.ComStmtPrepare:
		return cc.handleStmtPrepare(dataStr)
	case mysql.ComStmtExecute:
		return cc.handleStmtExecute(ctx1, data)
	case mysql.ComStmtFetch:
		return cc.handleStmtFetch(ctx1, data)
	case mysql.ComStmtClose:
		return cc.handleStmtClose(data)
	case mysql.ComStmtSendLongData:
		return cc.handleStmtSendLongData(data)
	case mysql.ComStmtReset:
		return cc.handleStmtReset(data)
	case mysql.ComSetOption:
		return cc.handleSetOption(data)
	case mysql.ComChangeUser:
		return cc.handleChangeUser(ctx1, data)
	default:
		return mysql.NewErrf(mysql.ErrUnknown, "command %d not supported now", cmd)
	}
}
126578
func (ch *Channel) dispatch(msg message) {
	switch m := msg.(type) {
	case *channelClose:
		// lock before sending connection.close-ok
		// to avoid unexpected interleaving with basic.publish frames if
		// publishing is happening concurrently
		ch.m.Lock()
		ch.send(&channelCloseOk{})
		ch.m.Unlock()
		ch.connection.closeChannel(ch, newError(m.ReplyCode, m.ReplyText))

	case *channelFlow:
		ch.notifyM.RLock()
		for _, c := range ch.flows {
			c <- m.Active
		}
		ch.notifyM.RUnlock()
		ch.send(&channelFlowOk{Active: m.Active})

	case *basicCancel:
		ch.notifyM.RLock()
		for _, c := range ch.cancels {
			c <- m.ConsumerTag
		}
		ch.notifyM.RUnlock()
		ch.consumers.cancel(m.ConsumerTag)

	case *basicReturn:
		ret := newReturn(*m)
		ch.notifyM.RLock()
		for _, c := range ch.returns {
			c <- *ret
		}
		ch.notifyM.RUnlock()

	case *basicAck:
		if ch.confirming {
			if m.Multiple {
				ch.confirms.Multiple(Confirmation{m.DeliveryTag, true})
			} else {
				ch.confirms.One(Confirmation{m.DeliveryTag, true})
			}
		}

	case *basicNack:
		if ch.confirming {
			if m.Multiple {
				ch.confirms.Multiple(Confirmation{m.DeliveryTag, false})
			} else {
				ch.confirms.One(Confirmation{m.DeliveryTag, false})
			}
		}

	case *basicDeliver:
		ch.consumers.send(m.ConsumerTag, newDelivery(ch, m))
		// TODO log failed consumer and close channel, this can happen when
		// deliveries are in flight and a no-wait cancel has happened

	default:
		ch.rpc <- msg
	}
}
315537
func (f EventHandlerFunc) HandleEvent(resp http.ResponseWriter, req *http.Request, event *Event) {
	f(resp, req, event)
}
850407
func (g *gossipRegistry) eventLoop() {
	for {
		select {
		// return when done
		case <-g.done:
			return
		case ev := <-g.events:
			// TODO: nonblocking update
			g.Lock()
			if _, ok := g.members[ev.node]; ok {
				g.members[ev.node] = ev.action
			}
			g.Unlock()
		}
	}
}
1230875
func (*CallingGoroutineDispatcher) DispatchTask(task *swf.PollForActivityTaskOutput, handler func(*swf.PollForActivityTaskOutput)) {
	handler(task)
}
1352010
func (h *DispatchHook) Run(ctx context.Context, name string, ui Ui, comm Communicator, data interface{}) error {

	hooks, ok := h.Mapping[name]
	if !ok {
		// No hooks for that name. No problem.
		return nil
	}

	for _, hook := range hooks {
		if err := ctx.Err(); err != nil {
			return err
		}

		if err := hook.Run(ctx, name, ui, comm, data); err != nil {
			return err
		}
	}

	return nil
}