Clean up unused rally collector items

@param collector
the {@link RallyCollector}
480790
@SuppressWarnings("PMD.AvoidDeeplyNestedIfStmts") // agreed PMD, fixme
	private void clean(RallyCollector collector, List<RallyProject> existingProjects) {
		Set<ObjectId> uniqueIDs = new HashSet<>();
		for (com.capitalone.dashboard.model.Component comp : dbComponentRepository.findAll()) {
			if (comp.getCollectorItems() != null && !comp.getCollectorItems().isEmpty()) {
				List<CollectorItem> itemList = comp.getCollectorItems().get(CollectorType.AgileTool);
				if (itemList != null) {
					for (CollectorItem ci : itemList) {
						if (ci != null && ci.getCollectorId().equals(collector.getId())) {
							uniqueIDs.add(ci.getId());
						}
					}
				}
			}
		}
		List<RallyProject> stateChangeJobList = new ArrayList<>();
		Set<ObjectId> udId = new HashSet<>();
		udId.add(collector.getId());
		for (RallyProject job : existingProjects) {
			// collect the jobs that need to change state : enabled vs disabled.
			if ((job.isEnabled() && !uniqueIDs.contains(job.getId())) || // if
			// it
			// was
			// enabled
			// but
			// not
			// on
			// a
			// dashboard
					(!job.isEnabled() && uniqueIDs.contains(job.getId()))) { // OR
				// it
				// was
				// disabled
				// and
				// now
				// on
				// a
				// dashboard
				job.setEnabled(uniqueIDs.contains(job.getId()));
				stateChangeJobList.add(job);
			}
		}
		if (!CollectionUtils.isEmpty(stateChangeJobList)) {
			rallyProjectRepository.save(stateChangeJobList);
		}
	}
158654
private void cleanUpDriverResources() {
    ctrlc.setComplete();
    try {
      Runtime.getRuntime().removeShutdownHook(ctrlc);
    }
    catch (IllegalStateException ignore) {
      // If "Shutdown in progress" exception would be thrown, just ignore and don't bother to remove the hook.
    }
    ctrlc = null;

    try {
      setShutdownRequested();
      driverCallbackSocket.close();
      driverCallbackSocket = null;
    }
    catch (Exception e) {
      System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)"));
      e.printStackTrace();
    }

    // At this point, resources are released.
    // The hadoop job has completed (job.isComplete() is true),
    // so the cluster memory and cpus are freed.
    // The driverCallbackSocket has been closed so a new one can be made.

    // The callbackManager itself may or may not have finished, but it doesn't
    // matter since the server socket has been closed.
  }
738062
public void cleanUpContainers() {

        List<String> removed = new ArrayList<String>();
        for (Entry<String, CmsContainerPageContainer> entry : m_targetContainers.entrySet()) {
            if (!RootPanel.getBodyElement().isOrHasChild(entry.getValue().getElement())) {
                removed.add(entry.getKey());
            }
        }
        for (String containerId : removed) {
            m_targetContainers.remove(containerId);
            m_containers.remove(containerId);
        }
        if (removed.size() > 0) {
            scheduleGalleryUpdate();
        }
    }
426775
@Override
    public void collect(FeatureCollector collector) {
        LOGGER.info("Starting Feature collection...");

        try {
            TeamDataClient teamData = new TeamDataClient(this.featureCollectorRepository,
                    this.featureSettings, this.teamRepository, this.v1Connection);

            teamData.updateTeamInformation();

            ProjectDataClient projectData = new ProjectDataClient(this.featureSettings,
                    this.projectRepository, this.featureCollectorRepository, this.v1Connection);
            projectData.updateProjectInformation();

            StoryDataClient storyData = new StoryDataClient(this.featureSettings,
                    this.featureRepository, this.featureCollectorRepository, this.v1Connection);
            storyData.updateStoryInformation();
        } catch (HygieiaException he) {
            LOGGER.error("Error in collecting Version One Data: [" + he.getErrorCode() + "] "
                    + he.getMessage());
        }

        LOGGER.info("Feature Data Collection Finished");

    }
