private void setTitle(HttpServletRequest request, Portal portal, String titleName)
      throws Exception {
    Resource resource = RequestUtils.getResource(request);
    ResourceGroup group = RequestUtils.getResourceGroupIfExists(request);
    ResourceType type;
    if (resource != null) {
      // resource alert definition
      type = resource.getResourceType();
    } else if (group != null) {
      // group alert definition
      type = group.getResourceType();
    } else {
      // template alert definition
      type = RequestUtils.getResourceType(request);
    }

    ResourceCategory category = type.getCategory();

    titleName = StringUtil.replace(titleName, "platform", category.toString().toLowerCase());

    portal.setName(titleName);

    // if there's an alert definition available, set our second
    // title parameter to its name
    try {
      AlertDefinition alertDef = AlertDefUtil.getAlertDefinition(request);
      request.setAttribute(Constants.TITLE_PARAM2_ATTR, alertDef.getName());
    } catch (ParameterNotFoundException e) {
      // it's okay
      log.trace("couldn't find alert definition: " + e.getMessage());
    }
  }
  private List<AutoGroupComposite> getResourceChildren(Resource resource, Subject subject) {
    ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();
    List<AutoGroupComposite> children =
        resourceManager.findChildrenAutoGroups(subject, resource.getId());

    AutoGroupComposite resourceGroupComposite =
        resourceManager.getResourceAutoGroup(subject, resource.getId());
    if (resourceGroupComposite != null) resourceGroupComposite.setMainResource(true);
    else return new ArrayList<AutoGroupComposite>();

    // now increase everyone's depth by one to account for the resource
    for (AutoGroupComposite child : children) {
      child.setDepth(child.getDepth() + 1);
    }

    children.add(0, resourceGroupComposite);

    Resource parentResource = resourceManager.getParentResource(resource.getId());
    AutoGroupComposite parentGroupComposite = null;
    if (parentResource != null) {
      parentGroupComposite = resourceManager.getResourceAutoGroup(subject, parentResource.getId());
    }

    if (parentGroupComposite != null) {
      // now increase everyone's depth by one to account for the parent
      for (AutoGroupComposite child : children) {
        child.increaseDepth(1);
      }

      children.add(0, parentGroupComposite);
    }

    return children;
  }
  @Override
  protected void onInit() {

    // To properly filter Create Child and Import menus we need existing singleton child resources.
    // If the
    // user has create permission and the parent type has singleton child types and creatable or
    // importable child
    // types, perform an async call to fetch the singleton children. If we make the async call don't
    // declare this
    // instance initialized until after it completes as we must have the children before the menu
    // buttons can be drawn.

    final Resource parentResource = parentResourceComposite.getResource();
    ResourceType parentType = parentResource.getResourceType();
    creatableChildTypes = getCreatableChildTypes(parentType);
    importableChildTypes = getImportableChildTypes(parentType);
    hasCreatableTypes = !creatableChildTypes.isEmpty();
    hasImportableTypes = !importableChildTypes.isEmpty();
    refreshSingletons(
        parentResource,
        new AsyncCallback<PageList<Resource>>() {

          public void onFailure(Throwable caught) {
            ResourceCompositeSearchView.super.onInit();
            initialized = true;
          }

          public void onSuccess(PageList<Resource> result) {
            ResourceCompositeSearchView.super.onInit();
            initialized = true;
          }
        });
  }
  /**
   * Encode the beginning of the given {@link ResourceLineageComponent}.
   *
   * @param facesContext the JSF context for the current request
   * @param component the {@link ResourceLineageComponent} to be encoded
   */
  @Override
  public void encodeBegin(FacesContext facesContext, UIComponent component) throws IOException {
    ResourceLineageComponent resourceLineage = (ResourceLineageComponent) component;
    ResponseWriter writer = facesContext.getResponseWriter();
    long monitorId = HibernatePerformanceMonitor.get().start();
    ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();
    List<Resource> ancestorResources =
        resourceManager.getResourceLineage(resourceLineage.getResourceId());
    HibernatePerformanceMonitor.get().stop(monitorId, "ResourceLineage renderer");
    if (ancestorResources.isEmpty()) {
      throw new IllegalStateException(
          "The list of ancestor resources should always contain at least one resource - the resource whose lineage was requested.");
    }

    Resource parentResource = ancestorResources.get(ancestorResources.size() - 1);
    for (Resource ancestorResource : ancestorResources) {
      writer.startElement("a", resourceLineage);
      writer.writeAttribute("href", buildURL(ancestorResource), null);
      writer.writeText(ancestorResource.getName(), null);
      writer.endElement("a");
      if (ancestorResource.getId()
          != parentResource.getId()) // separator after every item except the last one
      {
        writer.writeText(SEPARATOR, null);
      }
    }
  }
  protected void setResource(HttpServletRequest request, boolean config) throws Exception {
    try {
      Subject subject = WebUtility.getSubject(request);
      Integer resourceTypeId =
          WebUtility.getOptionalIntRequestParameter(
              request, ParamConstants.RESOURCE_TYPE_ID_PARAM, -1);
      int groupId = WebUtility.getOptionalIntRequestParameter(request, AttrConstants.GROUP_ID, -1);
      int parent = WebUtility.getOptionalIntRequestParameter(request, "parent", -1);
      String[] r = request.getParameterValues("r");
      String[] resourceIds = request.getParameterValues("resourceIds");

      // TODO rewrite the selection using WebUtility.getMetricsDisplayMode()
      if ((resourceTypeId > 0) && (parent > 0)) // autogroup
      {
        ResourceTypeManagerLocal resourceTypeManager = LookupUtil.getResourceTypeManager();
        ResourceType resourceType =
            resourceTypeManager.getResourceTypeById(subject, resourceTypeId);
        request.setAttribute(AttrConstants.RESOURCE_TYPE_ATTR, resourceType);
        request.setAttribute(AttrConstants.TITLE_PARAM_ATTR, resourceType.getName());
        request.setAttribute("parent", parent);
        request.setAttribute(ParamConstants.RESOURCE_TYPE_ID_PARAM, resourceTypeId);
        if (log.isDebugEnabled()) {
          log.debug("Autogroup p=" + parent + ", ct=" + resourceTypeId);
        }
      } else if (groupId > 0) // compat (or mixed) group
      {
        ResourceGroupManagerLocal resourceGroupManager = LookupUtil.getResourceGroupManager();
        ResourceGroup group = resourceGroupManager.getResourceGroupById(subject, groupId, null);
        request.setAttribute(AttrConstants.GROUP_ID, groupId);
        request.setAttribute(AttrConstants.TITLE_PARAM_ATTR, group.getName());
        // TODO more ?
      } else if ((resourceTypeId > 0) && (parent == -1)) // MeasurementDefinition
      {
        ResourceTypeManagerLocal resourceTypeManager = LookupUtil.getResourceTypeManager();
        ResourceType resourceType =
            resourceTypeManager.getResourceTypeById(subject, resourceTypeId);
        request.setAttribute(AttrConstants.RESOURCE_TYPE_ATTR, resourceType);
        request.setAttribute(ParamConstants.RESOURCE_TYPE_ID_PARAM, resourceTypeId);
      } else if ((r != null) && (r.length > 0)) // multiple scathered resources
      {
        log.trace("Multiple resources not handled yet"); // TODO what do we do here?
      } else if ((resourceIds != null) && (resourceIds.length > 0)) {
        log.trace("Multiple resources not yet handled"); // TODO what to we do here?
      } else // single resource
      {
        Integer resourceId =
            WebUtility.getRequiredIntRequestParameter(request, ParamConstants.RESOURCE_ID_PARAM);
        ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();
        Resource resource = resourceManager.getResourceById(subject, resourceId);
        ResourceUIBean resourceUIBean = new ResourceUIBean(resource, subject);
        request.setAttribute(AttrConstants.RESOURCE_ATTR, resource);
        request.setAttribute(AttrConstants.RESOURCE_ID_ATTR, resourceId);
        request.setAttribute(AttrConstants.TITLE_PARAM_ATTR, resource.getName());
        request.setAttribute(
            AttrConstants.PERFORMANCE_SUPPORTED_ATTR, resourceUIBean.getFacets().isCallTime());
      }
    } catch (ResourceNotFoundException e) {
      RequestUtils.setError(request, MessageConstants.ERR_RESOURCE_NOT_FOUND);
    }
  }
