Esempio n. 1
0
  public void testCreate() throws Exception {

    setupCollector("SNMP", false);
    setupTransactionManager();

    // Use a mock scheduler to track calls to the Collectd scheduler
    Scheduler m_scheduler = m_easyMockUtils.createMock(Scheduler.class);
    m_collectd.setScheduler(m_scheduler);

    // Expect one task to be scheduled
    m_scheduler.schedule(eq(0L), isA(ReadyRunnable.class));

    // Expect the scheduler to be started and stopped during Collectd
    // start() and stop()
    m_scheduler.start();
    m_scheduler.stop();

    m_easyMockUtils.replayAll();

    // Initialize Collectd
    m_collectd.afterPropertiesSet();

    // Start and stop collectd
    m_collectd.start();
    m_collectd.stop();

    m_easyMockUtils.verifyAll();
  }
Esempio n. 2
0
  @Override
  protected void setUp() throws Exception {

    m_backEnd = m_mock.createMock(PollerBackEnd.class);
    m_settings = m_mock.createMock(PollerSettings.class);
    m_pollService = m_mock.createMock(PollService.class);
    m_registrationListener = m_mock.createMock(PropertyChangeListener.class);
    m_polledServiceListener = m_mock.createMock(ServicePollStateChangedListener.class);
    m_configChangeListener = m_mock.createMock(ConfigurationChangedListener.class);

    setPollConfig(new DemoPollerConfiguration());
    m_oldPollerConfiguration = null;

    m_frontEnd = new DefaultPollerFrontEnd();

    m_frontEnd.setTimeAdjustment(new DefaultTimeAdjustment());

    //        ServerUnreachableAdaptor adaptor = new ServerUnreachableAdaptor();
    //        adaptor.setRemoteBackEnd(m_backEnd);
    //        m_frontEnd.setPollerBackEnd(adaptor);

    m_frontEnd.setPollerBackEnd(m_backEnd);

    m_frontEnd.setPollerSettings(m_settings);
    m_frontEnd.setPollService(m_pollService);

    m_frontEnd.addConfigurationChangedListener(m_configChangeListener);
    m_frontEnd.addPropertyChangeListener(m_registrationListener);
    m_frontEnd.addServicePollStateChangedListener(m_polledServiceListener);

    m_serviceStatus = PollStatus.available(1234.0);
  }
Esempio n. 3
0
  /** Add a dummy transaction manager that has mock calls to commit() and rollback() */
  private void setupTransactionManager() {
    PlatformTransactionManager m_transactionManager =
        m_easyMockUtils.createMock(PlatformTransactionManager.class);
    TransactionTemplate transactionTemplate = new TransactionTemplate(m_transactionManager);
    m_collectd.setTransactionTemplate(transactionTemplate);

    expect(m_transactionManager.getTransaction(isA(TransactionDefinition.class)))
        .andReturn(new SimpleTransactionStatus())
        .anyTimes();
    m_transactionManager.rollback(isA(TransactionStatus.class));
    expectLastCall().anyTimes();
    m_transactionManager.commit(isA(TransactionStatus.class));
    expectLastCall().anyTimes();
  }
Esempio n. 4
0
  private void setupCollector(String svcName, boolean successfulInit)
      throws CollectionInitializationException {
    ServiceCollector svcCollector = m_easyMockUtils.createMock(ServiceCollector.class);
    if (successfulInit) {
      svcCollector.initialize(isA(CollectionAgent.class), isAMap(String.class, Object.class));
    }
    svcCollector.initialize(Collections.<String, String>emptyMap());
    MockServiceCollector.setDelegate(svcCollector);

    // Tell the config to use the MockServiceCollector for the specified service
    Collector collector = new Collector();
    collector.setService(svcName);
    collector.setClassName(MockServiceCollector.class.getName());

    m_collectdConfigFactory = m_easyMockUtils.createMock(CollectdConfigFactory.class);
    m_collectdConfig = m_easyMockUtils.createMock(CollectdConfiguration.class);
    expect(m_collectdConfigFactory.getCollectdConfig()).andReturn(m_collectdConfig).anyTimes();
    expect(m_collectdConfig.getCollectors())
        .andReturn(Collections.singletonList(collector))
        .anyTimes();
    expect(m_collectdConfig.getThreads()).andReturn(1).anyTimes();

    m_collectd.setCollectdConfigFactory(m_collectdConfigFactory);
  }
public class GenericIndexResourceTypeTest {

  private static final String RRD_FILE_NAME = "ds.nullRrd";

  private FileAnticipator m_fileAnticipator;
  private EasyMockUtils m_mocks = new EasyMockUtils();
  private FilesystemResourceStorageDao m_resourceStorageDao;
  private StorageStrategy m_storageStrategy = m_mocks.createMock(StorageStrategy.class);
  private NodeDao m_nodeDao = m_mocks.createMock(NodeDao.class);
  private ResourceDao m_resourceDao = m_mocks.createMock(ResourceDao.class);

