<commit_before>//
// This file is part of the OpenNMS(R) Application.
//
// OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc.  All rights reserved.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// code that was published under the GNU General Public License. Copyrights for modified 
// and included code are below.
//
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//
// 2007 Jun 29: Move filter matching code to JdbcFilterDao and organize imports. - <EMAIL>
// 2006 Apr 07: Changed replaceNotification to handle preserving the order.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.                                                            
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//    
// For more information contact: 
//   OpenNMS Licensing       <<EMAIL>>
//   http://www.opennms.org/
//   http://www.opennms.com/
//
// Tab Size = 8

package org.opennms.netmgt.config;

import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.sql.DataSource;

import org.apache.log4j.Category;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.common.Header;
import org.opennms.netmgt.config.notifications.Notification;
import org.opennms.netmgt.config.notifications.Notifications;
import org.opennms.netmgt.config.notifications.Parameter;
import org.opennms.netmgt.eventd.EventUtil;
import org.opennms.netmgt.filter.FilterDaoFactory;
import org.opennms.netmgt.filter.FilterParseException;
import org.opennms.netmgt.utils.Querier;
import org.opennms.netmgt.utils.RowProcessor;
import org.opennms.netmgt.utils.SingleResultQuerier;
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Tticket;
import org.springframework.util.Assert;

/**
 * @author <NAME> <<EMAIL>>
 * This base class was refactored from NotificationFactory to support non-global
 * references during JUnit testing and later to support distributed processes.
 */
public abstract class NotificationManager {

    /**
     * Object containing all Notification objects parsed from the xml file
     */
    public Notifications m_notifications;
    /**
     * 
     */
    private Header oldHeader;
    public static final String PARAM_TYPE = "-t";
    public static final String PARAM_DESTINATION = "-d";
    public static final String PARAM_TEXT_MSG = "-tm";
    public static final String PARAM_NUM_MSG = "-nm";
    public static final String PARAM_RESPONSE = "-r";
    public static final String PARAM_NODE = "-nodeid";
    public static final String PARAM_INTERFACE = "-interface";
    public static final String PARAM_SERVICE = "-service";
    public static final String PARAM_SUBJECT = "-subject";
    public static final String PARAM_EMAIL = "-email";
    public static final String PARAM_PAGER_EMAIL = "-pemail";
    public static final String PARAM_XMPP_ADDRESS = "-xmpp";
    public static final String PARAM_TEXT_PAGER_PIN = "-tp";
    public static final String PARAM_NUM_PAGER_PIN = "-np";
    
    NotifdConfigManager m_configManager;
    private DataSource m_dbConnectionFactory;
    
    
    /**
     * @param configIn
     * @throws MarshalException
     * @throws ValidationException
     */
    protected NotificationManager(NotifdConfigManager configManager, DataSource dcf) {
        m_configManager = configManager;
        m_dbConnectionFactory = dcf;
    }

    public synchronized void parseXML(Reader reader) throws MarshalException, ValidationException {
        m_notifications = (Notifications) Unmarshaller.unmarshal(Notifications.class, reader);
        oldHeader = m_notifications.getHeader();
    }

    public boolean hasUei(String uei) throws IOException, MarshalException, ValidationException {
        update();
    
        for (Enumeration e = m_notifications.enumerateNotification(); e.hasMoreElements();) {
            Notification notif = (Notification) e.nextElement();
  
            if (uei.equals(notif.getUei()) || "MATCH-ANY-UEI".equals(notif.getUei())) {
                 return true;
            } else if (notif.getUei().charAt(0) == '~') {
               if (uei.matches(notif.getUei().substring(1))) {
                       return true;
               }
    
            }
        }
    
        return false;
    }
    
