/*
HandleEvent is a handler for Event responses from ThrustCore
This should be changed to private as soon as API stabilizes.
*/
769544
func (menu *Menu) HandleEvent(reply CommandResponse) {
	for _, item := range menu.Items {
		if reply.Event.CommandID == item.CommandID {
			Log.Print("Menu(", menu.TargetID, "):: Handling Event", item.CommandID, "::Handled With Flags", reply.Event.EventFlags, "With Type", item.Type)
			handler, ok := menu.ReplyHandlers[item.CommandID]
			if ok {
				handler(reply, item)
			} else {
				item.HandleEvent()
			}
			return
		}
	}
}
800029
func (eh guildRoleDeleteEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*GuildRoleDelete); ok {
		eh(s, t)
	}
}
835580
func (c *Client) handleEvent(msg []byte) error {
	event := &eventType{}
	err := json.Unmarshal(msg, event)
	if err != nil {
		return err
	}
	//var e interface{}
	switch event.Event {
	case "info":
		i := InfoEvent{}
		err = json.Unmarshal(msg, &i)
		if err != nil {
			return err
		}
		if i.Code == 0 && i.Version != 0 {
			err_open := c.handleOpen()
			if err_open != nil {
				return err_open
			}
		}
		c.listener <- &i
	case "auth":
		a := AuthEvent{}
		err = json.Unmarshal(msg, &a)
		if err != nil {
			return err
		}
		if a.Status != "" && a.Status == "OK" {
			c.Authentication = SuccessfulAuthentication
		} else {
			c.Authentication = RejectedAuthentication
		}
		c.handleAuthAck(&a)
		c.listener <- &a
		return nil
	case "subscribed":
		s := SubscribeEvent{}
		err = json.Unmarshal(msg, &s)
		if err != nil {
			return err
		}
		err = c.subscriptions.activate(s.SubID, s.ChanID)
		if err != nil {
			return err
		}
		c.listener <- &s
		return nil
	case "unsubscribed":
		s := UnsubscribeEvent{}
		err = json.Unmarshal(msg, &s)
		if err != nil {
			return err
		}
		err_rem := c.subscriptions.removeByChannelID(s.ChanID)
		if err_rem != nil {
			return err_rem
		}
		c.listener <- &s
	case "error":
		er := ErrorEvent{}
		err = json.Unmarshal(msg, &er)
		if err != nil {
			return err
		}
		c.listener <- &er
	case "conf":
		ec := ConfEvent{}
		err = json.Unmarshal(msg, &ec)
		if err != nil {
			return err
		}
		c.listener <- &ec
	default:
		c.log.Warningf("unknown event: %s", msg)
	}

	//err = json.Unmarshal(msg, &e)
	//TODO raw message isn't ever published

	return err
}
1196854
func (watcher *RecursiveWatcher) handleEvent(event *fsnotify.FileEvent) {
	if event.IsCreate() {
		watcher.handleCreate(event)
	}

	e := Event{
		FileEvent: event,
	}

	watcher.Events <- e
}
1120519
func (c *Collector) handleEvent(event events.Event) {
	switch event.(type) {
	case api.EventNode:
		c.handleNodeEvent(event)
	case api.EventTask:
		c.handleTaskEvent(event)
	case api.EventService:
		c.handleServiceEvent(event)
	case api.EventNetwork:
		c.handleNetworkEvent(event)
	case api.EventSecret:
		c.handleSecretsEvent(event)
	case api.EventConfig:
		c.handleConfigsEvent(event)
	}
}
196939
func (h *Handler) HandleEvent(e *events.Event) {
	buf := bufferPool.Get().(*buffer)
	buf.b = buf.b[:0]
	buf.b = append(buf.b, h.Prefix...)

	if fmt := h.TimeFormat; len(fmt) != 0 {
		loc := h.TimeLocation
		if loc == nil {
			loc = time.Local
		}
		buf.b = e.Time.In(loc).AppendFormat(buf.b, fmt)
		buf.b = append(buf.b, " - "...)
	}

	if len(e.Source) != 0 {
		buf.b = append(buf.b, e.Source...)
		buf.b = append(buf.b, " - "...)
	}

	buf.b = append(buf.b, e.Message...)
	buf.b = append(buf.b, '\n')

	if h.EnableArgs {
		hasError := false

		for _, a := range e.Args {
			if _, ok := a.Value.(error); ok {
				hasError = true
			} else {
				buf.b = append(buf.b, '\t')
				buf.b = append(buf.b, a.Name...)
				buf.b = append(buf.b, ':', ' ')
				fmt.Fprintf(buf, "%v\n", a.Value)
			}
		}

		if hasError {
			fmt.Fprint(buf, "\terrors:\n")

			for _, a := range e.Args {
				if err, ok := a.Value.(error); ok {
					fmt.Fprintf(buf, "\t\t- %+v\n", err)
				}
			}
		}
	}

	h.mutex.Lock()
	h.Output.Write(buf.b)
	h.mutex.Unlock()
	bufferPool.Put(buf)
}
660368
func (h *EventHandler) HandleEvent(ctx context.Context, event eh.Event) error {
	// Get or create the model, trying to use a waiting find with a min version
	// if the underlying repo supports it.
	findCtx, cancel := eh.NewContextWithMinVersionWait(ctx, event.Version()-1)
	defer cancel()
	entity, err := h.repo.Find(findCtx, event.AggregateID())
	if rrErr, ok := err.(eh.RepoError); ok && rrErr.Err == eh.ErrEntityNotFound {
		if h.factoryFn == nil {
			return Error{
				Err:       ErrModelNotSet,
				Namespace: eh.NamespaceFromContext(ctx),
			}
		}
		entity = h.factoryFn()
	} else if err != nil {
		return Error{
			Err:       err,
			Namespace: eh.NamespaceFromContext(ctx),
		}
	}

	// The entity should be one version behind the event.
	if entity, ok := entity.(eh.Versionable); ok {
		if entity.AggregateVersion()+1 != event.Version() {
			return Error{
				Err:       eh.ErrIncorrectEntityVersion,
				Namespace: eh.NamespaceFromContext(ctx),
			}
		}
	}

	// Run the projection, which will possibly increment the version.
	newEntity, err := h.projector.Project(ctx, event, entity)
	if err != nil {
		return Error{
			Err:       err,
			Namespace: eh.NamespaceFromContext(ctx),
		}
	}

	// The model should now be at the same version as the event.
	if newEntity, ok := newEntity.(eh.Versionable); ok {
		if newEntity.AggregateVersion() != event.Version() {
			return Error{
				Err:       eh.ErrIncorrectEntityVersion,
				Namespace: eh.NamespaceFromContext(ctx),
			}
		}
	}

	// Update or remove the model.
	if newEntity != nil {
		if err := h.repo.Save(ctx, newEntity); err != nil {
			return Error{
				Err:       err,
				Namespace: eh.NamespaceFromContext(ctx),
			}
		}
	} else {
		if err := h.repo.Remove(ctx, event.AggregateID()); err != nil {
			return Error{
				Err:       err,
				Namespace: eh.NamespaceFromContext(ctx),
			}
		}
	}

	return nil
}
202423
func (s SerfEventHandler) HandleEvent(e serf.Event) {
	if e == nil {
		return
	}

	var reconcile bool
	switch e.EventType() {

	// If the event is a Join event, call NodeJoined and then reconcile event with
	// persistent storage.
	case serf.EventMemberJoin:
		reconcile = s.ReconcileOnJoin
		if s.NodeJoined != nil {
			s.NodeJoined.HandleMemberJoin(e.(serf.MemberEvent))
		}

	// If the event is a Leave event, call NodeLeft and then reconcile event with
	// persistent storage.
	case serf.EventMemberLeave:
		reconcile = s.ReconcileOnLeave
		if s.NodeLeft != nil {
			s.NodeLeft.HandleMemberLeave(e.(serf.MemberEvent))
		}

	// If the event is a Failed event, call NodeFailed and then reconcile event with
	// persistent storage.
	case serf.EventMemberFailed:
		reconcile = s.ReconcileOnFail
		if s.NodeFailed != nil {
			s.NodeFailed.HandleMemberFailure(e.(serf.MemberEvent))
		}

	// If the event is a Reap event, reconcile event with persistent storage.
	case serf.EventMemberReap:
		reconcile = s.ReconcileOnReap
		if s.NodeReaped != nil {
			s.NodeReaped.HandleMemberReap(e.(serf.MemberEvent))
		}

	// If the event is a user event, handle leader elections, user events and unknown events.
	case serf.EventUser:
		s.handleUserEvent(e.(serf.UserEvent))

	// If the event is an Update event, call NodeUpdated
	case serf.EventMemberUpdate:
		reconcile = s.ReconcileOnUpdate
		if s.NodeUpdated != nil {
			s.NodeUpdated.HandleMemberUpdate(e.(serf.MemberEvent))
		}

	// If the event is a query, call Query Handler
	case serf.EventQuery:
		if s.QueryHandler != nil {
			s.QueryHandler.HandleQueryEvent(*e.(*serf.Query))
		}
	default:
		s.Logger.Warn("unhandled Serf Event: %#v", e)
		return
	}

	// Reconcile event with external storage
	if reconcile && s.Reconciler != nil {
		s.reconcile(e.(serf.MemberEvent))
	}
}
562205
func (eh userUpdateEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*UserUpdate); ok {
		eh(s, t)
	}
}
790123
func (w *Watcher) handleEvent(data []byte) {
	buf := bytes.NewBuffer(data)
	msg := &cnMsg{}
	hdr := &procEventHeader{}

	binary.Read(buf, byteOrder, msg)
	binary.Read(buf, byteOrder, hdr)

	switch hdr.What {
	case PROC_EVENT_FORK:
		event := &forkProcEvent{}
		binary.Read(buf, byteOrder, event)
		ppid := int(event.ParentTgid)
		pid := int(event.ChildTgid)

		if w.isWatching(ppid, PROC_EVENT_EXEC) {
			// follow forks
			watch, _ := w.watches[ppid]
			w.Watch(pid, watch.flags)
		}

		if w.isWatching(ppid, PROC_EVENT_FORK) {
			w.Fork <- &ProcEventFork{ParentPid: ppid, ChildPid: pid}
		}
	case PROC_EVENT_EXEC:
		event := &execProcEvent{}
		binary.Read(buf, byteOrder, event)
		pid := int(event.ProcessTgid)

		if w.isWatching(pid, PROC_EVENT_EXEC) {
			w.Exec <- &ProcEventExec{Pid: pid}
		}
	case PROC_EVENT_EXIT:
		event := &exitProcEvent{}
		binary.Read(buf, byteOrder, event)
		pid := int(event.ProcessTgid)

		if w.isWatching(pid, PROC_EVENT_EXIT) {
			w.RemoveWatch(pid)
			w.Exit <- &ProcEventExit{Pid: pid}
		}
	}
}
1338289
func (h *EventHandler) HandleEvent(ctx context.Context, event eh.Event) error {
	// Run the saga and collect commands.
	cmds := h.saga.RunSaga(ctx, event)

	// Dispatch commands back on the command bus.
	for _, cmd := range cmds {
		if err := h.commandHandler.HandleCommand(ctx, cmd); err != nil {
			return errors.New("could not handle command '" +
				string(cmd.CommandType()) + "' from saga '" +
				string(h.saga.SagaType()) + "': " + err.Error())
		}
	}

	return nil
}
1223275
func (c *DropMenu) HandleEvent(event termbox.Event) bool {
	moveUp := (event.Key == termbox.KeyArrowUp || (c.menu.vimMode && event.Ch == 'k'))
	moveDown := (event.Key == termbox.KeyArrowDown || (c.menu.vimMode && event.Ch == 'j'))
	if c.menuSelected {
		selIdx := c.menu.GetSelectedIndex()
		if (moveUp && selIdx == 0) || (moveDown && selIdx == (len(c.menu.options)-1)) {
			c.menuSelected = false
		} else {
			if c.menu.HandleEvent(event) {
				if c.menu.IsDone() {
					c.HideMenu()
				}
				return true
			}
		}
	} else {
		c.ShowMenu()
		return true
	}
	return false
}
483124
func (ed *Dispatcher) HandleConnectEvent(e esdispatcher.Event) {
	evt := e.(*ConnectEvent)

	if ed.connection != nil {
		// Already connected. No error.
		evt.ErrCh <- nil
		return
	}

	eventch, err := ed.EventCh()
	if err != nil {
		evt.ErrCh <- err
		return
	}

	peers, err := ed.discoveryService.GetPeers()
	if err != nil {
		evt.ErrCh <- err
		return
	}

	if len(peers) == 0 {
		evt.ErrCh <- errors.New("no peers to connect to")
		return
	}

	peer, err := ed.peerResolver.Resolve(peers)
	if err != nil {
		evt.ErrCh <- err
		return
	}

	conn, err := ed.connectionProvider(ed.context, ed.chConfig, peer)
	if err != nil {
		logger.Warnf("error creating connection: %s", err)
		evt.ErrCh <- errors.WithMessagef(err, "could not create client conn")
		return
	}

	ed.connection = conn
	ed.setConnectedPeer(peer)

	go ed.connection.Receive(eventch)

	evt.ErrCh <- nil
}
1032389
func (r *PolicyReactionEvent) Handle(res chan interface{}) {
	r.d.ReactToRuleUpdates(r.wg, r.epsToBumpRevision, r.endpointsToRegen, r.newRev)
}
762190
func unexpectedEventHandler(ctx *VmContext, ev VmEvent, state string) {
	switch ev.Event() {
	case COMMAND_SHUTDOWN,
		COMMAND_RELEASE,
		COMMAND_PAUSEVM:
		ctx.reportUnexpectedRequest(ev, state)
	default:
		ctx.Log(WARNING, "got unexpected event during ", state)
	}
}
228586
func (l *Linearizer) dispatchEvent(e *event) {
	defer l.md.Unlock()
	l.me.Lock()
	defer l.me.Unlock()
	if e.n+l.eventsSize > l.bufferSize {
		return
	}
	l.events = append(l.events, e)
	l.eventsSize += e.n
}
1080756
func handleDieEvent(engine *OrcEngine, event *adoc.Event) {
	actor := event.Actor
	if name, ok := actor.Attributes["name"]; ok {
		if pgname, _, instance, _, err := util.ParseContainerName(name); err == nil {
			engine.RLock()
			pgCtrl, ok := engine.pgCtrls[pgname]
			engine.RUnlock()
			if !ok {
				return
			}
			pgCtrl.RLock()
			spec := pgCtrl.spec.Clone()
			pgCtrl.RUnlock()
			if atomic.LoadInt32((*int32)(&pgCtrl.opState)) != PGOpStateUpgrading {
				log.Warnf("got %s event from %s, refresh this instance", event.Status, name)
				pgCtrl.opsChan <- pgOperRefreshInstance{instance, spec}
			}
		}
	}
}