  @Before
  public void setUp() throws IOException {
    m_fileAnticipator = new FileAnticipator();

    m_resourceStorageDao = new FilesystemResourceStorageDao();
    m_resourceStorageDao.setRrdDirectory(m_fileAnticipator.getTempDir());
    m_resourceStorageDao.setRrdStrategy(new NullRrdStrategy());
  }

  @After
  public void tearDown() {
    if (m_fileAnticipator.isInitialized()) {
      m_fileAnticipator.deleteExpected();
    }

    m_fileAnticipator.tearDown();
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelPlain() throws IOException {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "plain", m_storageStrategy);

    touch("snmp", "1", "foo", "1", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "plain", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndex() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${index}", m_storageStrategy);

    touch("snmp", "1", "foo", "1", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "1", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelStringAttribute() throws Exception {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${stringAttribute}", m_storageStrategy);

    File rrd = touch("snmp", "1", "foo", "1", RRD_FILE_NAME);
    m_fileAnticipator.tempFile(
        rrd.getParentFile(),
        RrdResourceAttributeUtils.STRINGS_PROPERTIES_FILE_NAME,
        "stringAttribute=hello!!!!");

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "hello!!!!", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeSourceAndIndexGetLabelStringAttribute() throws IOException {
    try {
      System.setProperty("org.opennms.rrd.storeByForeignSource", "true");

      GenericIndexResourceType rt =
          new GenericIndexResourceType(
              m_resourceStorageDao, "foo", "Foo Resource", "${stringAttribute}", m_storageStrategy);

      File rrd = touch("snmp", "fs", "source1", "123", "foo", "1", RRD_FILE_NAME);
      m_fileAnticipator.tempFile(
          rrd.getParentFile(),
          RrdResourceAttributeUtils.STRINGS_PROPERTIES_FILE_NAME,
          "stringAttribute=hello!!!!");

      m_mocks.replayAll();
      OnmsResource resource = rt.getChildByName(getNodeResource("source1", "123"), "1");
      m_mocks.verifyAll();

      assertNotNull("resource", resource);
      assertEquals("resource label", "hello!!!!", resource.getLabel());
    } finally {
      System.setProperty("org.opennms.rrd.storeByForeignSource", "false");
    }
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubIndexNumber() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${subIndex(3, 1)}", m_storageStrategy);

    touch("snmp", "1", "foo", "1.2.3.4", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.2.3.4");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "4", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubIndexBogusArguments() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao,
            "foo",
            "Foo Resource",
            "${subIndex(absolutely bogus)}",
            m_storageStrategy);

    touch("snmp", "1", "foo", "1.2.3.4", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.2.3.4");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "${subIndex(absolutely bogus)}", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubIndexBogusOffset() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${subIndex(foo, 1)}", m_storageStrategy);

    touch("snmp", "1", "foo", "1.2.3.4", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.2.3.4");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "${subIndex(foo, 1)}", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubIndexBadNumber() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${subIndex(4, 1)}", m_storageStrategy);

    touch("snmp", "1", "foo", "1.2.3.4", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.2.3.4");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "${subIndex(4, 1)}", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubIndexBeginning() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${subIndex(1)}", m_storageStrategy);

    touch("snmp", "1", "foo", "1.2.3.4", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.2.3.4");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "2.3.4", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubIndexEnding() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${subIndex(0, 3)}", m_storageStrategy);

    touch("snmp", "1", "foo", "1.2.3.4", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.2.3.4");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "1.2.3", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubIndexNoArguments() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${subIndex()}", m_storageStrategy);

    touch("snmp", "1", "foo", "1.2.3.4", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.2.3.4");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "${subIndex()}", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubIndexStartOutOfBounds() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${subIndex(4)}", m_storageStrategy);

    touch("snmp", "1", "foo", "1.2.3.4", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.2.3.4");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "${subIndex(4)}", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubIndexEndOutOfBounds() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${subIndex(0, 5)}", m_storageStrategy);

    touch("snmp", "1", "foo", "1.2.3.4", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.2.3.4");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "${subIndex(0, 5)}", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithHexConversion() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${hex(index)}", m_storageStrategy);

    touch("snmp", "1", "foo", "1.2.3.4.14.15", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.2.3.4.14.15");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "01:02:03:04:0E:0F", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithHexConversionBogusInteger() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao, "foo", "Foo Resource", "${hex(index)}", m_storageStrategy);

    touch("snmp", "1", "foo", "foo", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "foo");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "${hex(index)}", resource.getLabel());
  }

  /** Test for enhancement in bug #2467. */
  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubStringAndHexConversion() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao,
            "foo",
            "Foo Resource",
            "MAC Address ${hex(subIndex(0, 6))} on interface ${subIndex(6, 1)}",
            m_storageStrategy);

    touch("snmp", "1", "foo", "0.21.109.80.9.66.4", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "0.21.109.80.9.66.4");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals(
        "resource label", "MAC Address 00:15:6D:50:09:42 on interface 4", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithSubStringOfDynamicLength() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao,
            "foo",
            "Foo Resource",
            "Easy as ${subIndex(0, n)}",
            m_storageStrategy);

    touch("snmp", "1", "foo", "5.1.2.3.4.5", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "5.1.2.3.4.5");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "Easy as 1.2.3.4.5", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithThreeSubStringsOfDynamicLength() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao,
            "foo",
            "Foo Resource",
            "Easy as ${subIndex(0, n)} and ${subIndex(n, n)} and ${subIndex(n, n)}",
            m_storageStrategy);

    touch("snmp", "1", "foo", "1.1.2.1.2.3.1.2.3", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "1.1.2.1.2.3.1.2.3");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "Easy as 1 and 1.2 and 1.2.3", resource.getLabel());
  }