Exemple #6
0
 public Resource getResource(int resourceId) {
   for (Resource resource : resources) {
     if (resourceId == resource.getId()) {
       return resource;
     }
   }
   return null;
 }
  private Resource findServer(String name, Resource platform) {
    Set<Resource> servers = platform.getChildResources();

    for (Resource s : servers) {
      if (name.equals(s.getName())) {
        return s;
      }
    }

    return null;
  }
  private Set<Resource> getDiscoveredServers() {
    Set<Resource> found = new HashSet<Resource>();
    Resource platform = PluginContainer.getInstance().getInventoryManager().getPlatform();
    for (Resource resource : platform.getChildResources()) {
      if (resource.getResourceType().getName().equals("Postgres Server")) {
        found.add(resource);
      }
    }

    return found;
  }
Exemple #9
0
 public String toString() {
   return "["
       + resourceId
       + "] "
       + resource.getName()
       + " ("
       + resource.getResourceType().getName()
       + "::"
       + resource.getResourceType().getPlugin()
       + ")";
 }
  private Resource createResource(ResourceType resourceType, String host) throws Exception {
    Resource resource =
        new Resource(
            TEST_PREFIX + "CassandraDaemon", TEST_PREFIX + "CassandraDaemon", resourceType);
    resource.setUuid(UUID.randomUUID().toString());
    resource.getPluginConfiguration().setSimpleValue("host", host);
    getEntityManager().persist(resource);
    getEntityManager().flush();

    return resource;
  }
