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;
  }
  /**
   * 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);
      }
    }
  }
  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;
  }
    @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 static Resource convertToPojoResource(Resource resource, boolean includeDescendants) {
    Resource pojoResource = new Resource(resource.getId());
    pojoResource.setUuid(resource.getUuid());
    pojoResource.setResourceKey(resource.getResourceKey());
    pojoResource.setResourceType(resource.getResourceType());
    pojoResource.setMtime(resource.getMtime());
    pojoResource.setInventoryStatus(resource.getInventoryStatus());
    Configuration pcCopy = resource.getPluginConfiguration();
    if (pcCopy != null) {
      pcCopy = pcCopy.deepCopy();
    }
    pojoResource.setPluginConfiguration(pcCopy);
    pojoResource.setName(resource.getName());
    pojoResource.setDescription(resource.getDescription());
    pojoResource.setLocation(resource.getLocation());
    pojoResource.setVersion(resource.getVersion());

    if (resource.getParentResource() != null) {
      pojoResource.setParentResource(convertToPojoResource(resource.getParentResource(), false));
    }
    if (includeDescendants) {
      for (Resource childResource : resource.getChildResources()) {
        if (isVisibleInInventory(childResource)) {
          pojoResource.addChildResource(convertToPojoResource(childResource, true));
        }
      }
    }
    return pojoResource;
  }
Example #6
0
 public Resource getResource(int resourceId) {
   for (Resource resource : resources) {
     if (resourceId == resource.getId()) {
       return resource;
     }
   }
   return null;
 }
Example #7
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()));
    }
  }
  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 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));
  }
  @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;
  }
Example #11
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();
        }
      }
    }
  }
    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()));
    }
Example #13
0
  /**
   * 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>());
      }
    }
  }
    public MockInventoryManager() {
      super(pcConfig, null, pluginManager, new EventManager(pcConfig));
      platformType =
          new ResourceType(
              "platformResourceTypeName", "pluginName", ResourceCategory.PLATFORM, null);
      bundleHandlerType =
          new ResourceType("bhRTypeName", "pluginName", ResourceCategory.SERVER, platformType);
      serverTypeFS =
          new ResourceType(
              "typeName-fileSystem", "pluginName", ResourceCategory.SERVER, platformType);
      serverTypePC =
          new ResourceType(
              "typeName-plugConfig", "pluginName", ResourceCategory.SERVER, platformType);
      serverTypeRC =
          new ResourceType(
              "typeName-reSconfig", "pluginName", ResourceCategory.SERVER, platformType);
      serverTypeMT =
          new ResourceType("typeName-trait", "pluginName", ResourceCategory.SERVER, platformType);

      int id = 1;
      platform = new Resource("platformKey", "platformName", platformType);
      platform.setId(id++);
      bundleHandler = new Resource("bhKey", "bhName", bundleHandlerType);
      bundleHandler.setId(id++);
      bundleHandler.setParentResource(platform);
      bundleHandler.setUuid(UUID.randomUUID().toString());
      serverFS = new Resource("serverKey-fileSystem", "serverName-fileSystem", serverTypeFS);
      serverFS.setId(id++);
      serverFS.setParentResource(platform);
      serverPC = new Resource("serverKey-plugConfig", "serverName-plugConfig", serverTypePC);
      serverPC.setId(id++);
      serverPC.setParentResource(platform);
      serverRC = new Resource("serverKey-resConfig", "serverName-resConfig", serverTypeRC);
      serverRC.setId(id++);
      serverRC.setParentResource(platform);
      serverMT = new Resource("serverKey-traitConfig", "serverName-traitConfig", serverTypeMT);
      serverMT.setId(id++);
      serverMT.setParentResource(platform);

      typeResourceMap.put(platformType, platform);
      typeResourceMap.put(bundleHandlerType, bundleHandler);
      typeResourceMap.put(serverTypeFS, serverFS);
      typeResourceMap.put(serverTypePC, serverPC);
      typeResourceMap.put(serverTypeRC, serverRC);
      typeResourceMap.put(serverTypeMT, serverMT);

      ResourceContainer platformContainer = new ResourceContainer(platform, null);
      ResourceContainer bundleHandlerContainer = new ResourceContainer(bundleHandler, null);
      ResourceContainer serverContainerFS = new ResourceContainer(serverFS, null);
      ResourceContainer serverContainerPC = new ResourceContainer(serverPC, null);
      ResourceContainer serverContainerRC = new ResourceContainer(serverRC, null);
      ResourceContainer serverContainerMT = new ResourceContainer(serverMT, null);
      idResourceContainerMap.put(platform.getId(), platformContainer);
      idResourceContainerMap.put(bundleHandler.getId(), bundleHandlerContainer);
      idResourceContainerMap.put(serverFS.getId(), serverContainerFS);
      idResourceContainerMap.put(serverPC.getId(), serverContainerPC);
      idResourceContainerMap.put(serverRC.getId(), serverContainerRC);
      idResourceContainerMap.put(serverMT.getId(), serverContainerMT);

      bundleHandlerContainer.setResourceContext(new MockResourceContext(bundleHandler));

      // each different resource type that supports bundle deployments needs to define its
      // bundle configuration to denote where the base directory location is found.
      // Today we support four ways: via plugin config property, resource config property,
      // measurement trait value, or strictly on the root file system (using no resource specific
      // value)
      ResourceTypeBundleConfiguration rtbc =
          new ResourceTypeBundleConfiguration(new Configuration());
      rtbc.addBundleDestinationBaseDirectory(
          BUNDLE_CONFIG_NAME_FS, Context.fileSystem.name(), BUNDLE_CONFIG_CONTEXT_VALUE_FS, null);
      serverTypeFS.setResourceTypeBundleConfiguration(rtbc);

      rtbc = new ResourceTypeBundleConfiguration(new Configuration());
      rtbc.addBundleDestinationBaseDirectory(
          BUNDLE_CONFIG_NAME_PC,
          Context.pluginConfiguration.name(),
          BUNDLE_CONFIG_CONTEXT_VALUE_PC,
          null);
      serverTypePC.setResourceTypeBundleConfiguration(rtbc);

      rtbc = new ResourceTypeBundleConfiguration(new Configuration());
      rtbc.addBundleDestinationBaseDirectory(
          BUNDLE_CONFIG_NAME_RC,
          Context.resourceConfiguration.name(),
          BUNDLE_CONFIG_CONTEXT_VALUE_RC,
          null);
      serverTypeRC.setResourceTypeBundleConfiguration(rtbc);

      rtbc = new ResourceTypeBundleConfiguration(new Configuration());
      rtbc.addBundleDestinationBaseDirectory(
          BUNDLE_CONFIG_NAME_MT,
          Context.measurementTrait.name(),
          BUNDLE_CONFIG_CONTEXT_VALUE_MT,
          null);
      serverTypeMT.setResourceTypeBundleConfiguration(rtbc);

      // each different resource needs to specify where exactly it wants the bundles deployed
      // using the different contexts that are supported.
      Configuration pluginConfiguration = new Configuration();
      pluginConfiguration.put(
          new PropertySimple(BUNDLE_CONFIG_CONTEXT_VALUE_PC, BUNDLE_CONFIG_LOCATION_PC));
      serverPC.setPluginConfiguration(pluginConfiguration);

      Configuration resourceConfiguration = new Configuration();
      resourceConfiguration.put(
          new PropertySimple(BUNDLE_CONFIG_CONTEXT_VALUE_RC, BUNDLE_CONFIG_LOCATION_RC));
      serverRC.setResourceConfiguration(resourceConfiguration);

      MeasurementDefinition definition =
          new MeasurementDefinition(serverTypeMT, BUNDLE_CONFIG_CONTEXT_VALUE_MT);
      definition.setDataType(DataType.TRAIT);
      definition.setId(123);
      MeasurementSchedule schedule = new MeasurementSchedule(definition, serverMT);
      schedule.setId(123123);
      MeasurementScheduleRequest scheduleRequest = new MeasurementScheduleRequest(schedule);
      Set<MeasurementScheduleRequest> schedules = new HashSet<MeasurementScheduleRequest>(1);
      schedules.add(scheduleRequest);
      serverContainerMT.setMeasurementSchedule(schedules);
    }
Example #16
0
  @Test(enabled = ENABLE_TESTS)
  public void testDriftDef() throws Exception {
    Configuration config = new Configuration();
    DriftDefinition driftDefPojo = new DriftDefinition(config);
    driftDefPojo.setName("testDriftDef");
    driftDefPojo.setInterval(60L);
    driftDefPojo.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem, "foo/bar"));

    driftManager.updateDriftDefinition(
        overlord, EntityContext.forResource(newResource.getId()), driftDefPojo);

    ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();
    ResourceCriteria c = new ResourceCriteria();
    c.addFilterId(newResource.getId());
    c.fetchDriftDefinitions(true);
    List<Resource> resources = resourceManager.findResourcesByCriteria(overlord, c);
    assertEquals(1, resources.size());
    Set<DriftDefinition> driftDefs = resources.get(0).getDriftDefinitions();
    assertNotNull(driftDefs);
    assertEquals(3, driftDefs.size());
    DriftDefinition driftDef = null;
    for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext(); ) {
      driftDef = i.next();
      if (driftDefPojo.getName().equals(driftDef.getName())) break;
    }
    assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
    assertEquals(driftDefPojo.getName(), driftDef.getName());
    assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
    assertEquals(driftDefPojo.getInterval(), driftDef.getInterval());

    driftDefPojo.setInterval(120L);
    driftManager.updateDriftDefinition(
        overlord, EntityContext.forResource(newResource.getId()), driftDefPojo);

    resources = resourceManager.findResourcesByCriteria(overlord, c);
    assertEquals(1, resources.size());
    driftDefs = resources.get(0).getDriftDefinitions();
    assertNotNull(driftDefs);
    assertEquals(3, driftDefs.size());
    driftDef = null;
    for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext(); ) {
      driftDef = i.next();
      if (driftDefPojo.getName().equals(driftDef.getName())) break;
    }
    assertEquals(driftDefPojo.getName(), driftDef.getName());
    assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
    assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
    assertEquals(120L, driftDef.getInterval());

    driftDefPojo.setName("testDriftDef-2");
    driftDefPojo.setInterval(30L);
    driftDefPojo.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem, "foo/baz"));

    driftManager.updateDriftDefinition(
        overlord, EntityContext.forResource(newResource.getId()), driftDefPojo);

    resources = resourceManager.findResourcesByCriteria(overlord, c);
    assertEquals(1, resources.size());
    driftDefs = resources.get(0).getDriftDefinitions();
    assertNotNull(driftDefs);
    assertEquals(4, driftDefs.size());
    for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext(); ) {
      driftDef = i.next();
      if ("testDriftDef".equals(driftDef.getName())) {
        assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
        assertEquals("foo/bar", driftDef.getBasedir().getValueName());
        assertEquals(BaseDirValueContext.fileSystem, driftDef.getBasedir().getValueContext());
        assertEquals(120L, driftDef.getInterval());
      } else if ("testDriftDef-2".equals(driftDef.getName())) {
        assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
        assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
        assertEquals(driftDefPojo.getInterval(), driftDef.getInterval());
      } else if (!"test-1".equals(driftDef.getName()) && !"test-2".equals(driftDef.getName())) {
        fail("Unexpected drift def name: " + driftDef.getName());
      }
    }

    driftManager.deleteDriftDefinition(
        overlord, EntityContext.forResource(newResource.getId()), "testDriftDef");
    resources = resourceManager.findResourcesByCriteria(overlord, c);
    assertEquals(1, resources.size());
    driftDefs = resources.get(0).getDriftDefinitions();
    assertNotNull(driftDefs);
    assertEquals(3, driftDefs.size());
    for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext(); ) {
      driftDef = i.next();
      if (driftDefPojo.getName().equals(driftDef.getName())) break;
    }
    assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
    assertEquals(driftDefPojo.getName(), driftDef.getName());
    assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
    assertEquals(driftDefPojo.getInterval(), driftDef.getInterval());
  }
  @Test
  public void testDriftDef() throws Exception {
    Configuration config = new Configuration();
    DriftDefinition driftDefPojo = new DriftDefinition(config);
    driftDefPojo.setName("testDriftDef");
    driftDefPojo.setInterval(60L);
    driftDefPojo.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem, "foo/bar"));

    driftManager.updateDriftDefinition(
        overlord, EntityContext.forResource(newResource.getId()), driftDefPojo);

    DriftDefinitionCriteria c = new DriftDefinitionCriteria();
    c.addFilterResourceIds(newResource.getId());
    c.fetchConfiguration(true);
    List<DriftDefinition> driftDefs = driftManager.findDriftDefinitionsByCriteria(overlord, c);
    assertNotNull(driftDefs);
    assertEquals(3, driftDefs.size());
    DriftDefinition driftDef = null;
    for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext(); ) {
      driftDef = i.next();
      if (driftDefPojo.getName().equals(driftDef.getName())) break;
    }
    assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
    assertEquals(driftDefPojo.getName(), driftDef.getName());
    assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
    assertEquals(driftDefPojo.getInterval(), driftDef.getInterval());

    driftDefPojo.setInterval(120L);
    driftManager.updateDriftDefinition(
        overlord, EntityContext.forResource(newResource.getId()), driftDefPojo);

    driftDefs = driftManager.findDriftDefinitionsByCriteria(overlord, c);
    assertNotNull(driftDefs);
    assertEquals(3, driftDefs.size());
    driftDef = null;
    for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext(); ) {
      driftDef = i.next();
      if (driftDefPojo.getName().equals(driftDef.getName())) break;
    }
    assertEquals(driftDefPojo.getName(), driftDef.getName());
    assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
    assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
    assertEquals(120L, driftDef.getInterval());

    driftDefPojo = new DriftDefinition(driftDef.getConfiguration().deepCopyWithoutProxies());
    driftDefPojo.setName("testDriftDef-2");
    driftDefPojo.setInterval(30L);
    driftDefPojo.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem, "foo/baz"));

    driftManager.updateDriftDefinition(
        overlord, EntityContext.forResource(newResource.getId()), driftDefPojo);

    driftDefs = driftManager.findDriftDefinitionsByCriteria(overlord, c);
    assertNotNull(driftDefs);
    assertEquals(4, driftDefs.size());
    for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext(); ) {
      driftDef = i.next();
      if ("testDriftDef".equals(driftDef.getName())) {
        assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
        assertEquals("foo/bar", driftDef.getBasedir().getValueName());
        assertEquals(BaseDirValueContext.fileSystem, driftDef.getBasedir().getValueContext());
        assertEquals(120L, driftDef.getInterval());
      } else if ("testDriftDef-2".equals(driftDef.getName())) {
        assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
        assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
        assertEquals(driftDefPojo.getInterval(), driftDef.getInterval());
      } else if (!"test-1".equals(driftDef.getName()) && !"test-2".equals(driftDef.getName())) {
        fail("Unexpected drift def name: " + driftDef.getName());
      }
    }

    driftManager.deleteDriftDefinition(
        overlord, EntityContext.forResource(newResource.getId()), "testDriftDef");
    driftDefs = driftManager.findDriftDefinitionsByCriteria(overlord, c);
    assertNotNull(driftDefs);
    assertEquals(3, driftDefs.size());
    for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext(); ) {
      driftDef = i.next();
      if (driftDefPojo.getName().equals(driftDef.getName())) break;
    }
    assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
    assertEquals(driftDefPojo.getName(), driftDef.getName());
    assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
    assertEquals(driftDefPojo.getInterval(), driftDef.getInterval());
  }
  public void checkConfigurations(Resource resource, boolean checkChildren) {
    ResourceContainer resourceContainer = this.inventoryManager.getResourceContainer(resource);
    ConfigurationFacet resourceComponent = null;
    ResourceType resourceType = resource.getResourceType();

    if (resourceContainer != null
        && resourceContainer.getAvailability() != null
        && resourceContainer.getAvailability().getAvailabilityType() == AvailabilityType.UP) {

      try {
        resourceComponent =
            resourceContainer.createResourceComponentProxy(
                ConfigurationFacet.class,
                FacetLockType.NONE,
                CONFIGURATION_CHECK_TIMEOUT,
                true,
                false);
      } catch (PluginContainerException e) {
        // Expecting when the resource does not support configuration management
      }

      if (resourceComponent != null) {
        // Only report availability for committed resources; don't bother with new, ignored or
        // deleted resources.
        if (resource.getInventoryStatus() == InventoryStatus.COMMITTED
            && resourceType.getResourceConfigurationDefinition() != null) {

          if (log.isErrorEnabled())
            log.debug("Checking for updated resource configuration on: " + resource);

          ConfigurationUpdateRequest request =
              new ConfigurationUpdateRequest(
                  0, resource.getResourceConfiguration(), resource.getId());

          try {

            Configuration liveConfiguration = resourceComponent.loadResourceConfiguration();

            if (liveConfiguration != null) {
              ConfigurationDefinition configurationDefinition =
                  resourceType.getResourceConfigurationDefinition();

              // Normalize and validate the config.
              ConfigurationUtility.normalizeConfiguration(
                  liveConfiguration, configurationDefinition);
              List<String> errorMessages =
                  ConfigurationUtility.validateConfiguration(
                      liveConfiguration, configurationDefinition);
              for (String errorMessage : errorMessages) {
                log.warn(
                    "Plugin Error: Invalid "
                        + resourceType.getName()
                        + " resource configuration returned by "
                        + resourceType.getPlugin()
                        + " plugin - "
                        + errorMessage);
              }

              Configuration original = resource.getResourceConfiguration();
              if (!liveConfiguration.equals(original)) {
                log.info("New configuration version detected on resource: " + resource);
                this.configurationServerService.persistUpdatedResourceConfiguration(
                    resource.getId(), liveConfiguration);
                resource.setResourceConfiguration(liveConfiguration);
              }
            }
          } catch (Throwable t) {
            log.warn("Unable to check for updated configuration", t);
          }
        }
      }

      if (checkChildren) {
        // Avoid concurrent mod exceptions during potentially long duration issues
        Set<Resource> childSet = new HashSet<Resource>(resource.getChildResources());
        for (Resource child : childSet) {
          try {
            checkConfigurations(child, true);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
  @Test
  public void testStoreChangeSet() throws Exception {
    File rootDir = getTempDir();
    File changeSetsDir = new File(rootDir, "changesets");
    deleteDirectory(changeSetsDir);
    changeSetsDir.mkdirs();

    Headers headers = new Headers();
    headers.setResourceId(newResource.getId());
    headers.setDriftDefinitionId(1);
    headers.setDriftDefinitionName("test-1");
    headers.setBasedir(rootDir.getAbsolutePath());
    headers.setType(COVERAGE);
    headers.setVersion(0);

    String file1Hash = sha256("test-1-file-1");

    File changeSet1 = new File(changeSetsDir, "changeset-1.txt");
    ChangeSetWriter writer = new ChangeSetWriterImpl(changeSet1, headers);
    writer.write(addedFileEntry("test/file-1", file1Hash, 56789L, 1024L));
    writer.close();

    File changeSet1Zip = new File(changeSetsDir, "changeset-1.zip");
    ZipUtil.zipFileOrDirectory(changeSet1, changeSet1Zip);

    assertTrue(
        "Expected to find change set zip file: " + changeSet1Zip.getPath(), changeSet1Zip.exists());

    jpaDriftServer.storeChangeSet(overlord, newResource.getId(), changeSet1Zip);

    JPADriftChangeSetCriteria c = new JPADriftChangeSetCriteria();
    c.addFilterResourceId(newResource.getId());
    c.fetchDrifts(true);
    List<? extends DriftChangeSet<?>> changeSets =
        jpaDriftServer.findDriftChangeSetsByCriteria(overlord, c);
    assertEquals(1, changeSets.size());
    DriftChangeSet<?> changeSet = changeSets.get(0);
    assertEquals(0, changeSet.getVersion());
    assertEquals("Expected to find one entry in change set", 1, changeSet.getDrifts().size());

    DriftFile driftFile = jpaDriftServer.getDriftFile(overlord, file1Hash);
    assertNotNull(driftFile);
    assertEquals(DriftFileStatus.REQUESTED, driftFile.getStatus());

    // the second change set should report drift
    String modifiedFile1Hash = sha256("test-2-file-1-modified");
    headers.setType(DRIFT);
    headers.setVersion(1);
    File changeSet2 = new File(changeSetsDir, "changeset-2.txt");

    writer = new ChangeSetWriterImpl(changeSet2, headers);
    writer.write(changedFileEntry("test/file-1", file1Hash, modifiedFile1Hash, 56789L, 1024L));
    writer.close();

    File changeSet2Zip = new File(changeSetsDir, "changeset-2.zip");
    ZipUtil.zipFileOrDirectory(changeSet2, changeSet2Zip);

    assertTrue(
        "Expected to find change set file: " + changeSet2Zip.getPath(), changeSet2Zip.exists());

    jpaDriftServer.storeChangeSet(overlord, newResource.getId(), changeSet2Zip);
    c.addSortVersion(PageOrdering.ASC);
    c.addFilterCategory(DRIFT);
    changeSets = jpaDriftServer.findDriftChangeSetsByCriteria(overlord, c);
    assertEquals(1, changeSets.size());
    changeSet = changeSets.get(0);
    assertEquals("The change set version is wrong", 1, changeSet.getVersion());
    assertEquals("Expected to find one entry in change set", 1, changeSet.getDrifts().size());
    changeSet = changeSets.get(0);
    assertEquals(1, changeSet.getVersion());
    assertEquals(1, changeSet.getDrifts().size());
    Drift<?, ?> drift = changeSet.getDrifts().iterator().next();
    assertEquals("test/file-1", drift.getPath());
    assertEquals(file1Hash, drift.getOldDriftFile().getHashId());
    assertEquals(modifiedFile1Hash, drift.getNewDriftFile().getHashId());
    assertEquals(DriftCategory.FILE_CHANGED, drift.getCategory());

    driftFile = jpaDriftServer.getDriftFile(overlord, modifiedFile1Hash);
    assertNotNull(driftFile);
    assertEquals(DriftFileStatus.REQUESTED, driftFile.getStatus());
  }
 @Override
 public ResourceContainer getResourceContainer(Resource resource) {
   if (idResourceContainerMap == null) return null;
   return idResourceContainerMap.get(resource.getId());
 }
 public int extract(Resource r) {
   return r.getId();
 }
  protected Dashboard getDefaultDashboard() {
    Subject sessionSubject = UserSessionManager.getSessionSubject();
    Resource resource = resourceComposite.getResource();

    Dashboard dashboard = new Dashboard();

    dashboard.setName(DASHBOARD_NAME_PREFIX + sessionSubject.getId() + "_" + resource.getId());
    dashboard.setCategory(DashboardCategory.RESOURCE);
    dashboard.setResource(resource);
    dashboard.setColumns(2);

    // TODO, add real portlets
    // set leftmost column and let the rest be equally divided
    dashboard.setColumnWidths("40%");
    dashboard.getConfiguration().put(new PropertySimple(Dashboard.CFG_BACKGROUND, "#F1F2F3"));

    // figure out which portlets to display and how
    HashMap<String, String> resKeyNameMap =
        DashboardView.processPortletNameMapForResource(resourceComposite);
    int colLeft = 0;
    int colRight = 1;
    int rowLeft = 0;
    int rowRight = 0;
    // Left Column
    if (resKeyNameMap.containsKey(
        ResourceMetricsPortlet.KEY)) { // measurments top left if available
      DashboardPortlet measurements =
          new DashboardPortlet(ResourceMetricsPortlet.NAME, ResourceMetricsPortlet.KEY, 220);
      dashboard.addPortlet(measurements, colLeft, rowLeft++);
      resKeyNameMap.remove(ResourceMetricsPortlet.KEY);
    }

    // right Column(approx 60%. As larger more room to display table and N rows.)
    if (resKeyNameMap.containsKey(ResourceAlertsPortlet.KEY)) { // alerts top right if available
      DashboardPortlet alerts =
          new DashboardPortlet(ResourceAlertsPortlet.NAME, ResourceAlertsPortlet.KEY, 220);
      dashboard.addPortlet(alerts, colRight, rowRight++);
      resKeyNameMap.remove(ResourceAlertsPortlet.KEY);
    }
    if (resKeyNameMap.containsKey(ResourceOperationsPortlet.KEY)) { // operations if available
      DashboardPortlet ops =
          new DashboardPortlet(ResourceOperationsPortlet.NAME, ResourceOperationsPortlet.KEY, 220);
      dashboard.addPortlet(ops, colRight, rowRight++);
      resKeyNameMap.remove(ResourceOperationsPortlet.KEY);
    }
    if (resKeyNameMap.containsKey(
        ResourceConfigurationUpdatesPortlet.KEY)) { // configuration if available
      DashboardPortlet ops =
          new DashboardPortlet(
              ResourceConfigurationUpdatesPortlet.NAME,
              ResourceConfigurationUpdatesPortlet.KEY,
              220);
      dashboard.addPortlet(ops, colRight, rowRight++);
      resKeyNameMap.remove(ResourceConfigurationUpdatesPortlet.KEY);
    }

    // Fill out left column(typically smaller portlets) then alternate cols with remaining
    boolean displayLeft = false;
    for (String key : resKeyNameMap.keySet()) {
      DashboardPortlet portlet = new DashboardPortlet(resKeyNameMap.get(key), key, 100);
      if (rowLeft < 4) {
        dashboard.addPortlet(portlet, colLeft, rowLeft++);
      } else { // alternate
        if (!displayLeft) {
          dashboard.addPortlet(portlet, colRight, rowRight++);
        } else {
          dashboard.addPortlet(portlet, colLeft, rowLeft++);
        }
        // toggle
        displayLeft = !displayLeft;
      }
    }

    return dashboard;
  }