  @Test
  public void
      testGetResourceByNodeAndIndexGetLabelIndexWithSubStringAndDynSubStringAndDynSubStringAndSubStringToEnd() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao,
            "foo",
            "Foo Resource",
            "Easy as ${subIndex(0, 1)} and ${subIndex(1, n)} and ${subIndex(n, n)} and ${subIndex(n)}",
            m_storageStrategy);

    touch("snmp", "1", "foo", "3.3.1.2.3.3.4.5.6.0", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "3.3.1.2.3.3.4.5.6.0");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "Easy as 3 and 1.2.3 and 4.5.6 and 0", resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithDisplaySubStringOfDynamicLength() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao,
            "foo",
            "Foo Resource",
            "Easy as ${string(subIndex(0, n))}",
            m_storageStrategy);

    touch("snmp", "1", "foo", "3.112.105.101", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "3.112.105.101");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "Easy as pie", resource.getLabel());
  }

  @Test
  public void
      testGetResourceByNodeAndIndexGetLabelIndexWithSubStringAndTwoDisplaySubStringsOfDynamicLengthAndSubStringToEnd() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao,
            "foo",
            "Foo Resource",
            "Easy as ${subIndex(0, 1)} piece of ${string(subIndex(1, n))} or just under ${string(subIndex(n, n))} pieces of ${subIndex(n)}",
            m_storageStrategy);

    touch("snmp", "1", "foo", "1.3.112.105.101.2.80.105.3.1.4.1.5.9", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource =
        rt.getChildByName(getNodeResource(1), "1.3.112.105.101.2.80.105.3.1.4.1.5.9");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals(
        "resource label",
        "Easy as 1 piece of pie or just under Pi pieces of 3.1.4.1.5.9",
        resource.getLabel());
  }

  @Test
  public void testGetResourceByNodeAndIndexGetLabelIndexWithBogusUseOfNforStartOfFirstSubIndex() {
    GenericIndexResourceType rt =
        new GenericIndexResourceType(
            m_resourceStorageDao,
            "foo",
            "Foo Resource",
            "Easy as ${subIndex(n, 3)}",
            m_storageStrategy);

    touch("snmp", "1", "foo", "3.1.2.3", RRD_FILE_NAME);

    m_mocks.replayAll();
    OnmsResource resource = rt.getChildByName(getNodeResource(1), "3.1.2.3");
    m_mocks.verifyAll();

    assertNotNull("resource", resource);
    assertEquals("resource label", "Easy as ${subIndex(n, 3)}", resource.getLabel());
  }

  private OnmsResource getNodeResource(int nodeId) {
    final NodeResourceType nodeResourceType = new NodeResourceType(m_resourceDao, m_nodeDao);
    OnmsNode node = new OnmsNode();
    node.setId(nodeId);
    node.setLabel("Node" + nodeId);
    return nodeResourceType.createResourceForNode(node);
  }

  private OnmsResource getNodeResource(String fs, String fid) {
    NodeResourceType nodeSourceResourceType = new NodeResourceType(m_resourceDao, m_nodeDao);
    OnmsNode node = new OnmsNode();
    node.setId(0);
    node.setLabel("Node");
    node.setForeignSource(fs);
    node.setForeignId(fid);
    return nodeSourceResourceType.createResourceForNode(node);
  }

  private File touch(String first, String... more) {
    Path parent = m_fileAnticipator.getTempDir().toPath();
    Path path = parent.resolve(Paths.get(first, more));
    File file = path.toFile();
    file.getParentFile().mkdirs();
    try {
      file.createNewFile();
    } catch (IOException e) {
      throw Throwables.propagate(e);
    }
    assertTrue(file.canRead());
    return file;
  }
}
Esempio n. 6
0
  @Override
  protected void setUp() throws Exception {
    EventIpcManager m_eventIpcManager;
    NodeDao m_nodeDao;

    MockLogAppender.setupLogging();

    Resource threshdResource = new ClassPathResource("/etc/thresholds.xml");
    File homeDir = threshdResource.getFile().getParentFile().getParentFile();
    System.setProperty("opennms.home", homeDir.getAbsolutePath());

    // Test setup
    m_eventIpcManager = m_easyMockUtils.createMock(EventIpcManager.class);
    EventIpcManagerFactory.setIpcManager(m_eventIpcManager);
    m_nodeDao = m_easyMockUtils.createMock(NodeDao.class);
    m_ipIfDao = m_easyMockUtils.createMock(IpInterfaceDao.class);
    m_scheduler = new MockScheduler();

    m_eventIpcManager.addEventListener(isA(EventListener.class));
    expectLastCall().anyTimes();
    m_eventIpcManager.addEventListener(isA(EventListener.class), isACollection(String.class));
    expectLastCall().anyTimes();
    m_eventIpcManager.addEventListener(isA(EventListener.class), isA(String.class));
    expectLastCall().anyTimes();
    m_eventIpcManager.removeEventListener(isA(EventListener.class));
    expectLastCall().anyTimes();

    //        MockNetwork m_network = new MockNetwork();
    //        m_network.setCriticalService("ICMP");
    //        m_network.addNode(1, "Router");
    //        m_network.addInterface("192.168.1.1");
    //        m_network.addService("ICMP");
    //        m_network.addService("SMTP");
    //        m_network.addInterface("192.168.1.2");
    //        m_network.addService("ICMP");
    //        m_network.addService("SMTP");
    //        m_network.addNode(2, "Server");
    //        m_network.addInterface("192.168.1.3");
    //        m_network.addService("ICMP");
    //        m_network.addService("HTTP");
    //        m_network.addNode(3, "Firewall");
    //        m_network.addInterface("192.168.1.4");
    //        m_network.addService("SMTP");
    //        m_network.addService("HTTP");
    //        m_network.addInterface("192.168.1.5");
    //        m_network.addService("SMTP");
    //        m_network.addService("HTTP");
    //
    //        MockDatabase m_db = new MockDatabase();
    //        m_db.populate(m_network);
    //
    //        DataSourceFactory.setInstance(m_db);

    // Mock the FilterDao without using EasyMockUtils so that it can be verified separately
    m_filterDao = EasyMock.createMock(FilterDao.class);
    List<InetAddress> allIps = new ArrayList<InetAddress>();
    allIps.add(addr("192.168.1.1"));
    allIps.add(addr("192.168.1.2"));
    allIps.add(addr("192.168.1.3"));
    allIps.add(addr("192.168.1.4"));
    allIps.add(addr("192.168.1.5"));
    expect(m_filterDao.getActiveIPAddressList("IPADDR IPLIKE *.*.*.*"))
        .andReturn(allIps)
        .anyTimes();
    expect(m_filterDao.getActiveIPAddressList("IPADDR IPLIKE 1.1.1.1"))
        .andReturn(new ArrayList<InetAddress>(0))
        .anyTimes();
    EasyMock.replay(m_filterDao);
    FilterDaoFactory.setInstance(m_filterDao);

    // This call will also ensure that the poll-outages.xml file can parse IPv4
    // and IPv6 addresses.
    Resource resource = new ClassPathResource("etc/poll-outages.xml");
    PollOutagesConfigFactory factory = new PollOutagesConfigFactory(resource);
    factory.afterPropertiesSet();
    PollOutagesConfigFactory.setInstance(factory);

    final MockTransactionTemplate transTemplate = new MockTransactionTemplate();
    transTemplate.afterPropertiesSet();

    m_collectd = new Collectd();
    m_collectd.setEventIpcManager(m_eventIpcManager);
    // m_collectd.setCollectdConfigFactory(m_collectdConfigFactory);
    m_collectd.setNodeDao(m_nodeDao);
    m_collectd.setIpInterfaceDao(m_ipIfDao);
    m_collectd.setFilterDao(m_filterDao);
    m_collectd.setScheduler(m_scheduler);
    m_collectd.setTransactionTemplate(transTemplate);
    // m_collectd.afterPropertiesSet();

    ThresholdingConfigFactory.setInstance(
        new ThresholdingConfigFactory(
            ConfigurationTestUtils.getInputStreamForConfigFile("thresholds.xml")));
  }
 @Override
 public void setUp() {
   m_mocks = new EasyMockUtils();
   m_eventProxy = m_mocks.createMock(EventProxy.class);
 }
