<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.
 *
 * Original code base Copyright (C) 1999-2001 Oculan Corp.  All rights reserved.
 *
 * 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/
 */
package org.opennms.mock.snmp;

import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.util.Iterator;
import java.util.List;

import org.snmp4j.TransportMapping;
import org.snmp4j.agent.BaseAgent;
import org.snmp4j.agent.CommandProcessor;
import org.snmp4j.agent.DuplicateRegistrationException;
import org.snmp4j.agent.ManagedObject;
import org.snmp4j.agent.io.ImportModes;
import org.snmp4j.agent.mo.MOTableRow;
import org.snmp4j.agent.mo.snmp.RowStatus;
import org.snmp4j.agent.mo.snmp.SnmpCommunityMIB;
import org.snmp4j.agent.mo.snmp.SnmpNotificationMIB;
import org.snmp4j.agent.mo.snmp.SnmpTargetMIB;
import org.snmp4j.agent.mo.snmp.StorageType;
import org.snmp4j.agent.mo.snmp.TransportDomains;
import org.snmp4j.agent.mo.snmp.VacmMIB;
import org.snmp4j.log.Log4jLogFactory;
import org.snmp4j.log.LogFactory;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.MessageProcessingModel;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.PrivDES;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModel;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.Counter32;
import org.snmp4j.smi.Counter64;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.Variable;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.ThreadPool;
import org.springframework.core.io.Resource;

/*
 * The <code>MockSnmpAgent</code> class extends the SNMP4J BaseAgent
 * class to provide a mock SNMP agent for SNMP-based OpenNMS tests.
 * Large chunks of code were lifted from the org.snmp4j.agent.test.TestAgent
 * class.
 * 
 * @author <NAME>
 * @version 1.0
 */
public class MockSnmpAgent extends BaseAgent implements Runnable {

    // initialize Log4J logging
    static {
        LogFactory.setLogFactory(new Log4jLogFactory());
    }
    

    protected String m_address;
    private Resource m_moFile;
    private boolean m_running;
    private boolean m_stopped;
    private List<ManagedObject> m_moList;
    private MockSnmpMOLoader m_moLoader;

    /*
     * Creates the mock agent with files to read and store the boot counter,
     * to read and store the agent configuration, and to read the mocked
     * managed objects (MOs), plus a string describing the address and port
     * to bind to.
     * 
     * @param bootFile
     * 		a file containing the boot counter in serialized form (as expected by BaseAgent).
     * @param confFile
     * 		a configuration file with serialized management information.
     * @param moFile
     * 		a MIB dump file describing the managed objects to be mocked.  The current implementation
     * 		expects a Java properties file, which can conveniently be generated using the Net-SNMP
     * 		utility <code>snmpwalk</code> with the <code>-One</code> option set.
     */
    public MockSnmpAgent(File bootFile, File confFile, Resource moFile, String bindAddress) {
        super(bootFile, confFile, new CommandProcessor(new OctetString(MPv3.createLocalEngineID())));
        m_address = bindAddress;
        m_moFile = moFile;
        agent.setThreadPool(ThreadPool.create("RequestPool", 4));
    }

    public static MockSnmpAgent createAgentAndRun(Resource moFile, String bindAddress) throws InterruptedException {
        try {
            if (moFile.getInputStream() == null) {
                throw new IllegalArgumentException("could not get InputStream mock object resource; does it exist?  Resource: " + moFile);
            }
        } catch (IOException e) {
            throw new RuntimeException("Got IOException while checking for existence of mock object file: " + e, e);
        }
        
        MockSnmpAgent agent = new MockSnmpAgent(new File("/dev/null"), new File("/dev/null"), moFile, bindAddress);
        Thread thread = new Thread(agent);
        thread.start();

        try {
            while (!agent.isRunning() && thread.isAlive()) {
                Thread.sleep(10);
            } 
        } catch (InterruptedException e) {
            agent.shutDownAndWait();
            throw e;
        }

        if (!thread.isAlive()) {
            agent.m_running = false;
            agent.m_stopped = true;
            throw new IllegalStateException("agent failed to start--check logs");
        }

        return agent;
    }

