// HandleEvent handles incoming events.  The only events handled are
// those for the Text objects; when those change, the TextBar adjusts
// the layout to accommodate.
550909
func (t *TextBar) HandleEvent(ev tcell.Event) bool {
	switch ev.(type) {
	case *EventWidgetContent:
		t.changed = true
		return true
	}
	return false
}
1011778
func (p *Parser) handleEvent(rawEvent []string) *event.Event {
	normalizer := normalizer.Parser{}
	if len(rawEvent) == 0 {
		return nil
	}
	firstLine := rawEvent[0]

	// First, try to parse the prefix
	match, suffix, generalMeta := parsePrefix(p.pgPrefixRegex, firstLine)
	if !match {
		// Note: this may be noisy when debug logging is turned on, since the
		// postgres general log contains lots of other statements as well.
		logrus.WithField("line", firstLine).Debug("Log line prefix didn't match expected format")
		return nil
	}

	ev := &event.Event{
		Data: make(map[string]interface{}, 0),
	}

	addFieldsToEvent(generalMeta, ev)

	// Now, parse the slow query header
	match, query, slowQueryMeta := parsePrefix(slowQueryHeaderRegex, suffix)

	if !match {
		logrus.WithField("line", firstLine).Debug("didn't find slow query header, skipping line")
		return nil
	}

	if rawDuration, ok := slowQueryMeta["duration"]; ok {
		duration, _ := strconv.ParseFloat(rawDuration, 64)
		ev.Data["duration"] = duration
	} else {
		logrus.WithField("query", query).Debug("Failed to find query duration in log line")
	}

	// Finally, concatenate the remaining text to form the query, and attempt to
	// normalize it.
	for _, line := range rawEvent[1:] {
		query += " " + strings.TrimLeft(line, " \t")
	}
	normalizedQuery := normalizer.NormalizeQuery(query)

	ev.Data["query"] = query
	ev.Data["normalized_query"] = normalizedQuery
	if len(normalizer.LastTables) > 0 {
		ev.Data["tables"] = strings.Join(normalizer.LastTables, " ")
	}
	if len(normalizer.LastComments) > 0 {
		ev.Data["comments"] = "/* " + strings.Join(normalizer.LastComments, " */ /* ") + " */"
	}

	return ev
}
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)
}
343098
func (s *Subscription) Handle(es string, h HandlerFunc) error {
	if _, ok := validEvents[es]; !ok {
		return fmt.Errorf("unknown event: %s", es)
	}

	s.lock.Lock()
	s.handlers[es] = h
	s.lock.Unlock()
	return nil
}
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
}
658683
func (p *Parser) handleEvents(rawEvents <-chan []string, send chan<- event.Event, wg *sync.WaitGroup) {
	defer wg.Done()
	// TODO: spin up a group of goroutines to do this
	for rawEvent := range rawEvents {
		ev := p.handleEvent(rawEvent)
		if ev != nil {
			send <- *ev
		}
	}
}
842040
func eventHandler(w http.ResponseWriter, r *http.Request) {
	if r.Body != nil {
		defer r.Body.Close()
	}

	ctx := r.Context()

	switch r.Method {
	// Get all events
	case http.MethodGet:
		events, err := getEvents(Configuration.Service.ReadMaxLimit)
		if err != nil {
			LoggingClient.Error(err.Error())
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		encode(events, w)
		break
		// Post a new event
	case http.MethodPost:
		contentType := r.Header.Get(clients.ContentType)
		if contentType == clients.ContentTypeCBOR {
			errMsg := "CBOR payload is not yet supported"
			http.Error(w, errMsg, http.StatusNotImplemented)
			LoggingClient.Error(errMsg)

			return
		}

		var e models.Event
		dec := json.NewDecoder(r.Body)
		err := dec.Decode(&e)

		// Problem Decoding Event
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			LoggingClient.Error("Error decoding event: " + err.Error())
			return
		}

		LoggingClient.Info("Posting Event: " + e.String())

		newId, err := addNewEvent(e, ctx)
		if err != nil {
			switch t := err.(type) {
			case *errors.ErrValueDescriptorNotFound:
				http.Error(w, t.Error(), http.StatusBadRequest)
			case *errors.ErrValueDescriptorInvalid:
				http.Error(w, t.Error(), http.StatusBadRequest)
			default:
				http.Error(w, t.Error(), http.StatusInternalServerError)
			}
			LoggingClient.Error(err.Error())
			return
		}

		w.WriteHeader(http.StatusOK)
		w.Write([]byte(newId))

		break
		// Do not update the readings
	case http.MethodPut:
		contentType := r.Header.Get(clients.ContentType)
		if contentType == clients.ContentTypeCBOR {
			errMsg := "CBOR payload is not yet supported"
			http.Error(w, errMsg, http.StatusNotImplemented)
			LoggingClient.Error(errMsg)

			return
		}

		var from models.Event
		dec := json.NewDecoder(r.Body)
		err := dec.Decode(&from)

		// Problem decoding event
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			LoggingClient.Error("Error decoding the event: " + err.Error())
			return
		}

		LoggingClient.Info("Updating event: " + from.ID)
		err = updateEvent(from, ctx)
		if err != nil {
			switch t := err.(type) {
			case *errors.ErrEventNotFound:
				http.Error(w, t.Error(), http.StatusNotFound)
			default:
				http.Error(w, t.Error(), http.StatusInternalServerError)
			}
			LoggingClient.Error(err.Error())
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("true"))
	}
}
667067
func (r Rule) Handle(h events.Handler) Rule {
	return Rules{r, Handle(h)}.Eval
}
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)
	}
}
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
}
897554
func (b *BoxLayout) HandleEvent(ev tcell.Event) bool {
	switch ev.(type) {
	case *EventWidgetContent:
		// This can only have come from one of our children.
		b.changed = true
		b.PostEventWidgetContent(b)
		return true
	}
	for _, c := range b.cells {
		if c.widget.HandleEvent(ev) {
			return true
		}
	}
	return false
}
824681
func (g *Gui) handleEvent(ev *termbox.Event) error {
	switch ev.Type {
	case termbox.EventKey, termbox.EventMouse:
		return g.onKey(ev)
	case termbox.EventError:
		return ev.Err
	default:
		return nil
	}
}
693833
func (i *instanceManager) handleEvents() {
	eventsCh, cancel, err := i.dispenseTaskEventsCh()
	if err != nil {
		i.logger.Error("failed to dispense driver", "error", err)
	}

	var backoff time.Duration
	var retry int
	for {
		if backoff > 0 {
			select {
			case <-time.After(backoff):
			case <-i.ctx.Done():
				cancel()
				return
			}
		}

		select {
		case <-i.ctx.Done():
			cancel()
			return
		case ev, ok := <-eventsCh:
			if ok {
				i.handleEvent(ev)
				continue
			}

			// if the channel is closed attempt to open a new one
			newEventsChan, newCancel, err := i.dispenseTaskEventsCh()
			if err != nil {
				i.logger.Warn("failed to receive task events, retrying", "error", err, "retry", retry)

				// Calculate the new backoff
				backoff = (1 << (2 * uint64(retry))) * driverFPBackoffBaseline
				if backoff > driverFPBackoffLimit {
					backoff = driverFPBackoffLimit
				}
				retry++
				continue
			}
			cancel()
			eventsCh = newEventsChan
			cancel = newCancel

			// Reset backoff
			backoff = 0
			retry = 0
		}
	}
}
73523
func (c *Client) SimpleEvent(title, text string) error {
	e := NewEvent(title, text)
	return c.Event(e)
}
196136
func (hs Handlers) HandleEvent(ctx context.Context, e *executor.Event) (err error) {
	if h := hs[e.GetType()]; h != nil {
		return h.HandleEvent(ctx, e)
	}
	return nil
}
1178273
func (r *Router) HandleFunc(event string, fn func(http.ResponseWriter, *http.Request)) {
	r.Handle(event, http.HandlerFunc(fn))
}
1223280
func (eh rateLimitEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*RateLimit); ok {
		eh(s, t)
	}
}