Example application that sends an email when an alarm event is
    detected.
13336
def main():
    
    try:
        # Retrieve the first USB device
        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))

        # Set up an event handler and open the device
        device.on_alarm += handle_alarm
        with device.open(baudrate=BAUDRATE):
            while True:
                time.sleep(1)

    except Exception as ex:
        print('Exception:', ex)
765813
public static void alertUserOnFlowFinished(final ExecutableFlow flow, final AlerterHolder
      alerterHolder, final String[] extraReasons) {
    final ExecutionOptions options = flow.getExecutionOptions();
    final Alerter mailAlerter = alerterHolder.get("email");
    if (flow.getStatus() != Status.SUCCEEDED) {
      if (options.getFailureEmails() != null && !options.getFailureEmails().isEmpty()) {
        try {
          mailAlerter.alertOnError(flow, extraReasons);
        } catch (final Exception e) {
          logger.error("Failed to alert on error for execution " + flow.getExecutionId(), e);
        }
      }
      if (options.getFlowParameters().containsKey("alert.type")) {
        final String alertType = options.getFlowParameters().get("alert.type");
        final Alerter alerter = alerterHolder.get(alertType);
        if (alerter != null) {
          try {
            alerter.alertOnError(flow, extraReasons);
          } catch (final Exception e) {
            logger.error("Failed to alert on error by " + alertType + " for execution " + flow
                .getExecutionId(), e);
          }
        } else {
          logger.error("Alerter type " + alertType + " doesn't exist. Failed to alert.");
        }
      }
    } else {
      if (options.getSuccessEmails() != null && !options.getSuccessEmails().isEmpty()) {
        try {
          mailAlerter.alertOnSuccess(flow);
        } catch (final Exception e) {
          logger.error("Failed to alert on success for execution " + flow.getExecutionId(), e);
        }
      }
      if (options.getFlowParameters().containsKey("alert.type")) {
        final String alertType = options.getFlowParameters().get("alert.type");
        final Alerter alerter = alerterHolder.get(alertType);
        if (alerter != null) {
          try {
            alerter.alertOnSuccess(flow);
          } catch (final Exception e) {
            logger.error("Failed to alert on success by " + alertType + " for execution " + flow
                .getExecutionId(), e);
          }
        } else {
          logger.error("Alerter type " + alertType + " doesn't exist. Failed to alert.");
        }
      }
    }
  }
444616
public void alarm(Object alarmObj)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "alarm", alarmObj);
      
      // Has the async reader already sent a message back to the client?
      boolean sessionAvailable = true;
      if (!asynchReader.isComplete())
      {
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Async reader has not yet got a message");
         // If not stop the session...
         try 
         {
            try
            {
               asynchReader.stopSession();
            }
            catch (SISessionDroppedException e)
            {
               // No FFDC Code Needed
               if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Caught a SISessionDroppedException", e);
               sessionAvailable = false;
               
               // If the session was unavailable this may be because the connection has been closed 
               // while we were in a receiveWithWait(). In this case, we should try and send an error
               // back to the client, but not worry too much if we cannot
               if (asynchReader.isConversationClosed())
               {
                  if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) 
                     SibTr.debug(this, tc, "The Conversation was closed - no need to panic");
               }
               else
               {
                  // The Conversation was not closed, throw the exception on so we can inform
                  // the client
                  throw e;
               }
            }
            catch (SISessionUnavailableException e)
            {
               // No FFDC Code Needed
               if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Caught a SISessionUnavailableException", e);
               sessionAvailable = false;
               
               // See the comments above...
               if (asynchReader.isConversationClosed())
               {
                  if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) 
                     SibTr.debug(this, tc, "The Conversation was closed - no need to panic");
               }
               else
               {
                  throw e;
               }
            }
         }
         catch (SIException sis)
         {
            //No FFDC code needed
            //Only FFDC if we haven't received a meTerminated event.
            if(!asynchReader.hasMETerminated())
            {
               FFDCFilter.processException(sis, CLASS_NAME + ".alarm", 
                                           CommsConstants.CATTIMER_ALARM_01, this);
            }
            
            sessionAvailable = false;
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, sis.getMessage(), sis);
            
            asynchReader.sendErrorToClient(sis,
                                           CommsConstants.CATTIMER_ALARM_01);
         }
         finally
         {
            //At this point we should deregister asyncReader as a SICoreConnectionListener as the current receive with wait is pretty much finished.
            //Note that there is a bit of a timing window where asyncReader.consumeMessages could be called and we end up deregistering 
            //the listener twice but that is allowed by the API. We minimize this window by only doing a dereg if the asyncReader isn't complete.
            if(!asynchReader.isComplete())
            {
               try
               {
                  final MPConsumerSession mpSession = (MPConsumerSession) asynchReader.getCATMainConsumer().getConsumerSession();
                  mpSession.getConnection().removeConnectionListener(asynchReader);
               }
               catch(SIException e)
               {
                  //No FFDC code needed   
                  if(TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, e.getMessage(), e);
                  
                  //No need to send an exception back to the client in this case as we are only really performing tidy up processing.
                  //Also, if it is a really bad problem we are likely to have already send the exception back in the previous catch block.
               }
            }
         }
      }
      
      if (sessionAvailable)
      {
         // ...and check again.
         // If the async reader has still not sent a message at this point we
         // assume a timeout and inform the client
         if (asynchReader.isComplete())
         {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Async reader got a message");
         }
         else
         {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "No message received");
            
            asynchReader.sendNoMessageToClient();
         }
      }
            
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "alarm");
   }