Exemple #11
0
  private void initChildren() {
    ResourceCriteria criteria = new ResourceCriteria();
    criteria.addFilterParentResourceId(resourceId);
    PageList<Resource> childResources =
        remoteClient
            .getResourceManager()
            .findResourcesByCriteria(remoteClient.getSubject(), criteria);

    for (Resource child : childResources) {
      this.children.add(proxyFactory.getResource(child.getId()));
    }
  }
Exemple #12
0
 private void initConfigDefs() {
   this.resourceConfigurationDefinition =
       remoteClient
           .getConfigurationManager()
           .getResourceConfigurationDefinitionWithTemplatesForResourceType(
               remoteClient.getSubject(), resource.getResourceType().getId());
   this.pluginConfigurationDefinition =
       remoteClient
           .getConfigurationManager()
           .getPluginConfigurationDefinitionForResourceType(
               remoteClient.getSubject(), resource.getResourceType().getId());
 }
  @Test(dependsOnMethods = "testPluginLoad")
  public void testServerDiscovery() throws Exception {
    InventoryReport report =
        PluginContainer.getInstance().getInventoryManager().executeServerScanImmediately();
    assert report != null;
    System.out.println("Discovery took: " + (report.getEndTime() - report.getStartTime()) + "ms");

    Resource platform = PluginContainer.getInstance().getInventoryManager().getPlatform();
    Set<Resource> servers = platform.getChildResources();

    // assert servers.size() != 0; Don't require a running app server for testing at this point
    System.out.println("Found " + servers.size() + " servers");
  }
  private List<Resource> findResources(
      Resource parent, String typeName, List<Resource> foundResources) {
    if (parent.getResourceType().getName().equals(typeName)) {
      foundResources.add(parent);
    }

    for (Resource resource : parent.getChildResources()) {
      for (Resource child : resource.getChildResources()) {
        findResources(child, typeName, foundResources);
      }
    }

    return foundResources;
  }