public class OpenNMSProvisionerTest {

  private OpenNMSProvisioner m_provisioner;

  private TestCapsdConfigManager m_capsdConfig;

  private TestPollerConfigManager m_pollerConfig;

  public static final String POLLER_CONFIG =
      "\n"
          + "<poller-configuration\n"
          + "   threads=\"10\"\n"
          + "   nextOutageId=\"SELECT nextval(\'outageNxtId\')\"\n"
          + "   serviceUnresponsiveEnabled=\"false\">\n"
          + "   <node-outage status=\"on\" pollAllIfNoCriticalServiceDefined=\"true\"></node-outage>\n"
          + "   <package name=\"default\">\n"
          + "       <filter>IPADDR IPLIKE *.*.*.*</filter>\n"
          + "       <rrd step = \"300\">\n"
          + "           <rra>RRA:AVERAGE:0.5:1:2016</rra>\n"
          + "           <rra>RRA:AVERAGE:0.5:12:4464</rra>\n"
          + "           <rra>RRA:MIN:0.5:12:4464</rra>\n"
          + "           <rra>RRA:MAX:0.5:12:4464</rra>\n"
          + "       </rrd>\n"
          + "       <service name=\"ICMP\" interval=\"300000\">\n"
          + "           <parameter key=\"retry\" value=\"2\" />\n"
          + "           <parameter key=\"timeout\" value=\"3000\"/>\n"
          + "       </service>\n"
          + "       <downtime begin=\"10000\" end=\"40000\" interval=\"300000\"/>\n"
          + "       <downtime begin=\"40000\" interval=\"300000\"/>\n"
          + "   </package>\n"
          + "   <package name=\"MyTcp\">\n"
          + "       <filter>IPADDR IPLIKE *.*.*.*</filter>\n"
          + "       <rrd step = \"300\">\n"
          + "           <rra>RRA:AVERAGE:0.5:1:2016</rra>\n"
          + "           <rra>RRA:AVERAGE:0.5:12:4464</rra>\n"
          + "           <rra>RRA:MIN:0.5:12:4464</rra>\n"
          + "           <rra>RRA:MAX:0.5:12:4464</rra>\n"
          + "       </rrd>\n"
          + "       <service name=\"MyTcp\" interval=\"1234\">\n"
          + "           <parameter key=\"retry\" value=\"3\" />\n"
          + "           <parameter key=\"timeout\" value=\"314159\"/>\n"
          + "           <parameter key=\"port\" value=\"1776\"/>\n"
          + "           <parameter key=\"banner\" value=\"Right back at ya!\"/>\n"
          + "       </service>\n"
          + "       <downtime begin=\"0\" end=\"1492\" interval=\"17\"/>\n"
          + "       <downtime begin=\"1492\" interval=\"1234\"/>\n"
          + "   </package>\n"
          + "   <monitor service=\"ICMP\" class-name=\"org.opennms.netmgt.poller.monitors.LdapMonitor\"/>\n"
          + "   <monitor service=\"MyTcp\" class-name=\"org.opennms.netmgt.poller.monitors.LdapMonitor\"/>\n"
          + "</poller-configuration>\n";

