@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");
    }
  }
 /** {@inheritDoc} */
 @Override
 public void visit(OnmsResource resource) {
   if (m_resourceAttributeValueMatch.equals(
           resource.getExternalValueAttributes().get(m_resourceAttributeKey))
       || m_resourceAttributeValueMatch.equals(
           resource.getStringPropertyAttributes().get(m_resourceAttributeKey))) {
     m_delegatedVisitor.visit(resource);
   }
 }
  private OnmsResource createResource(final OnmsIpInterface ipInterface) {
    final String intf = InetAddressUtils.str(ipInterface.getIpAddress());
    final String label = intf;
    final String resource = intf;

    final Set<OnmsAttribute> set = new LazySet<OnmsAttribute>(new AttributeLoader(intf));
    final OnmsResource r = new OnmsResource(resource, label, this, set);
    r.setEntity(ipInterface);
    return r;
  }
  /** {@inheritDoc} */
  @Override
  public List<OnmsResource> getResourcesFromGraphs(List<Graph> graphs) {
    Assert.notNull(graphs, "graph argument cannot be null");
    List<OnmsResource> resources = new LinkedList<OnmsResource>();
    HashMap<String, List<OnmsResource>> resourcesMap = new HashMap<String, List<OnmsResource>>();
    for (Graph graph : graphs) {
      String resourceId = getResourceIdForGraph(graph);

      if (resourceId != null) {
        String[] resourceParts = DefaultGraphResultsService.parseResourceId(resourceId);
        if (resourceParts == null) {
          log().warn("getResourcesFromGraphs: unparsable resourceId, skipping: " + resourceId);
          continue;
        }

        String parent = resourceParts[0];
        String childType = resourceParts[1];
        String childName = resourceParts[2];

        List<OnmsResource> resourcesForParent = resourcesMap.get(parent);
        if (resourcesForParent == null) {
          try {
            resourcesForParent = getResourceService().getResourceListById(resourceId);
            if (resourcesForParent == null) {
              log().warn("getResourcesFromGraphs: no resources found for parent " + parent);
              continue;
            } else {
              resourcesMap.put(parent, resourcesForParent);
              log().debug("getResourcesFromGraphs: add resourceList to map for " + parent);
            }
          } catch (Throwable e) {
            log()
                .warn(
                    "getResourcesFromGraphs: unexpected exception thrown while fetching resource list for \""
                        + parent
                        + "\", skipping resource",
                    e);
            continue;
          }
        }

        for (OnmsResource r : resourcesForParent) {
          if (childType.equals(r.getResourceType().getName()) && childName.equals(r.getName())) {
            resources.add(r);
            log().debug("getResourcesFromGraphs: found resource in map" + r.toString());
            break;
          }
        }
      }
    }
    return resources;
  }
  @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 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());
  }
 /** {@inheritDoc} */
 @Override
 public Report buildNodeReport(int node_id) {
   String resourceId = OnmsResource.createResourceId("node", Integer.toString(node_id));
   OnmsResource node = getResourceService().getResourceById(resourceId);
   return buildResourceReport(
       getResourceService(), node, "Node Report for Node Number " + node_id);
 }
  /** {@inheritDoc} */
  @Override
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {
    String[] requiredParameters =
        new String[] {"parentResourceId or", "parentResourceType and parentResource"};

    String endUrl = WebSecurityUtils.sanitizeString(request.getParameter("endUrl"));

    String resourceId = WebSecurityUtils.sanitizeString(request.getParameter("parentResourceId"));
    if (resourceId == null) {
      String resourceType =
          WebSecurityUtils.sanitizeString(request.getParameter("parentResourceType"));
      String resource = WebSecurityUtils.sanitizeString(request.getParameter("parentResource"));
      if (request.getParameter("parentResourceType") == null) {
        throw new MissingParameterException("parentResourceType", requiredParameters);
      }
      if (request.getParameter("parentResource") == null) {
        throw new MissingParameterException("parentResource", requiredParameters);
      }

      resourceId = OnmsResource.createResourceId(resourceType, resource);
    }

    if (endUrl == null || "".equals(endUrl)) {
      endUrl = m_defaultEndUrl;
    }

    ChooseResourceModel model = m_chooseResourceService.findChildResources(resourceId, endUrl);

    return new ModelAndView("/graph/chooseresource", "model", model);
  }
 /** {@inheritDoc} */
 @Override
 public Report buildNodeSourceReport(String nodeSource) {
   String resourceId = OnmsResource.createResourceId("nodeSource", nodeSource);
   OnmsResource res = getResourceService().getResourceById(resourceId);
   return buildResourceReport(
       getResourceService(), res, "Node Report for Foreign Source:Id " + nodeSource);
 }
  /** {@inheritDoc} */
  @Override
  public List<OnmsResource> getResourcesForDomain(String domain) {
    ArrayList<OnmsResource> resources = new ArrayList<OnmsResource>();

    List<String> ifaces = getQueryableInterfacesForDomain(domain);
    for (String iface : ifaces) {
      OnmsResource resource = getResourceByDomainAndInterface(domain, iface);
      try {
        resource.setLink(
            "element/nodeList.htm?listInterfaces=true&snmpParm=ifAlias&snmpParmMatchType=contains&snmpParmValue="
                + URLEncoder.encode(iface, "UTF-8"));
      } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("URLEncoder.encode complained about UTF-8. " + e, e);
      }
      resources.add(resource);
    }

    return OnmsResource.sortIntoResourceList(resources);
  }
  @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 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());
  }
  /** {@inheritDoc} */
  @Override
  public List<OnmsResource> getResourcesForNode(int nodeId) {
    ArrayList<OnmsResource> resources = new ArrayList<OnmsResource>();

    List<String> indexes = getQueryableIndexesForNode(nodeId);
    for (String index : indexes) {
      resources.add(getResourceByNodeAndIndex(nodeId, index));
    }
    return OnmsResource.sortIntoResourceList(resources);
  }
  /** 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
      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());
  }
 /** {@inheritDoc} */
 @Override
 public List<OnmsResource> getResourcesForNodeSource(String nodeSource, int nodeId) {
   String[] ident = nodeSource.split(":");
   OnmsNode node = m_nodeDao.findByForeignId(ident[0], ident[1]);
   if (node == null) {
     throw new ObjectRetrievalFailureException(
         OnmsNode.class, nodeSource, "Could not find node with nodeSource " + nodeSource, null);
   }
   File relPath =
       new File(ResourceTypeUtils.FOREIGN_SOURCE_DIRECTORY, ident[0] + File.separator + ident[1]);
   File parent = getParentResourceDirectory(relPath.toString(), true);
   return OnmsResource.sortIntoResourceList(populateResourceList(parent, relPath, node, true));
 }
  /** {@inheritDoc} */
  @Override
  public List<OnmsResource> getResourcesForNode(int nodeId) {
    OnmsNode node = m_nodeDao.get(nodeId);
    if (node == null) {
      throw new ObjectRetrievalFailureException(
          OnmsNode.class,
          Integer.toString(nodeId),
          "Could not find node with node ID " + nodeId,
          null);
    }

    File parent = getParentResourceDirectory(Integer.toString(nodeId), true);
    return OnmsResource.sortIntoResourceList(populateResourceList(parent, null, node, false));
  }
  @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());
  }
  private static Report buildResourceReport(
      ResourceService service, OnmsResource parentResource, String title) {
    Report report = new Report();
    report.setTitle(title);
    report.setShow_timespan_button(true);
    report.setShow_graphtype_button(true);

    List<OnmsResource> resources = service.findChildResources(parentResource, "interfaceSnmp");
    for (OnmsResource resource : resources) {
      PrefabGraph[] graphs = service.findPrefabGraphsForResource(resource);
      if (graphs.length == 0) {
        continue;
      }

      Graph graph = new Graph();
      graph.setTitle("");
      graph.setResourceId(resource.getId());
      graph.setTimespan("7_day");
      graph.setGraphtype(graphs[0].getName());

      report.addGraph(graph);
    }
    return report;
  }
  private static String getResourceIdForGraph(Graph graph) {
    Assert.notNull(graph, "graph argument cannot be null");

    String resourceId;
    if (graph.getResourceId() != null) {
      resourceId = graph.getResourceId();
    } else {
      String parentResourceTypeName;
      String parentResourceName;
      String resourceTypeName;
      String resourceName;

      if (graph.getNodeId() != null && !graph.getNodeId().equals("null")) {
        parentResourceTypeName = "node";
        parentResourceName = graph.getNodeId();
      } else if (graph.getNodeSource() != null && !graph.getNodeSource().equals("null")) {
        parentResourceTypeName = "nodeSource";
        parentResourceName = graph.getNodeSource();
      } else if (graph.getDomain() != null && !graph.getDomain().equals("null")) {
        parentResourceTypeName = "domain";
        parentResourceName = graph.getDomain();
      } else {
        throw new IllegalArgumentException("Graph does not have a resourceId, nodeId, or domain.");
      }

      String intf = graph.getInterfaceId();
      if (intf == null || "".equals(intf)) {
        resourceTypeName = "nodeSnmp";
        resourceName = "";
      } else {
        resourceTypeName = "interfaceSnmp";
        resourceName = intf;
      }

      resourceId =
          OnmsResource.createResourceId(
              parentResourceTypeName, parentResourceName, resourceTypeName, resourceName);
    }

    return resourceId;
  }
  /** {@inheritDoc} */
  @Override
  public List<OnmsResource> getResourcesForNode(int nodeId) {
    LinkedList<OnmsResource> resources = new LinkedList<OnmsResource>();

    Collection<LocationMonitorIpInterface> statuses =
        m_locationMonitorDao.findStatusChangesForNodeForUniqueMonitorAndInterface(nodeId);

    for (LocationMonitorIpInterface status : statuses) {
      String definitionName = status.getLocationMonitor().getDefinitionName();
      int id = status.getLocationMonitor().getId();
      final OnmsIpInterface ipInterface = status.getIpInterface();
      String ipAddr = InetAddressUtils.str(ipInterface.getIpAddress());

      File iface = getInterfaceDirectory(id, ipAddr);

      if (iface.isDirectory()) {
        resources.add(createResource(definitionName, id, ipAddr));
      }
    }

    return OnmsResource.sortIntoResourceList(resources);
  }
  private ArrayList<OnmsResource> populateResourceList(
      File parent, File relPath, OnmsNode node, Boolean isForeign) {

    ArrayList<OnmsResource> resources = new ArrayList<OnmsResource>();

    File[] intfDirs = parent.listFiles(RrdFileConstants.INTERFACE_DIRECTORY_FILTER);

    Set<OnmsSnmpInterface> snmpInterfaces = node.getSnmpInterfaces();
    Map<String, OnmsSnmpInterface> intfMap = new HashMap<String, OnmsSnmpInterface>();

    for (OnmsSnmpInterface snmpInterface : snmpInterfaces) {
      /*
       * When Cisco Express Forwarding (CEF) or some ATM encapsulations
       * (AAL5) are used on Cisco routers, an additional entry might be
       * in the ifTable for these sub-interfaces, but there is no
       * performance data available for collection.  This check excludes
       * ifTable entries where ifDescr contains "-cef".  See bug #803.
       */
      if (snmpInterface.getIfDescr() != null) {
        if (Pattern.matches(".*-cef.*", snmpInterface.getIfDescr())) {
          continue;
        }
      }

      String replacedIfName = AlphaNumeric.parseAndReplace(snmpInterface.getIfName(), '_');
      String replacedIfDescr = AlphaNumeric.parseAndReplace(snmpInterface.getIfDescr(), '_');

      String[] keys =
          new String[] {
            replacedIfName + "-",
            replacedIfDescr + "-",
            replacedIfName + "-" + snmpInterface.getPhysAddr(),
            replacedIfDescr + "-" + snmpInterface.getPhysAddr()
          };

      for (String key : keys) {
        if (!intfMap.containsKey(key)) {
          intfMap.put(key, snmpInterface);
        }
      }
    }

    for (File intfDir : intfDirs) {
      String name = intfDir.getName();

      String desc = name;
      String mac = "";

      // Strip off the MAC address from the end, if there is one
      int dashIndex = name.lastIndexOf('-');

      if (dashIndex >= 0) {
        desc = name.substring(0, dashIndex);
        mac = name.substring(dashIndex + 1, name.length());
      }

      String key = desc + "-" + mac;
      OnmsSnmpInterface snmpInterface = intfMap.get(key);

      String label;
      Long ifSpeed = null;
      String ifSpeedFriendly = null;
      if (snmpInterface == null) {
        label = name + " (*)";
      } else {
        StringBuffer descr = new StringBuffer();
        StringBuffer parenString = new StringBuffer();

        if (snmpInterface.getIfAlias() != null) {
          parenString.append(snmpInterface.getIfAlias());
        }
        // Append all of the IP addresses on this ifindex
        for (OnmsIpInterface ipif : snmpInterface.getIpInterfaces()) {
          String ipaddr = InetAddressUtils.str(ipif.getIpAddress());
          if (!"0.0.0.0".equals(ipaddr)) {
            if (parenString.length() > 0) {
              parenString.append(", ");
            }
            parenString.append(ipaddr);
          }
        }
        if ((snmpInterface.getIfSpeed() != null) && (snmpInterface.getIfSpeed() != 0)) {
          ifSpeed = snmpInterface.getIfSpeed();
          ifSpeedFriendly = SIUtils.getHumanReadableIfSpeed(ifSpeed);
          if (parenString.length() > 0) {
            parenString.append(", ");
          }
          parenString.append(ifSpeedFriendly);
        }

        if (snmpInterface.getIfName() != null) {
          descr.append(snmpInterface.getIfName());
        } else if (snmpInterface.getIfDescr() != null) {
          descr.append(snmpInterface.getIfDescr());
        } else {
          /*
           * Should never reach this point, since ifLabel is based on
           * the values of ifName and ifDescr but better safe than sorry.
           */
          descr.append(name);
        }

        /* Add the extended information in parenthesis after the ifLabel,
         * if such information was found.
         */
        if (parenString.length() > 0) {
          descr.append(" (");
          descr.append(parenString);
          descr.append(")");
        }

        label = descr.toString();
      }

      OnmsResource resource = null;
      if (isForeign) {
        resource =
            getResourceByNodeSourceAndInterface(
                relPath.toString(), intfDir.getName(), label, ifSpeed, ifSpeedFriendly);
      } else {
        resource =
            getResourceByNodeAndInterface(
                node.getId(), intfDir.getName(), label, ifSpeed, ifSpeedFriendly);
      }
      if (snmpInterface != null) {
        Set<OnmsIpInterface> ipInterfaces = snmpInterface.getIpInterfaces();
        if (ipInterfaces.size() > 0) {
          int id = ipInterfaces.iterator().next().getId();
          resource.setLink("element/interface.jsp?ipinterfaceid=" + id);
        } else {
          int ifIndex = snmpInterface.getIfIndex();
          if (ifIndex > -1) {
            resource.setLink(
                "element/snmpinterface.jsp?node=" + node.getNodeId() + "&ifindex=" + ifIndex);
          }
        }

        resource.setEntity(snmpInterface);
      } else {
        LOG.debug("populateResourceList: snmpInterface is null");
      }
      LOG.debug("populateResourceList: adding resource toString {}", resource.toString());
      resources.add(resource);
    }

    return resources;
  }
 /** {@inheritDoc} */
 @Override
 public Report buildDomainReport(String domain) {
   String resourceId = OnmsResource.createResourceId("domain", domain);
   OnmsResource res = getResourceService().getResourceById(resourceId);
   return buildResourceReport(getResourceService(), res, "Domain Report for Domain " + domain);
 }
  @Override
  public GraphResults findResults(
      String[] resourceIds, String[] reports, long start, long end, String relativeTime) {
    if (resourceIds == null) {
      throw new IllegalArgumentException("resourceIds argument cannot be null");
    }
    if (reports == null) {
      throw new IllegalArgumentException("reports argument cannot be null");
    }
    if (end < start) {
      throw new IllegalArgumentException("end time cannot be before start time");
    }

    GraphResults graphResults = new GraphResults();
    graphResults.setStart(new Date(start));
    graphResults.setEnd(new Date(end));
    graphResults.setRelativeTime(relativeTime);
    graphResults.setRelativeTimePeriods(m_periods);
    graphResults.setReports(reports);

    HashMap<String, List<OnmsResource>> resourcesMap = new HashMap<String, List<OnmsResource>>();

    for (String resourceId : resourceIds) {
      String[] values = parseResourceId(resourceId);
      if (values == null) {
        continue;
      }
      String parent = values[0];
      String childType = values[1];
      String childName = values[2];
      LOG.debug(
          "findResults: parent, childType, childName = {}, {}, {}",
          values[0],
          values[1],
          values[2]);
      OnmsResource resource = null;
      if (!resourcesMap.containsKey(parent)) {
        List<OnmsResource> resourceList =
            m_resourceDao.getResourceById(resourceId).getChildResources();
        if (resourceList == null) {
          LOG.warn("findResults: zero child resources found for {}", parent);
        } else {
          resourcesMap.put(parent, resourceList);
          LOG.debug("findResults: add resourceList to map for {}", parent);
        }
      }
      for (OnmsResource r : resourcesMap.get(parent)) {
        if (childType.equals(r.getResourceType().getName()) && childName.equals(r.getName())) {
          resource = r;
          LOG.debug("findResults: found resource in map{}", r.toString());
          break;
        }
      }
      try {
        graphResults.addGraphResultSet(
            createGraphResultSet(resourceId, resource, reports, graphResults));
      } catch (IllegalArgumentException e) {
        LOG.warn(e.getMessage(), e);
        continue;
      }
    }

    graphResults.setGraphTopOffsetWithText(m_rrdDao.getGraphTopOffsetWithText());
    graphResults.setGraphLeftOffset(m_rrdDao.getGraphLeftOffset());
    graphResults.setGraphRightOffset(m_rrdDao.getGraphRightOffset());

    return graphResults;
  }
 /** {@inheritDoc} */
 public String getLinkForResource(final OnmsResource resource) {
   return "element/interface.jsp?node="
       + resource.getParent().getName()
       + "&intf="
       + resource.getName();
 }