1042283
def stop_notifying(cls, user_or_email, instance):
        """"""
        super(InstanceEvent, cls).stop_notifying(user_or_email,
                                                 object_id=instance.pk)
835634
def do_start_alerts(self, _):
        
        if self._alerter_thread.is_alive():
            print("The alert thread is already started")
        else:
            self._stop_thread = False
            self._alerter_thread = threading.Thread(name='alerter', target=self._alerter_thread_func)
            self._alerter_thread.start()
869617
public boolean sendHtmlEmail(String toEmail, String title, String content) {

        LOG.info("send to " + toEmail);
        LOG.info("title: " + title);
        LOG.info("content" + content);

        if (StringUtils.isBlank(toEmail)) {
            return false;
        }

        String localName = "";
        Visitor visitor = ThreadContext.getSessionVisitor();
        if (visitor != null) {
            LOG.info(visitor.toString());
            localName += visitor.getLoginUserName() + " ";
        }

        try {

            InetAddress addr = InetAddress.getLocalHost();
            localName += addr.getHostName().toString();

        } catch (UnknownHostException e) {

            LOG.warn("When send alarm mail,we can't get hostname", e);
        }

        String mailTitle = localName + "/" + getSystemDate();

        int len = 0;
        int lenLimit = ALARM_MAIL_TITLE_LENGTH;
        if (title != null) {
            len = title.length();
            if (len > lenLimit) {
                len = lenLimit;
            }
            mailTitle += title.substring(0, len);
        }

        String mailTo = toEmail;
        String mailFrom = emailProperties.getFromEmail();
        String[] mailToList = mailTo.split(";");

        if (content == null) {

            return false;

        } else {

            try {
                mailBean.sendHtmlMail(mailFrom, mailToList, mailTitle, content);
            } catch (Exception e) {
                LOG.error("When send alarm mail,we can't send it", e);
                return false;
            }
        }

        return true;
    }
619134
def create_alarm(self, check, notification_plan, criteria=None,
            disabled=False, label=None, name=None, metadata=None):
        
        return self._alarm_manager.create(check, notification_plan,
                criteria=criteria, disabled=disabled, label=label, name=name,
                metadata=metadata)
542552
private boolean sendErrorMail(String content, String title) {

        String localName = "";

        try {

            InetAddress addr = InetAddress.getLocalHost();
            localName = addr.getHostName().toString();

        } catch (UnknownHostException e) {

            LOG.warn("When send alarm mail,we can't get hostname", e);
        }

        String mailTitle = localName + " /" + ALARM_MAIL_TITLE + "/" + getSystemDate();

        int len = 0;
        int lenLimit = ALARM_MAIL_TITLE_LENGTH;
        if (title != null) {
            len = title.length();
            if (len > lenLimit) {
                len = lenLimit;
            }
            mailTitle += title.substring(0, len);
        }

        String mailTo = emailProperties.getEmailReceiver();
        String mailFrom = emailProperties.getFromEmail();
        String[] mailToList = mailTo.split(";");

        if (content == null) {

            return false;

        } else {

            try {
                mailBean.sendHtmlMail(mailFrom, mailToList, mailTitle, content);
            } catch (Exception e) {
                LOG.warn("When send alarm mail,we can't send it", e);
                return false;
            }
        }
        return true;
    }