Exemple #15
0
  private void buildFavoriteResourcesMenu(
      Favorites favorites,
      Menu menu,
      Set<Integer> resourceIds,
      AncestryUtil.MapWrapper typesWrapper) {

    if (resourceIds.isEmpty()) {
      menu.setItems();
      return;
    }

    List<MenuItem> items = new ArrayList<MenuItem>(resourceIds.size());

    for (final Integer resourceId : resourceIds) {
      Resource resource = favorites.getResource(resourceId);
      if (null == resource) {
        // if the resource is gone just skip it
        continue;
      }

      MenuItem item = new MenuItem(resource.getName());
      item.setIcon(ImageManager.getResourceIcon(resource));

      // build a subMenu to display a disambiguated resource
      item.setAttribute(AncestryUtil.RESOURCE_ID, resourceId);
      item.setAttribute(AncestryUtil.RESOURCE_NAME, resource.getName());
      item.setAttribute(AncestryUtil.RESOURCE_ANCESTRY, resource.getAncestry());
      item.setAttribute(AncestryUtil.RESOURCE_TYPE_ID, resource.getResourceType().getId());
      item.setAttribute(AncestryUtil.RESOURCE_ANCESTRY_TYPES, typesWrapper);
      Menu ancestryMenu = new Menu();
      MenuItem ancestryItem = new MenuItem(AncestryUtil.getAncestryHoverHTML(item, -1));
      ancestryItem.setEnabled(false);
      ancestryMenu.setItems(ancestryItem);
      ancestryMenu.setSubmenuDirection("left");
      ancestryMenu.setAutoWidth();
      item.setSubmenu(ancestryMenu);

      item.addClickHandler(
          new com.smartgwt.client.widgets.menu.events.ClickHandler() {
            public void onClick(MenuItemClickEvent event) {
              CoreGUI.goToView(LinkManager.getResourceLink(resourceId));
            }
          });

      items.add(item);
    }

    menu.setCanSelectParentItems(Boolean.TRUE);
    menu.setItems(items.toArray(new MenuItem[items.size()]));
  }
  private Resource createNewResource() throws Exception {
    getTransactionManager().begin();
    Resource resource;

    try {
      try {
        ResourceType resourceType =
            new ResourceType(
                "plat" + System.currentTimeMillis(), "test", ResourceCategory.PLATFORM, null);
        DriftDefinitionTemplate template = new DriftDefinitionTemplate();
        template.setName("test-template");
        DriftDefinition templateDef = new DriftDefinition(new Configuration());
        templateDef.setName("test-template-def");
        template.setTemplateDefinition(templateDef);
        template.setUserDefined(true);
        resourceType.addDriftDefinitionTemplate(template);
        em.persist(resourceType);

        Agent agent = new Agent("testagent", "testaddress", 1, "", "testtoken");
        em.persist(agent);
        em.flush();

        DriftDefinition test1Def = new DriftDefinition(new Configuration());
        test1Def.setName("test-1");

        DriftDefinition test2Def = new DriftDefinition(new Configuration());
        test2Def.setName("test-2");

        resource = new Resource("reskey" + System.currentTimeMillis(), "resname", resourceType);
        resource.setUuid("" + new Random().nextInt());
        resource.setAgent(agent);
        resource.setInventoryStatus(InventoryStatus.COMMITTED);
        resource.addDriftDefinition(test1Def);
        resource.addDriftDefinition(test2Def);
        em.persist(resource);

      } catch (Exception e) {
        System.out.println("CANNOT PREPARE TEST: " + e);
        getTransactionManager().rollback();
        throw e;
      }

      em.flush();
      getTransactionManager().commit();
    } finally {
    }

    return resource;
  }
  @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
  public MeasurementBaseline calculateAutoBaselineInNewTransaction(
      Subject subject, Integer measurementScheduleId, long startDate, long endDate, boolean save)
      throws BaselineCreationException, MeasurementNotFoundException {

    MeasurementBaseline baseline;
    MeasurementSchedule sched =
        entityManager.find(MeasurementSchedule.class, measurementScheduleId);

    if (sched != null) {
      Resource resource = sched.getResource();

      // only check permissions if the user is attempting to save a new baseline
      if (save
          && !authorizationManager.hasResourcePermission(
              subject, Permission.MANAGE_MEASUREMENTS, resource.getId())) {
        log.error(
            "Cannot calculate baseline - permission denied. "
                + "resource="
                + resource
                + "; user="******"; perm="
                + Permission.MANAGE_MEASUREMENTS);
        throw new PermissionException(
            "Cannot calculate baseline - you do not have permission on this resource");
      }
    } else {
      throw new MeasurementNotFoundException(
          "Scheduled measurement [" + measurementScheduleId + "] not found");
    }

    try {
      baseline = calculateBaseline(sched, true, startDate, endDate, save);
      if (save) {
        // We have changed the baseline information for the schedule, so remove the now outdated OOB
        // info.
        oobManager.removeOOBsForSchedule(subject, sched);
      }
    } catch (DataNotAvailableException e) {
      throw new BaselineCreationException(
          "Error fetching data for baseline calculation for measurementSchedule[id="
              + measurementScheduleId
              + "]");
    }

    return baseline;
  }
  private String buildURL(Resource resource) {
    String url = FunctionTagLibrary.getDefaultResourceTabURL() + "?id=" + resource.getId();

    // Session-encode the URL in case the client doesn't have cookies enabled.
    url = FacesContext.getCurrentInstance().getExternalContext().encodeResourceURL(url);
    return url;
  }