  private static final String CAPSD_CONFIG =
      "\n"
          + "<capsd-configuration max-suspect-thread-pool-size=\"2\" max-rescan-thread-pool-size=\"3\"\n"
          + "   delete-propagation-enabled=\"true\">\n"
          + "   <protocol-plugin protocol=\"ICMP\" class-name=\"org.opennms.netmgt.capsd.plugins.LdapPlugin\"/>\n"
          + "   <protocol-plugin protocol=\"MyTcp\" class-name=\"org.opennms.netmgt.capsd.plugins.LdapPlugin\"/>\n"
          + "</capsd-configuration>\n";

  private EasyMockUtils m_mocks = new EasyMockUtils();
  private RrdStrategy<?, ?> m_strategy = m_mocks.createMock(RrdStrategy.class);

  private MockEventIpcManager m_eventManager;

  private JdbcCapsdDbSyncer m_syncer;

  @Before
  public void setUp() throws Exception {
    MockLogAppender.setupLogging();
    MockDatabase db = new MockDatabase();
    DataSourceFactory.setInstance(db);

    RrdUtils.setStrategy(m_strategy);

    m_provisioner = new OpenNMSProvisioner();

    m_eventManager = new MockEventIpcManager();
    m_provisioner.setEventManager(m_eventManager);

    m_capsdConfig = new TestCapsdConfigManager(CAPSD_CONFIG);
    CapsdConfigFactory.setInstance(m_capsdConfig);

    m_pollerConfig = new TestPollerConfigManager(POLLER_CONFIG, "localhost", false);
    PollerConfigFactory.setInstance(m_pollerConfig);

    m_provisioner.setCapsdConfig(m_capsdConfig);
    m_provisioner.setPollerConfig(m_pollerConfig);

    InputStream configStream =
        ConfigurationTestUtils.getInputStreamForConfigFile("opennms-server.xml");
    OpennmsServerConfigFactory onmsSvrConfig = new OpennmsServerConfigFactory(configStream);
    configStream.close();
    OpennmsServerConfigFactory.setInstance(onmsSvrConfig);

    configStream = ConfigurationTestUtils.getInputStreamForConfigFile("database-schema.xml");
    DatabaseSchemaConfigFactory.setInstance(new DatabaseSchemaConfigFactory(configStream));
    configStream.close();

    configStream =
        ConfigurationTestUtils.getInputStreamForResource(
            this, "/org/opennms/netmgt/capsd/collectd-configuration.xml");
    CollectdConfigFactory.setInstance(
        new CollectdConfigFactory(
            configStream, onmsSvrConfig.getServerName(), onmsSvrConfig.verifyServer()));
    configStream.close();

    JdbcTemplate jdbcTemplate = new JdbcTemplate(db);

    m_syncer = new JdbcCapsdDbSyncer();
    m_syncer.setJdbcTemplate(jdbcTemplate);
    m_syncer.setOpennmsServerConfig(OpennmsServerConfigFactory.getInstance());
    m_syncer.setCapsdConfig(m_capsdConfig);
    m_syncer.setPollerConfig(m_pollerConfig);
    m_syncer.setCollectdConfig(CollectdConfigFactory.getInstance());
    m_syncer.setNextSvcIdSql(db.getNextServiceIdStatement());
    m_syncer.afterPropertiesSet();

    m_syncer.syncServices();
    m_provisioner.setCapsdDbSyncer(m_syncer);
  }