341398
protected void sendWardenEmailToUser(NotificationContext context, SubSystem subSystem) {
        EntityManager em = emf.get();
        PrincipalUser user = getWardenUser(context.getAlert().getName());
        SuspensionRecord record = SuspensionRecord.findByUserAndSubsystem(em, user, subSystem);
        Set<String> to = new HashSet<>();

        to.add(user.getEmail());

        String subject = "Warden Email Notification";
        StringBuilder message = new StringBuilder();

        message.append(MessageFormat.format("<p>{0} has been suspended from the Argus system for violating the following policy</p>",
                user.getUserName()));
        message.append(MessageFormat.format("Subsystem: {0}", subSystem.toString()));
        message.append(MessageFormat.format("<br>Policy: {0}",
                context.getAlert().getName().replace(WARDEN_ALERT_NAME_PREFIX + user.getUserName() + "-", "")));
        message.append(MessageFormat.format("<br>Threshold: {0}", context.getAlert().getTriggers().get(0).getThreshold()));
        message.append(MessageFormat.format("<br>Triggering Value: {0}", context.getTriggerEventValue()));
        if (record.getSuspendedUntil() == -1) {
            message.append("<br> You have been suspended indefinitely");
        } else {
            message.append(MessageFormat.format("<br>Reinstatement Time: {0}", DATE_FORMATTER.get().format(new Date(record.getSuspendedUntil()))));
        }
        _mailService.sendMessage(to, subject, message.toString(), "text/html; charset=utf-8", MailService.Priority.HIGH);
        to.clear();
        to.add("argus-admin@salesforce.com");
        message.append("<p><a href='").append(getAlertUrl(context.getAlert().getId())).append("'>Click here to view alert definition.</a><br/>");
        _mailService.sendMessage(to, subject, message.toString(), "text/html; charset=utf-8", MailService.Priority.HIGH);
    }
640231
def emit(self, action, event):
        
        NotificationManager.instance().emit(action, event, project_id=self.id)
163926
function (notifyText) {
			this.writeDebug('notify',notifyText);
			if (this.settings.callbackNotify) {
				this.settings.callbackNotify.call(this, notifyText);
			}
			else {
				alert(notifyText);
			}
		}
1220354
def notify(condition, message)
      spec = Contact.normalize(condition.notify)
      unmatched = []

      # Resolve contacts.
      resolved_contacts =
      spec[:contacts].inject([]) do |acc, contact_name_or_group|
        cons = Array(God.contacts[contact_name_or_group] || God.contact_groups[contact_name_or_group])
        unmatched << contact_name_or_group if cons.empty?
        acc += cons
        acc
      end

      # Warn about unmatched contacts.
      unless unmatched.empty?
        msg = "#{condition.watch.name} no matching contacts for '#{unmatched.join(", ")}'"
        applog(condition.watch, :warn, msg)
      end

      # Notify each contact.
      resolved_contacts.each do |c|
        host = `hostname`.chomp rescue 'none'
        begin
          c.notify(message, Time.now, spec[:priority], spec[:category], host)
          msg = "#{condition.watch.name} #{c.info ? c.info : "notification sent for contact: #{c.name}"} (#{c.base_name})"
          applog(condition.watch, :info, msg % [])
        rescue Exception => e
          applog(condition.watch, :error, "#{e.message} #{e.backtrace}")
          msg = "#{condition.watch.name} Failed to deliver notification for contact: #{c.name} (#{c.base_name})"
          applog(condition.watch, :error, msg % [])
        end
      end
    end
346245
def acknowledge_alarm(self, alarm, comment=None):
        
        url = '/processors/{}/{}/parameters{}/alarms/{}'.format(
            self._instance, self._processor, alarm.name, alarm.sequence_number)
        req = rest_pb2.EditAlarmRequest()
        req.state = 'acknowledged'
        if comment is not None:
            req.comment = comment
        self._client.put_proto(url, data=req.SerializeToString())
1304488
def email_alerts(action,
                 host=None,
                 admin_username=None,
                 admin_password=None):
    '''
    
    '''

    if action:
        return __execute_cmd('config -g cfgEmailAlert -o '
                             'cfgEmailAlertEnable -i 1 1', host=host,
                             admin_username=admin_username,
                             admin_password=admin_password)
    else:
        return __execute_cmd('config -g cfgEmailAlert -o '
                             'cfgEmailAlertEnable -i 1 0')