582419
public static <E> void removeMatcing(Collection<E> collection, Matcher<? super E> matcher) {
		Iterator<E> iter = collection.iterator();
		while (iter.hasNext()) {
			E item = iter.next();
			if (matcher.matches(item)) iter.remove();
		}
	}
616681
public void clearUnused() {
	Log log = getLog();
	try {
	    // create cleaner engine for session/client scope
	    if (session == null) session = new StorageScopeEngine(factory, log, new StorageScopeCleaner[] { new FileStorageScopeCleaner(Scope.SCOPE_SESSION, null)// new
		    // SessionEndListener())
		    , new DatasourceStorageScopeCleaner(Scope.SCOPE_SESSION, null)// new
		    // SessionEndListener())
		    // ,new CacheStorageScopeCleaner(Scope.SCOPE_SESSION, new SessionEndListener())
	    });
	    if (client == null) client = new StorageScopeEngine(factory, log,
		    new StorageScopeCleaner[] { new FileStorageScopeCleaner(Scope.SCOPE_CLIENT, null), new DatasourceStorageScopeCleaner(Scope.SCOPE_CLIENT, null)
		    // ,new CacheStorageScopeCleaner(Scope.SCOPE_CLIENT, null) //Cache storage need no control, if
		    // there is no listener
		    });
	    // store session/client scope and remove from memory
	    storeUnusedStorageScope(factory, Scope.SCOPE_CLIENT);
	    storeUnusedStorageScope(factory, Scope.SCOPE_SESSION);

	    // remove unused memory based client/session scope (invoke onSessonEnd)
	    clearUnusedMemoryScope(factory, Scope.SCOPE_CLIENT);
	    clearUnusedMemoryScope(factory, Scope.SCOPE_SESSION);

	    // session must be executed first, because session creates a reference from client scope
	    session.clean();
	    client.clean();

	    // clean all unused application scopes
	    clearUnusedApplications(factory);
	}
	catch (Exception t) {
	    error(t);
	}
    }