Exemple #19
0
  public void init() {

    this.resource =
        remoteClient.getResourceManager().getResource(remoteClient.getSubject(), resourceId);

    // Lazy init children, not here
    initMeasurements();
    initOperations();
    initConfigDefs();
    initContent();

    List<PackageType> packageTypes = new ArrayList<PackageType>();
    for (ContentType ct : contentTypes.values()) {
      packageTypes.add(ct.getPackageType());
    }

    fingerprint =
        new ResourceTypeFingerprint(
            resource.getResourceType(),
            measurementDefinitions,
            operationDefinitions,
            packageTypes,
            pluginConfigurationDefinition,
            resourceConfigurationDefinition);
  }
    /**
     * Additional processing to support a cross-resource view)
     *
     * @param result
     * @param response
     * @param request
     */
    protected void dataRetrieved(
        final PageList<AlertDefinition> result,
        final DSResponse response,
        final DSRequest request) {
      HashSet<Integer> typesSet = new HashSet<Integer>();
      HashSet<String> ancestries = new HashSet<String>();
      for (AlertDefinition alertDefinition : result) {
        Resource resource = alertDefinition.getResource();
        if (null != resource) {
          typesSet.add(resource.getResourceType().getId());
          ancestries.add(resource.getAncestry());
        }
      }

      // In addition to the types of the result resources, get the types of their ancestry
      typesSet.addAll(AncestryUtil.getAncestryTypeIds(ancestries));

      ResourceTypeRepository typeRepo = ResourceTypeRepository.Cache.getInstance();
      typeRepo.getResourceTypes(
          typesSet.toArray(new Integer[typesSet.size()]),
          new TypesLoadedCallback() {

            public void onTypesLoaded(Map<Integer, ResourceType> types) {
              // Smartgwt has issues storing a Map as a ListGridRecord attribute. Wrap it in a pojo.
              AncestryUtil.MapWrapper typesWrapper = new AncestryUtil.MapWrapper(types);

              Record[] records = buildRecords(result);
              for (Record record : records) {
                // To avoid a lot of unnecessary String construction, be lazy about building
                // ancestry hover text.
                // Store the types map off the records so we can build a detailed hover string as
                // needed.
                record.setAttribute(AncestryUtil.RESOURCE_ANCESTRY_TYPES, typesWrapper);

                // Build the decoded ancestry Strings now for display
                record.setAttribute(
                    AncestryUtil.RESOURCE_ANCESTRY_VALUE, AncestryUtil.getAncestryValue(record));
              }
              response.setData(records);
              response.setTotalRows(
                  result
                      .getTotalSize()); // for paging to work we have to specify size of full result
              // set
              processResponse(request.getRequestId(), response);
            }
          });
    }
  private Resource findService(String serviceName, String serverName, Resource platform) {
    Resource server = findServer(serverName, platform);

    if (server == null) {
      return null;
    }

    Set<Resource> services = server.getChildResources();

    for (Resource s : services) {
      if (serviceName.equals(s.getName())) {
        return s;
      }
    }

    return null;
  }