  @After
  public void tearDown() throws Exception {
    MockLogAppender.assertNoWarningsOrGreater();
  }

  static class TestPollerConfigManager extends PollerConfigManager {
    String m_xml;

    public TestPollerConfigManager(String xml, String localServer, boolean verifyServer)
        throws MarshalException, ValidationException, IOException {
      super(new ByteArrayInputStream(xml.getBytes("UTF-8")), localServer, verifyServer);
      save();
    }

    @SuppressWarnings("deprecation")
    public void update() throws IOException, MarshalException, ValidationException {
      m_config = CastorUtils.unmarshal(PollerConfiguration.class, new StringReader(m_xml));
      setUpInternalData();
    }

    protected void saveXml(String xml) throws IOException {
      m_xml = xml;
    }

    public List<InetAddress> getIpList(Package pkg) {
      return new ArrayList<InetAddress>(0);
    }

    public String getXml() {
      return m_xml;
    }
  }

  @Test
  public void testGetServiceConfiguration() throws Exception {
    checkServiceConfiguration("default", "ICMP", 2, 3000, 300000, 300000, 30000);
    checkTcpConfiguration("MyTcp", "MyTcp", 3, 314159, 1234, 17, 1492, 1776, "Right back at ya!");
  }

  private Map<String, Object> checkTcpConfiguration(
      String pkgName,
      String svcName,
      int retries,
      int timeout,
      int interval,
      int downtimeInterval,
      int downtimeDuration,
      int port,
      String banner)
      throws Exception {
    Map<String, Object> configParams =
        checkServiceConfiguration(
            pkgName, svcName, retries, timeout, interval, downtimeInterval, downtimeDuration);
    assertEquals(Integer.valueOf(port), configParams.get("port"));
    assertEquals(banner, configParams.get("banner"));
    return configParams;
  }

  private Map<String, Object> checkServiceConfiguration(
      String pkgName,
      String svcName,
      int retries,
      int timeout,
      int interval,
      int downtimeInterval,
      int downtimeDuration)
      throws Exception {
    Map<String, Object> configParams = m_provisioner.getServiceConfiguration(pkgName, svcName);
    assertEquals(svcName, configParams.get("serviceid"));
    assertEquals(Integer.valueOf(interval), configParams.get("interval"));
    assertEquals(Integer.valueOf(downtimeInterval), configParams.get("downtime_interval"));
    assertEquals(Integer.valueOf(downtimeDuration), configParams.get("downtime_duration"));
    assertNull(configParams.get("downtime_interval1"));
    assertNull(configParams.get("downtime_duration1"));
    assertEquals(Integer.valueOf(retries), configParams.get("retries"));
    assertEquals(Integer.valueOf(timeout), configParams.get("timeout"));

    TestPollerConfigManager mgr =
        new TestPollerConfigManager(m_pollerConfig.getXml(), "localhost", false);

    Package pkg = mgr.getPackage(pkgName);
    assertNotNull(pkg);
    Service svc = mgr.getServiceInPackage(svcName, pkg);
    assertNotNull(svc);
    assertEquals(interval, svc.getInterval());
    assertNotNull(
        "Unables to find monitor for svc " + svcName + " in origonal config",
        m_pollerConfig.getServiceMonitor(svcName));
    assertNotNull("Unable to find monitor for svc " + svcName, mgr.getServiceMonitor(svcName));

    assertNotNull(
        "Unable to find protocol plugin in capsdConfig for svc " + svcName,
        m_capsdConfig.getProtocolPlugin(svcName));
    assertNotNull(
        "Unable to find service table entry in capsdConfig for svc " + svcName,
        m_syncer.getServiceId(svcName));

    return configParams;
  }

  @Test
  public void testGetServiceConfigNullPkgName() {
    try {
      m_provisioner.getServiceConfiguration(null, "ICMP");
      fail("Expected exception");
    } catch (NullPointerException e) {

    }
  }