    public Notification[] getNotifForEvent(Event event) throws IOException, MarshalException, ValidationException {
        update();
        List<Notification> notifList = new ArrayList<Notification>();
        Notification[] notif = null;
        boolean matchAll = getConfigManager().getNotificationMatch();
        Category log = ThreadCategory.getInstance(getClass());
    
        for (Enumeration e = m_notifications.enumerateNotification(); e.hasMoreElements();) {
            Notification curNotif = (Notification) e.nextElement();
    
            boolean curHasUei = false;
            boolean curHasSeverity = false;

            log.debug("Checking " + event.getUei() + " against " + curNotif.getUei());
 
            if (event.getUei().equals(curNotif.getUei()) || "MATCH-ANY-UEI".equals(curNotif.getUei())) {
               curHasUei = true;
            } else if (curNotif.getUei().charAt(0) == '~') {
               if (event.getUei().matches(curNotif.getUei().substring(1))) {
                       curHasUei = true;
               }
            }

            /**
             * Check if event severity matches pattern in notification
             */
            log.debug("Checking event severity: " + event.getSeverity() + " against notification severity: " + curNotif.getEventSeverity());
            // parameter is optional, return true if not set
            if (curNotif.getEventSeverity() == null) {
               curHasSeverity = true;
            } else if (event.getSeverity().toLowerCase().matches(curNotif.getEventSeverity().toLowerCase())) {
               curHasSeverity = true;
            }
           
            if (curNotif.getStatus().equals("on") && curHasSeverity && (curHasUei || "MATCH-ANY-UEI".equals(curNotif.getUei()) && (nodeInterfaceServiceValid(curNotif, event) || !event.hasNodeid()))) {
                boolean parmsmatched = getConfigManager().matchNotificationParameters(event, curNotif);

                if (!parmsmatched) {
                    log().debug("Event " + event.getUei() + " did not match parameters for notice " + curNotif.getName());
                    continue;
                }
                notifList.add(curNotif);

                log().debug("Event " + event.getUei() + " matched notice " + curNotif.getName());
                
                if (!matchAll)
                    break;
            }
        }
    
        if (!notifList.isEmpty()) {
            notif = (Notification[]) notifList.toArray(new Notification[0]);
        }
        return notif;
    }