1207684
public static final <T extends Recyclable> void recycle(Collection<T> recyclables)
    {
        recyclables.stream().forEach((recyclable) ->
        {
            recycle(recyclable);
        }
168745
private void cleanup_event_filters() {
        Enumeration keys = event_callback_map.keys();
        while (keys.hasMoreElements()) {
            String name = (String) keys.nextElement();
            EventCallBackStruct callback_struct = event_callback_map.get(name);
            if (callback_struct.consumer instanceof NotifdEventConsumer) {
                try {
                    EventChannelStruct ec_struct = channel_map.get(callback_struct.channel_name);
                    Filter filter = ec_struct.structuredProxyPushSupplier.get_filter(callback_struct.filter_id);
                    ec_struct.structuredProxyPushSupplier.remove_filter(callback_struct.filter_id);
                    filter.destroy();
                } catch (FilterNotFound e) {
                    // Do nothing
                }
            }
        }
    }
856471
public void collectStats(final StatsCollector collector) {
    final byte[][] kinds = {
        METRICS_QUAL.getBytes(CHARSET),
        TAG_NAME_QUAL.getBytes(CHARSET),
        TAG_VALUE_QUAL.getBytes(CHARSET)
      };
    try {
      final Map<String, Long> used_uids = UniqueId.getUsedUIDs(this, kinds)
        .joinUninterruptibly();

      collectUidStats(metrics, collector);
      if (config.getBoolean("tsd.core.uid.random_metrics")) {
        collector.record("uid.ids-used", 0, "kind=" + METRICS_QUAL);
        collector.record("uid.ids-available", 0, "kind=" + METRICS_QUAL);
      } else {
        collector.record("uid.ids-used", used_uids.get(METRICS_QUAL),
            "kind=" + METRICS_QUAL);
        collector.record("uid.ids-available",
            (Internal.getMaxUnsignedValueOnBytes(metrics.width()) -
                used_uids.get(METRICS_QUAL)), "kind=" + METRICS_QUAL);
      }

      collectUidStats(tag_names, collector);
      collector.record("uid.ids-used", used_uids.get(TAG_NAME_QUAL),
          "kind=" + TAG_NAME_QUAL);
      collector.record("uid.ids-available",
          (Internal.getMaxUnsignedValueOnBytes(tag_names.width()) -
              used_uids.get(TAG_NAME_QUAL)),
          "kind=" + TAG_NAME_QUAL);

      collectUidStats(tag_values, collector);
      collector.record("uid.ids-used", used_uids.get(TAG_VALUE_QUAL),
          "kind=" + TAG_VALUE_QUAL);
      collector.record("uid.ids-available",
          (Internal.getMaxUnsignedValueOnBytes(tag_values.width()) -
              used_uids.get(TAG_VALUE_QUAL)), "kind=" + TAG_VALUE_QUAL);

    } catch (Exception e) {
      throw new RuntimeException("Shouldn't be here", e);
    }

    collector.record("uid.filter.rejected", rejected_dps.get(), "kind=raw");
    collector.record("uid.filter.rejected", rejected_aggregate_dps.get(),
        "kind=aggregate");

    {
      final Runtime runtime = Runtime.getRuntime();
      collector.record("jvm.ramfree", runtime.freeMemory());
      collector.record("jvm.ramused", runtime.totalMemory());
    }

    collector.addExtraTag("class", "IncomingDataPoints");
    try {
      collector.record("hbase.latency", IncomingDataPoints.putlatency, "method=put");
    } finally {
      collector.clearExtraTag("class");
    }

    collector.addExtraTag("class", "TSDB");
    try {
      collector.record("datapoints.added", datapoints_added, "type=all");
    } finally {
      collector.clearExtraTag("class");
    }

    collector.addExtraTag("class", "TsdbQuery");
    try {
      collector.record("hbase.latency", TsdbQuery.scanlatency, "method=scan");
    } finally {
      collector.clearExtraTag("class");
    }
    final ClientStats stats = client.stats();
    collector.record("hbase.root_lookups", stats.rootLookups());
    collector.record("hbase.meta_lookups",
                     stats.uncontendedMetaLookups(), "type=uncontended");
    collector.record("hbase.meta_lookups",
                     stats.contendedMetaLookups(), "type=contended");
    collector.record("hbase.rpcs",
                     stats.atomicIncrements(), "type=increment");
    collector.record("hbase.rpcs", stats.deletes(), "type=delete");
    collector.record("hbase.rpcs", stats.gets(), "type=get");
    collector.record("hbase.rpcs", stats.puts(), "type=put");
    collector.record("hbase.rpcs", stats.appends(), "type=append");
    collector.record("hbase.rpcs", stats.rowLocks(), "type=rowLock");
    collector.record("hbase.rpcs", stats.scannersOpened(), "type=openScanner");
    collector.record("hbase.rpcs", stats.scans(), "type=scan");
    collector.record("hbase.rpcs.batched", stats.numBatchedRpcSent());
    collector.record("hbase.flushes", stats.flushes());
    collector.record("hbase.connections.created", stats.connectionsCreated());
    collector.record("hbase.connections.idle_closed", stats.idleConnectionsClosed());
    collector.record("hbase.nsre", stats.noSuchRegionExceptions());
    collector.record("hbase.nsre.rpcs_delayed",
                     stats.numRpcDelayedDueToNSRE());
    collector.record("hbase.region_clients.open",
        stats.regionClients());
    collector.record("hbase.region_clients.idle_closed",
        stats.idleConnectionsClosed());

    compactionq.collectStats(collector);
    // Collect Stats from Plugins
    if (startup != null) {
      try {
        collector.addExtraTag("plugin", "startup");
        startup.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (rt_publisher != null) {
      try {
        collector.addExtraTag("plugin", "publish");
        rt_publisher.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (authentication != null) {
      try {
        collector.addExtraTag("plugin", "authentication");
        authentication.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (search != null) {
      try {
        collector.addExtraTag("plugin", "search");
        search.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (storage_exception_handler != null) {
      try {
        collector.addExtraTag("plugin", "storageExceptionHandler");
        storage_exception_handler.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (ts_filter != null) {
      try {
        collector.addExtraTag("plugin", "timeseriesFilter");
        ts_filter.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
    if (uid_filter != null) {
      try {
        collector.addExtraTag("plugin", "uidFilter");
        uid_filter.collectStats(collector);
      } finally {
        collector.clearExtraTag("plugin");
      }
    }
  }
172812
public synchronized void setHandler(Handler handler) {
        String handlerId = CollectorManagerUtils.getHandlerId(handler);
        HandlerManager hdlrMgr;
        if (!handlerMgrs.containsKey(handlerId)) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Adding handler to the list", handler.getClass());
            }
            hdlrMgr = new HandlerManager(handler);
            handlerMgrs.put(hdlrMgr.getHandlerId(), hdlrMgr);
            hdlrMgr.getHandler().init(this);
        }
    }
1114324
@Override
   public final ReportDataHolderImpl collect() {
      holder = new BlockingDataHolder(dataQueueSize, queueTimeout);
      Runnable r = new collectThread();
      Thread t = new Thread(r, DATA_COLLECTOR_THREAD);
      t.setUncaughtExceptionHandler(this);
      t.start();
      return holder;
   }
656373
@SuppressWarnings("unchecked")
	public static <T> Collection<T> removeAny(Collection<T> collection, T... elesRemoved) {
		collection.removeAll(newHashSet(elesRemoved));
		return collection;
	}
16589
public void deleteMtoNImplementor(CollectionDescriptor cod, Object obj, Iterator collectionIterator, Collection mnKeys)
    {
        if(mnKeys.isEmpty() || collectionIterator == null)
        {
            return;
        }
        List workList = new ArrayList(mnKeys);
        MtoNBroker.Key relatedObjKeys;
        ClassDescriptor relatedCld = pb.getDescriptorRepository().getDescriptorFor(cod.getItemClass());
        Object relatedObj;

        // remove keys of relatedObject from the existing m:n rows in workList
        while(collectionIterator.hasNext())
        {
            relatedObj = collectionIterator.next();
            relatedObjKeys = new MtoNBroker.Key(pb.serviceBrokerHelper().getKeyValues(relatedCld, relatedObj, true));
            workList.remove(relatedObjKeys);
        }

        // delete all remaining keys in workList
        ClassDescriptor cld = pb.getDescriptorRepository().getDescriptorFor(obj.getClass());
        ValueContainer[] pkValues = pb.serviceBrokerHelper().getKeyValues(cld, obj);

        String[] pkColumns = cod.getFksToThisClass();
        String[] fkColumns = cod.getFksToItemClass();
        String table = cod.getIndirectionTable();
        String deleteStmt;

        ValueContainer[] fkValues;
        Iterator iter = workList.iterator();
        while(iter.hasNext())
        {
            fkValues = ((MtoNBroker.Key) iter.next()).m_containers;
            deleteStmt = pb.serviceSqlGenerator().getDeleteMNStatement(table, pkColumns, fkColumns);
            pb.serviceJdbcAccess().executeUpdateSQL(deleteStmt, cld, pkValues, fkValues);
        }
    }
494570
public boolean removeAll(Collection<?> collection) {
        boolean result = false;
        synchronized (mLock) {
            Iterator<?> it;
            if (mOriginalValues != null) {
                it = mOriginalValues.iterator();

            } else {
                it = mObjects.iterator();
            }
            while (it.hasNext()) {
                if (collection.contains(it.next())) {
                    it.remove();
                    result = true;
                }
            }
        }
        if (mNotifyOnChange) notifyDataSetChanged();
        return result;
    }
384703
public static void collect() {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                devicePropertiesCollector.collect();
                appStateCollector.collect();
            }
        });
    }
998763
function cleanUp() {
			_Helper.removeByPath(that.mPostRequests, sPath, oEntityData);
			aCollection.splice(aCollection.indexOf(oEntityData), 1);
			aCollection.$created -= 1;
			addToCount(that.mChangeListeners, sPath, aCollection, -1);
			delete aCollection.$byPredicate[sTransientPredicate];
			if (!sPath) {
				// Note: sPath is empty only in a CollectionCache, so we may call adjustReadRequests
				that.adjustReadRequests(0, -1);
			}
			fnCancelCallback();
		}
91358
public void cleanUp() {
    m_Owner     = null;
    m_Train     = null;
    m_Test      = null;
    m_Generator = null;
    m_Values    = null;
  }