  @Test
  public void testGetServiceConfigNullServiceId() {
    try {
      m_provisioner.getServiceConfiguration("default", null);
      fail("Expected exception");
    } catch (NullPointerException e) {

    }
  }

  @Test
  public void testGetServiceConfigInvalidPkg() {
    try {
      m_provisioner.getServiceConfiguration("invalid", "ICMP");
      fail("Expected exception");
    } catch (IllegalArgumentException e) {

    }
  }

  @Test
  public void testGetServiceConfigInvalidServiceId() {
    try {
      m_provisioner.getServiceConfiguration("default", "invalid");
      fail("Expected exception");
    } catch (IllegalArgumentException e) {

    }
  }

  @Test
  public void testAddServiceIcmp() throws Exception {

    m_provisioner.addServiceICMP("MyIcmp", 77, 1066, 36, 5, 1812);
    checkServiceConfiguration("MyIcmp", "MyIcmp", 77, 1066, 36, 5, 1812);

    TestPollerConfigManager mgr =
        new TestPollerConfigManager(m_pollerConfig.getXml(), "localhost", false);

    Package pkg = mgr.getPackage("MyIcmp");
    assertNotNull(pkg);
    assertNotNull(mgr.getServiceInPackage("MyIcmp", pkg));
  }

  // TODO: Add test for exception on save of XML file
  @Test
  public void testAddServiceDatabase() throws Exception {
    expectUpdateEvent();
    m_mocks.replayAll();

    m_provisioner.addServiceDatabase(
        "MyDB",
        13,
        2001,
        54321,
        71,
        23456,
        "dbuser",
        "dbPasswd",
        "org.mydb.MyDriver",
        "jdbc://mydbhost:2");
    checkDatabaseConfiguration(
        "MyDB",
        "MyDB",
        13,
        2001,
        54321,
        71,
        23456,
        "dbuser",
        "dbPasswd",
        "org.mydb.MyDriver",
        "jdbc://mydbhost:2");

    m_mocks.verifyAll();
    verifyEvents();
  }

  @Test
  public void testAddServiceDNS() throws Exception {
    expectUpdateEvent();
    m_mocks.replayAll();

    m_provisioner.addServiceDNS("MyDNS", 11, 1111, 11111, 111, 111111, 101, "www.opennms.org");
    checkDNSConfiguration("MyDNS", "MyDNS", 11, 1111, 11111, 111, 111111, 101, "www.opennms.org");

    m_mocks.verifyAll();
    verifyEvents();
  }

  @Test
  public void testAddServiceHTTP() throws Exception {
    expectUpdateEvent();
    m_mocks.replayAll();

    m_provisioner.addServiceHTTP(
        "MyHTTP",
        22,
        2222,
        22222,
        222,
        222222,
        "opennms.com",
        212,
        "200-203",
        "Home",
        "/index.html",
        "user",
        "passwd",
        null);
    checkHTTPConfiguration(
        "MyHTTP",
        "MyHTTP",
        22,
        2222,
        22222,
        222,
        222222,
        "opennms.com",
        212,
        "200-203",
        "Home",
        "/index.html",
        "user",
        "passwd",
        null);

    m_mocks.verifyAll();
    verifyEvents();
  }

  @Test
  public void testAddServiceHTTPNoResponseCode() throws Exception {
    expectUpdateEvent();
    m_mocks.replayAll();

    m_provisioner.addServiceHTTP(
        "MyHTTP",
        22,
        2222,
        22222,
        222,
        222222,
        "opennms.com",
        212,
        "",
        "Home",
        "/index.html",
        "user",
        "pw",
        "");
    checkHTTPConfiguration(
        "MyHTTP",
        "MyHTTP",
        22,
        2222,
        22222,
        222,
        222222,
        "opennms.com",
        212,
        null,
        "Home",
        "/index.html",
        "user",
        "pw",
        "");

    m_mocks.verifyAll();
    verifyEvents();
  }

  private Map<String, Object> checkHTTPConfiguration(
      String pkgName,
      String svcName,
      int retries,
      int timeout,
      int interval,
      int downtimeInterval,
      int downtimeDuration,
      String hostName,
      int port,
      String responseCode,
      String contentCheck,
      String url,
      String user,
      String passwd,
      String agent)
      throws Exception {
    Map<String, Object> configParams =
        checkServiceConfiguration(
            pkgName, svcName, retries, timeout, interval, downtimeInterval, downtimeDuration);
    assertEquals(hostName, configParams.get("hostname"));
    assertEquals(Integer.valueOf(port), configParams.get("port"));
    assertEquals(responseCode, configParams.get("response"));
    assertEquals(contentCheck, configParams.get("response_text"));
    assertEquals(user, configParams.get("user"));
    assertEquals(passwd, configParams.get("password"));
    assertEquals(agent, configParams.get("agent"));
    assertEquals(url, configParams.get("url"));
    return configParams;
  }