    public void shutDownAndWait() throws InterruptedException {
        if (!isRunning()) {
            return;<commit_msg>Add a really primitive main() method to MockSnmpAgent as a first step toward making it something we can distribute as a standalone agent simulator<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.
 *
 * Original code base Copyright (C) 1999-2001 Oculan Corp.  All rights reserved.
 *
 * 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/
 */
package org.opennms.mock.snmp;

import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.util.Iterator;
import java.util.List;

import org.snmp4j.TransportMapping;
import org.snmp4j.agent.BaseAgent;
import org.snmp4j.agent.CommandProcessor;
import org.snmp4j.agent.DuplicateRegistrationException;
import org.snmp4j.agent.ManagedObject;
import org.snmp4j.agent.io.ImportModes;
import org.snmp4j.agent.mo.MOTableRow;
import org.snmp4j.agent.mo.snmp.RowStatus;
import org.snmp4j.agent.mo.snmp.SnmpCommunityMIB;
import org.snmp4j.agent.mo.snmp.SnmpNotificationMIB;
import org.snmp4j.agent.mo.snmp.SnmpTargetMIB;
import org.snmp4j.agent.mo.snmp.StorageType;
import org.snmp4j.agent.mo.snmp.TransportDomains;
import org.snmp4j.agent.mo.snmp.VacmMIB;
import org.snmp4j.log.Log4jLogFactory;
import org.snmp4j.log.LogFactory;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.MessageProcessingModel;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.PrivDES;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModel;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.Counter32;
import org.snmp4j.smi.Counter64;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.Variable;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.ThreadPool;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/*
 * The <code>MockSnmpAgent</code> class extends the SNMP4J BaseAgent
 * class to provide a mock SNMP agent for SNMP-based OpenNMS tests.
 * Large chunks of code were lifted from the org.snmp4j.agent.test.TestAgent
 * class.
 * 
 * @author <NAME>
 * @version 1.0
 */
public class MockSnmpAgent extends BaseAgent implements Runnable {

    // initialize Log4J logging
    static {
        LogFactory.setLogFactory(new Log4jLogFactory());
    }
    

    protected String m_address;
    private Resource m_moFile;
    private boolean m_running;
    private boolean m_stopped;
    private List<ManagedObject> m_moList;
    private MockSnmpMOLoader m_moLoader;

    /*
     * Creates the mock agent with files to read and store the boot counter,
     * to read and store the agent configuration, and to read the mocked
     * managed objects (MOs), plus a string describing the address and port
     * to bind to.
     * 
     * @param bootFile
     * 		a file containing the boot counter in serialized form (as expected by BaseAgent).
     * @param confFile
     * 		a configuration file with serialized management information.
     * @param moFile
     * 		a MIB dump file describing the managed objects to be mocked.  The current implementation
     * 		expects a Java properties file, which can conveniently be generated using the Net-SNMP
     * 		utility <code>snmpwalk</code> with the <code>-One</code> option set.
     */
    public MockSnmpAgent(File bootFile, File confFile, Resource moFile, String bindAddress) {
        super(bootFile, confFile, new CommandProcessor(new OctetString(MPv3.createLocalEngineID())));
        m_address = bindAddress;
        m_moFile = moFile;
        agent.setThreadPool(ThreadPool.create("RequestPool", 4));
    }
    
    public static MockSnmpAgent createAgentAndRun(Resource moFile, String bindAddress) throws InterruptedException {
        try {
            if (moFile.getInputStream() == null) {
                throw new IllegalArgumentException("could not get InputStream mock object resource; does it exist?  Resource: " + moFile);
            }
        } catch (IOException e) {
            throw new RuntimeException("Got IOException while checking for existence of mock object file: " + e, e);
        }
        
        MockSnmpAgent agent = new MockSnmpAgent(new File("/dev/null"), new File("/dev/null"), moFile, bindAddress);
        Thread thread = new Thread(agent);
        thread.start();

        try {
            while (!agent.isRunning() && thread.isAlive()) {
                Thread.sleep(10);
            } 
        } catch (InterruptedException e) {
            agent.shutDownAndWait();
            throw e;
        }

        if (!thread.isAlive()) {
            agent.m_running = false;
            agent.m_stopped = true;
            throw new IllegalStateException("agent failed to start--check logs");
        }

        return agent;
    }
    
    public static void main(String[] args) {
    	if (args.length < 2) {
    		System.err.println("Usage: MockSnmpAgent props-file listen-addr\n\nWhere props-file is relative to CLASSPATH\nand listen-addr is of the form 10.11.12.13/1161 to listen on port 1161");
    		System.exit(1);
    	}
    	ClassPathResource moFile = new ClassPathResource(args[0]);
       	String bindAddress = args[1];
    	
    	try {
    		MockSnmpAgent agt = MockSnmpAgent.createAgentAndRun(moFile, bindAddress);
    	} catch (InterruptedException e) {
    		System.exit(0);
    	}
    }    

    public void shutDownAndWait() throws InterruptedException {
        if (!isRunning()) {
            return;
{'fraction_non_alphanumeric': 0.08786017949929145, 'fraction_numerical': 0.014249724452842073, 'mean_word_length': 3.281429052915403, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 1, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5452877', 'n_tokens_mistral': 3923, 'n_tokens_neox': 3797, 'n_words': 1171}