824263
def alert_stream(self, reset_event, kill_event):
        """"""
        _LOGGING.debug('Stream Thread Started: %s, %s', self.name, self.cam_id)
        start_event = False
        parse_string = ""
        fail_count = 0

        url = '%s/ISAPI/Event/notification/alertStream' % self.root_url

        # pylint: disable=too-many-nested-blocks
        while True:

            try:
                stream = self.hik_request.get(url, stream=True,
                                              timeout=(CONNECT_TIMEOUT,
                                                       READ_TIMEOUT))
                if stream.status_code == requests.codes.not_found:
                    # Try alternate URL for stream
                    url = '%s/Event/notification/alertStream' % self.root_url
                    stream = self.hik_request.get(url, stream=True)

                if stream.status_code != requests.codes.ok:
                    raise ValueError('Connection unsucessful.')
                else:
                    _LOGGING.debug('%s Connection Successful.', self.name)
                    fail_count = 0
                    self.watchdog.start()

                for line in stream.iter_lines():
                    # _LOGGING.debug('Processing line from %s', self.name)
                    # filter out keep-alive new lines
                    if line:
                        str_line = line.decode("utf-8", "ignore")
                        # New events start with --boundry
                        if str_line.find('<EventNotificationAlert') != -1:
                            # Start of event message
                            start_event = True
                            parse_string += str_line
                        elif str_line.find('</EventNotificationAlert>') != -1:
                            # Message end found found
                            parse_string += str_line
                            start_event = False
                            if parse_string:
                                tree = ET.fromstring(parse_string)
                                self.process_stream(tree)
                                self.update_stale()
                                parse_string = ""
                        else:
                            if start_event:
                                parse_string += str_line

                    if kill_event.is_set():
                        # We were asked to stop the thread so lets do so.
                        break
                    elif reset_event.is_set():
                        # We need to reset the connection.
                        raise ValueError('Watchdog failed.')

                if kill_event.is_set():
                    # We were asked to stop the thread so lets do so.
                    _LOGGING.debug('Stopping event stream thread for %s',
                                   self.name)
                    self.watchdog.stop()
                    self.hik_request.close()
                    return
                elif reset_event.is_set():
                    # We need to reset the connection.
                    raise ValueError('Watchdog failed.')

            except (ValueError,
                    requests.exceptions.ConnectionError,
                    requests.exceptions.ChunkedEncodingError) as err:
                fail_count += 1
                reset_event.clear()
                _LOGGING.warning('%s Connection Failed (count=%d). Waiting %ss. Err: %s',
                                 self.name, fail_count, (fail_count * 5) + 5, err)
                parse_string = ""
                self.watchdog.stop()
                self.hik_request.close()
                time.sleep(5)
                self.update_stale()
                time.sleep(fail_count * 5)
                continue
369834
public JsonResponse deleteAlert(String email, String alertId) throws IOException {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put(Alert.PARAM_EMAIL, email);
        data.put(Alert.PARAM_ALERT_ID, alertId);
        return apiDelete(ApiAction.alert, data);
    }
502984
public void alarm(Object alarmContext)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(this, tc, "alarm", alarmContext);

    // Alarm context should be an sid, make it so.
    SIBUuid12 sid = (SIBUuid12) alarmContext;

    // synchronized here in case we're racing with an answer to our
    // query.
    synchronized (flushMap)
    {
      // See if the query record is still around
      FlushQueryRecord entry = flushMap.get(sid);

      if (entry != null)
      {
        // Query still active, see if we need to restart.
        entry.attempts--;
        if (entry.attempts > 0)
        {
          // Yup, resend the query and reset the alarm.  If
          // entry.cached is null, then this is a "request flush"
          // rather than an "are you flushed".
          try
          {
            if (entry.cache == null)
            {
              upControl.sendRequestFlushMessage(entry.source,
                                                entry.destId,
                                                entry.busId,
                                                entry.requestID,
                                                sid,
                                                false);  //TODO check indoubtDiscard
            }
            else
            {
              upControl.sendAreYouFlushedMessage(entry.source,
                                                 entry.destId,
                                                 entry.busId,
                                                 entry.requestID, sid);
            }
          }
          catch (SIResourceException e)
          {
            // No FFDC code needed

            // If we run out of resources, then give up on the query
            // and log an error.  This is probably only important for
            // "request flush" queries.
            flushMap.remove(sid);

            // TODO: actually, this should be an admin message.
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
              SibTr.event(tc, "Flush query failed for stream: " + sid);
          }

        }
        else
        {
          // Nope, didn't work.  Remove the query record, log the event,
          // and exit.
          flushMap.remove(sid);
          // TODO: actually, this should be an admin message.
          if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
            SibTr.event(tc, "Flush query expired for stream: " + sid);
        }
      }
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "alarm");
  }