    private Category log() {<commit_msg>Start working on 1.3.5 fixes to notifications.<commit_after>//
// This file is part of the OpenNMS(R) Application.
//
// OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc.  All rights reserved.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// code that was published under the GNU General Public License. Copyrights for modified 
// and included code are below.
//
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//
// 2007 Jun 29: Move filter matching code to JdbcFilterDao and organize imports. - <EMAIL>
// 2006 Apr 07: Changed replaceNotification to handle preserving the order.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.                                                            
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//    
// For more information contact: 
//   OpenNMS Licensing       <<EMAIL>>
//   http://www.opennms.org/
//   http://www.opennms.com/
//
// Tab Size = 8

package org.opennms.netmgt.config;

import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.sql.DataSource;

import org.apache.log4j.Category;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.common.Header;
import org.opennms.netmgt.config.notifications.Notification;
import org.opennms.netmgt.config.notifications.Notifications;
import org.opennms.netmgt.config.notifications.Parameter;
import org.opennms.netmgt.eventd.EventUtil;
import org.opennms.netmgt.filter.FilterDaoFactory;
import org.opennms.netmgt.filter.FilterParseException;
import org.opennms.netmgt.utils.Querier;
import org.opennms.netmgt.utils.RowProcessor;
import org.opennms.netmgt.utils.SingleResultQuerier;
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Tticket;
import org.springframework.util.Assert;

/**
 * @author <NAME> <<EMAIL>>
 * This base class was refactored from NotificationFactory to support non-global
 * references during JUnit testing and later to support distributed processes.
 */
public abstract class NotificationManager {

    /**
     * Object containing all Notification objects parsed from the xml file
     */
    public Notifications m_notifications;
    /**
     * 
     */
    private Header oldHeader;
    public static final String PARAM_TYPE = "-t";
    public static final String PARAM_DESTINATION = "-d";
    public static final String PARAM_TEXT_MSG = "-tm";
    public static final String PARAM_NUM_MSG = "-nm";
    public static final String PARAM_RESPONSE = "-r";
    public static final String PARAM_NODE = "-nodeid";
    public static final String PARAM_INTERFACE = "-interface";
    public static final String PARAM_SERVICE = "-service";
    public static final String PARAM_SUBJECT = "-subject";
    public static final String PARAM_EMAIL = "-email";
    public static final String PARAM_PAGER_EMAIL = "-pemail";
    public static final String PARAM_XMPP_ADDRESS = "-xmpp";
    public static final String PARAM_TEXT_PAGER_PIN = "-tp";
    public static final String PARAM_NUM_PAGER_PIN = "-np";
    
    NotifdConfigManager m_configManager;
    private DataSource m_dbConnectionFactory;
    
    
    /**
     * @param configIn
     * @throws MarshalException
     * @throws ValidationException
     */
    protected NotificationManager(NotifdConfigManager configManager, DataSource dcf) {
        m_configManager = configManager;
        m_dbConnectionFactory = dcf;
    }

    public synchronized void parseXML(Reader reader) throws MarshalException, ValidationException {
        m_notifications = (Notifications) Unmarshaller.unmarshal(Notifications.class, reader);
        oldHeader = m_notifications.getHeader();
    }

    public boolean hasUei(String uei) throws IOException, MarshalException, ValidationException {
        update();
    
        for (Enumeration e = m_notifications.enumerateNotification(); e.hasMoreElements();) {
            Notification notif = (Notification) e.nextElement();
  
            if (uei.equals(notif.getUei()) || "MATCH-ANY-UEI".equals(notif.getUei())) {
                 return true;
            } else if (notif.getUei().charAt(0) == '~') {
               if (uei.matches(notif.getUei().substring(1))) {
                       return true;
               }
    
            }
        }
    
        return false;
    }
    
    public Notification[] getNotifForEvent(Event event) throws IOException, MarshalException, ValidationException {
        update();
        List<Notification> notifList = new ArrayList<Notification>();
        Notification[] notif = null;
        boolean matchAll = getConfigManager().getNotificationMatch();
        Category log = ThreadCategory.getInstance(getClass());
    
        for (Enumeration e = m_notifications.enumerateNotification(); e.hasMoreElements();) {
            Notification curNotif = (Notification) e.nextElement();
    
            boolean curHasUei = false;
            boolean curHasSeverity = false;

            log.debug("Checking " + event.getUei() + " against " + curNotif.getUei());
 
            if (event.getUei().equals(curNotif.getUei()) || "MATCH-ANY-UEI".equals(curNotif.getUei())) {
               curHasUei = true;
            } else if (curNotif.getUei().charAt(0) == '~') {
               if (event.getUei().matches(curNotif.getUei().substring(1))) {
                       curHasUei = true;
               }
            }

            /**
             * Check if event severity matches pattern in notification
             */
            log.debug("Checking event severity: " + event.getSeverity() + " against notification severity: " + curNotif.getEventSeverity());
            // parameter is optional, return true if not set
            if (curNotif.getEventSeverity() == null) {
               curHasSeverity = true;
            } else if (event.getSeverity().toLowerCase().matches(curNotif.getEventSeverity().toLowerCase())) {
               curHasSeverity = true;
            }
           
            // The notice has to be "on"
            // The notice has to match a severity if configured - currHasSeverity should be true if there is no severity rule 
            // The notice has to match the UEI of the event or MATCH-ANY-UEI
            // If all those things are true:
            // Then the service has to match if configured, the interface if configured, and the node if configured.

            if (curNotif.getStatus().equals("on") && curHasSeverity && curHasUei && nodeInterfaceServiceValid(curNotif, event)) {
                boolean parmsmatched = getConfigManager().matchNotificationParameters(event, curNotif);

                if (!parmsmatched) {
                    log().debug("Event " + event.getUei() + " did not match parameters for notice " + curNotif.getName());
                    continue;
                }
                notifList.add(curNotif);

                log().debug("Event " + event.getUei() + " matched notice " + curNotif.getName());
                
                if (!matchAll)
                    break;
            }
        }
    
        if (!notifList.isEmpty()) {
            notif = (Notification[]) notifList.toArray(new Notification[0]);
        }
        return notif;
    }

    private Category log() {
{'fraction_non_alphanumeric': 0.10200429491768075, 'fraction_numerical': 0.004712479121927941, 'mean_word_length': 2.744695108331472, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 14}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6275728', 'n_tokens_mistral': 4758, 'n_tokens_neox': 4636, 'n_words': 1300}