Exemple #22
0
  private void deleteNewResource(Resource resource) throws Exception {
    if (null != resource) {
      EntityManager em = null;

      try {
        ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();

        // invoke bulk delete on the resource to remove any dependencies not defined in the
        // hibernate entity model
        // perform in-band and out-of-band work in quick succession
        List<Integer> deletedIds = resourceManager.uninventoryResource(overlord, resource.getId());
        for (Integer deletedResourceId : deletedIds) {
          resourceManager.uninventoryResourceAsyncWork(overlord, deletedResourceId);
        }

        // now dispose of other hibernate entities
        getTransactionManager().begin();
        em = getEntityManager();

        ResourceType type = em.find(ResourceType.class, resource.getResourceType().getId());
        Agent agent = em.find(Agent.class, resource.getAgent().getId());
        if (null != agent) {
          em.remove(agent);
        }
        if (null != type) {
          em.remove(type);
        }

        getTransactionManager().commit();
      } catch (Exception e) {
        try {
          System.out.println(
              "CANNOT CLEAN UP TEST (" + this.getClass().getSimpleName() + ") Cause: " + e);
          getTransactionManager().rollback();
        } catch (Exception ignore) {
        }
      } finally {
        if (null != em) {
          em.close();
        }
      }
    }
  }
  public List<MetricDisplaySummary> getMetrics(
      Resource parentResource,
      AutoGroupComposite resourceGroupComposite,
      Subject subject,
      long beginTime,
      long endTime)
      throws MeasurementException {
    if (log.isTraceEnabled()) {
      log.trace(
          "finding metric summaries for resourceType ["
              + resourceGroupComposite.getResourceType().getName());
    }

    List<MetricDisplaySummary> metricSummaries = null;
    // TODO GH: Why are we only getting the first one? --> single resource case
    //

    List resources = resourceGroupComposite.getResources();
    if ((resources != null) && (resources.size() == 1)) {
      ResourceWithAvailability resource = (ResourceWithAvailability) resources.get(0);

      metricSummaries =
          chartsManager.getMetricDisplaySummariesForMetrics(
              subject,
              resource.getResource().getId(),
              DataType.MEASUREMENT,
              beginTime,
              endTime,
              true,
              true);
    } else if ((resources != null) && (resources.size() > 1)) {
      List<Resource> res = new ArrayList<Resource>();
      for (Object o : resources) {
        if (o instanceof ResourceWithAvailability) {
          ResourceWithAvailability rwa = (ResourceWithAvailability) o;
          res.add(rwa.getResource());
        }
      }

      Map<Integer, List<MetricDisplaySummary>> sumMap =
          dataManager.findNarrowedMetricDisplaySummariesForCompatibleResources(
              subject, res, beginTime, endTime);
      metricSummaries = sumMap.values().iterator().next();

      // fill in some data that does not come from the backend
      for (MetricDisplaySummary tmp : metricSummaries) {
        tmp.setParentId(parentResource.getId());
        tmp.setChildTypeId(resourceGroupComposite.getResourceType().getId());
      }
    }

    return metricSummaries;
  }
    private ResourceTreeNode(Resource resource) {
      this.resource = resource;

      String id = String.valueOf(resource.getId());
      String parentId =
          resource.getParentResource() == null
              ? null
              : String.valueOf((resource.getParentResource().getId()));

      setID(id);
      setParentID(parentId);

      setAttribute("id", id);
      setAttribute("parentId", parentId);
      setAttribute("name", resource.getName());
      setAttribute("timestamp", ""); // String.valueOf(resource.getItime())); // Seems to be null
      setAttribute(
          "currentAvailability",
          ImageManager.getAvailabilityIconFromAvailType(
              resource.getCurrentAvailability().getAvailabilityType()));
    }
    @Override
    public ListGridRecord copyValues(AlertDefinition from) {
      // in order to support sorting our list grid on the parent and resource columns,
      // we have to assign these to something that is sortable
      ListGridRecord record = super.copyValues(from);
      Resource resource = from.getResource();

      record.setAttribute(FIELD_RESOURCE, resource.getName());

      Integer parentId =
          from.getParentId(); // a valid non-zero number means the alert def came from a template
      AlertDefinition groupAlertDefinition = from.getGroupAlertDefinition();

      if (parentId != null && parentId.intValue() > 0) {
        record.setAttribute(FIELD_PARENT, "<b>" + MSG.view_alert_definition_for_type() + "</b>");
      } else if (groupAlertDefinition != null) {
        record.setAttribute(FIELD_PARENT, "<b>" + MSG.view_alert_definition_for_group() + "</b>");
      }

      // for ancestry handling
      record.setAttribute(AncestryUtil.RESOURCE_ID, resource.getId());
      record.setAttribute(AncestryUtil.RESOURCE_NAME, resource.getName());
      record.setAttribute(AncestryUtil.RESOURCE_ANCESTRY, resource.getAncestry());
      record.setAttribute(AncestryUtil.RESOURCE_TYPE_ID, resource.getResourceType().getId());

      return record;
    }
  private void loadTree() {
    int searchId;
    Resource currentResource = EnterpriseFacesContextUtility.getResourceIfExists();
    if (currentResource == null) {
      searchId = Integer.parseInt(FacesContextUtility.getOptionalRequestParameter("parent"));
    } else {
      searchId = currentResource.getId();
    }

    Subject user = EnterpriseFacesContextUtility.getSubject();

    long start = System.currentTimeMillis();
    long monitorId = HibernatePerformanceMonitor.get().start();
    Resource rootResource = resourceManager.getRootResourceForResource(searchId);
    long end = System.currentTimeMillis();
    HibernatePerformanceMonitor.get().stop(monitorId, "ResourceTree root resource");
    log.debug("Found root resource in " + (end - start));

    Agent agent =
        agentManager.getAgentByResourceId(
            LookupUtil.getSubjectManager().getOverlord(), rootResource.getId());

    start = System.currentTimeMillis();
    monitorId = HibernatePerformanceMonitor.get().start();
    List<ResourceFlyweight> resources =
        resourceManager.findResourcesByAgent(
            user, agent.getId(), PageControl.getUnlimitedInstance());
    end = System.currentTimeMillis();
    HibernatePerformanceMonitor.get().stop(monitorId, "ResourceTree agent resource");
    log.debug("Loaded " + resources.size() + " raw resources in " + (end - start));

    start = System.currentTimeMillis();
    monitorId = HibernatePerformanceMonitor.get().start();
    rootNode = load(rootResource.getId(), resources);
    end = System.currentTimeMillis();
    HibernatePerformanceMonitor.get().stop(monitorId, "ResourceTree tree construction");
    log.debug("Constructed tree in " + (end - start));
  }
  /**
   * This operates differently from the other {{checkConditions()}} methods. Because it's possible
   * that one batch of events may contain both an event triggering a problem event and also an event
   * triggering its recovery alert, we return after a matched condition to allow for the caller to
   * check remaining events only after a cache refresh has been performed.
   *
   * @param stats not null. the stats object to update
   * @param source
   * @param events
   * @return the number of eventsProcessed until a match was found or all events were processed.
   */
  public AlertConditionCacheStats checkConditions(EventSource source, List<Event> events) {
    AlertConditionCacheStats stats = new AlertConditionCacheStats();
    if ((events == null) || events.isEmpty()) {
      return stats;
    }

    int initialSize = events.size();
    try {
      Resource resource = source.getResource();
      List<EventCacheElement> cacheElements = lookupEventCacheElements(resource.getId());

      for (Iterator<Event> i = events.iterator(); i.hasNext(); ) {
        Event event = i.next();
        i.remove();
        int matched = stats.matched;
        processCacheElements(
            cacheElements,
            event.getSeverity(),
            event.getTimestamp(),
            stats,
            event.getDetail(),
            "sourceLocation=" + source.getLocation());
        if (matched < stats.matched) {
          break;
        }
      }

      AlertConditionCacheMonitor.getMBean().incrementEventCacheElementMatches(stats.matched);
      AlertConditionCacheMonitor.getMBean().incrementEventProcessingTime(stats.getAge());
      if (log.isDebugEnabled()) {
        log.debug("Check Events[size=" + (initialSize - events.size()) + "] - " + stats);
      }
    } catch (Throwable t) {
      // don't let any exceptions bubble up to the calling SLSB layer
      log.error("Error during event cache processing for agent[id=" + agentId + "]", t);
    }
    return stats;
  }
  private void refreshSingletons(
      final Resource parentResource, final AsyncCallback<PageList<Resource>> callback) {
    singletonChildren = new ArrayList<Resource>(); // initialize to non-null

    Integer[] singletonChildTypes = getSingletonChildTypes(parentResource.getResourceType());

    if (canCreate && singletonChildTypes.length > 0 && (hasCreatableTypes || hasImportableTypes)) {
      ResourceCriteria criteria = new ResourceCriteria();
      criteria.addFilterParentResourceId(parentResource.getId());
      criteria.addFilterResourceTypeIds(singletonChildTypes);
      GWTServiceLookup.getResourceService()
          .findResourcesByCriteria(
              criteria,
              new AsyncCallback<PageList<Resource>>() {

                @Override
                public void onSuccess(PageList<Resource> result) {
                  singletonChildren = result;
                  if (callback != null) {
                    callback.onSuccess(result);
                  }
                }

                @Override
                public void onFailure(Throwable caught) {
                  Log.error("Failed to load child resources for [" + parentResource + "]", caught);
                  if (callback != null) {
                    callback.onFailure(caught);
                  }
                }
              });
    } else {
      if (callback != null) {
        callback.onSuccess(new PageList<Resource>());
      }
    }
  }
  /**
   * Tests that the JON Agent can be discovered.
   *
   * @throws Exception
   */
  public void testServerDiscovery() throws Exception {
    InventoryReport report = pc.getInventoryManager().executeServerScanImmediately();
    assert report != null;

    Resource platform = pc.getInventoryManager().getPlatform();
    Set<Resource> servers = platform.getChildResources();
    assert servers.size() > 0;

    Resource agent_resource = servers.iterator().next();
    assert agent_resource.getName().indexOf("RHQ Agent") > -1
        : "Bad name: " + agent_resource.getName();
    assert agent_resource.getResourceType().getName().equals(AGENT_RESOURCE_TYPE_NAME)
        : "Bad type: " + agent_resource.getResourceType();
    assert agent_resource.getResourceType().getCategory() == ResourceCategory.SERVER
        : "Bad type: " + agent_resource.getResourceType();

    pc.getInventoryManager().executeServiceScanImmediately();

    InventoryPrinter.outputInventory(new PrintWriter(System.out), false);
  }
  private void removeExistingSingletons(
      List<Resource> singletonChildren, Map<String, ResourceType> displayNameMap) {

    List<String> existingSingletons = new ArrayList<String>();

    Set<String> displayNames = displayNameMap.keySet();
    for (final String displayName : displayNames) {
      final ResourceType type = displayNameMap.get(displayName);
      boolean exists = false;

      if (type.isSingleton()) {
        for (Resource child : singletonChildren) {
          exists = child.getResourceType().equals(displayNameMap.get(displayName));
          if (exists) {
            existingSingletons.add(displayName);
            break;
          }
        }
      }
    }
    for (String existing : existingSingletons) {
      displayNameMap.remove(existing);
    }
  }