  @Test
  public void testAddServiceHTTPS() throws Exception {
    expectUpdateEvent();
    m_mocks.replayAll();

    m_provisioner.addServiceHTTPS(
        "MyHTTPS",
        33,
        3333,
        33333,
        333,
        333333,
        "opennms.com",
        313,
        "303",
        "Secure",
        "/secure.html",
        "user",
        "pw",
        "");
    checkHTTPSConfiguration(
        "MyHTTPS",
        "MyHTTPS",
        33,
        3333,
        33333,
        333,
        333333,
        "opennms.com",
        313,
        "303",
        "Secure",
        "/secure.html",
        "user",
        "pw",
        "");

    m_mocks.verifyAll();
    verifyEvents();
  }

  private Map<String, Object> checkHTTPSConfiguration(
      String pkgName,
      String svcName,
      int retries,
      int timeout,
      int interval,
      int downtimeInterval,
      int downtimeDuration,
      String hostName,
      int port,
      String responseCode,
      String contentCheck,
      String url,
      String user,
      String passwd,
      String agent)
      throws Exception {
    return checkHTTPConfiguration(
        pkgName,
        svcName,
        retries,
        timeout,
        interval,
        downtimeInterval,
        downtimeDuration,
        hostName,
        port,
        responseCode,
        contentCheck,
        url,
        user,
        passwd,
        agent);
  }

  @Test
  public void testAddServiceTCP() throws Exception {
    expectUpdateEvent();
    m_mocks.replayAll();

    m_provisioner.addServiceTCP("MyTCP", 4, 44, 444, 4444, 44444, 404, "HELO");
    checkTCPConfiguration("MyTCP", "MyTCP", 4, 44, 444, 4444, 44444, 404, "HELO");

    m_mocks.verifyAll();
    verifyEvents();
  }

  private void expectUpdateEvent() {
    m_eventManager
        .getEventAnticipator()
        .anticipateEvent(
            MockEventUtil.createEventBuilder("Test", EventConstants.SCHEDOUTAGES_CHANGED_EVENT_UEI)
                .getEvent());
  }

  private void verifyEvents() {
    m_eventManager.getEventAnticipator().verifyAnticipated(1000, 0, 0, 0, 0);
  }

  @Test
  public void testReaddServiceTCP() throws Exception {
    testAddServiceTCP();
    expectUpdateEvent();
    m_provisioner.addServiceTCP("MyTCP", 5, 55, 555, 5555, 55555, 505, "AHOY");
    checkTCPConfiguration("MyTCP", "MyTCP", 5, 55, 555, 5555, 55555, 505, "AHOY");
    verifyEvents();
  }

  // TODO: If a service is not in capsd it gets deleted at startup.. test that
  // adding one adds it to casd as well

  // TODO: make sure we add a monitor to pollerConfig

  // TODO: make sure we add a plugin to capsdConfig

  // TODO: Test adding as well as updating a service

  // TODO: ensure the data gets saved to the config file

  private Map<String, Object> checkTCPConfiguration(
      String pkgName,
      String svcName,
      int retries,
      int timeout,
      int interval,
      int downtimeInterval,
      int downtimeDuration,
      int port,
      String contentCheck)
      throws Exception {
    Map<String, Object> configParams =
        checkServiceConfiguration(
            pkgName, svcName, retries, timeout, interval, downtimeInterval, downtimeDuration);
    assertEquals(Integer.valueOf(port), configParams.get("port"));
    assertEquals(contentCheck, configParams.get("banner"));
    return configParams;
  }

  private Map<String, Object> checkDNSConfiguration(
      String pkgName,
      String svcName,
      int retries,
      int timeout,
      int interval,
      int downtimeInterval,
      int downtimeDuration,
      int port,
      String lookup)
      throws Exception {
    Map<String, Object> configParams =
        checkServiceConfiguration(
            pkgName, svcName, retries, timeout, interval, downtimeInterval, downtimeDuration);
    assertEquals(Integer.valueOf(port), configParams.get("port"));
    assertEquals(lookup, configParams.get("lookup"));
    return configParams;
  }

  private Map<String, Object> checkDatabaseConfiguration(
      String pkgName,
      String svcName,
      int retries,
      int timeout,
      int interval,
      int downtimeInterval,
      int downtimeDuration,
      String username,
      String password,
      String driver,
      String dbUrl)
      throws Exception {
    Map<String, Object> configParams =
        checkServiceConfiguration(
            pkgName, svcName, retries, timeout, interval, downtimeInterval, downtimeDuration);
    assertEquals(username, configParams.get("user"));
    assertEquals(password, configParams.get("password"));
    assertEquals(driver, configParams.get("driver"));
    assertEquals(dbUrl, configParams.get("url"));
    return configParams;
  }
}
 public <T> T createMock(Class<T> clazz) {
   return m_easyMock.createMock(clazz);
 }