@Override
  public void cacheStarted(ComponentRegistry cr, String cacheName) {
    Configuration configuration = cr.getComponent(Configuration.class);
    boolean indexingEnabled = configuration.indexing().enabled();
    if (!indexingEnabled) {
      if (verifyChainContainsQueryInterceptor(cr)) {
        throw new IllegalStateException(
            "It was NOT expected to find the Query interceptor registered in the InterceptorChain as indexing was disabled, but it was found");
      }
      return;
    }
    if (!verifyChainContainsQueryInterceptor(cr)) {
      throw new IllegalStateException(
          "It was expected to find the Query interceptor registered in the InterceptorChain but it wasn't found");
    }

    // initializing the query module command initializer.
    // we can t inject Cache and CacheManager with @inject in there
    Cache<?, ?> cache = cr.getComponent(Cache.class);
    CommandInitializer initializer = cr.getComponent(CommandInitializer.class);
    EmbeddedCacheManager cacheManager =
        cr.getGlobalComponentRegistry().getComponent(EmbeddedCacheManager.class);
    initializer.setCache(cache, cacheManager);

    QueryBox queryBox = new QueryBox();
    queryBox.setCache(cache.getAdvancedCache());
    cr.registerComponent(queryBox, QueryBox.class);

    // Register query mbeans
    registerQueryMBeans(cache.getAdvancedCache(), cr, cacheName);
  }
  @Override
  public void cacheStarted(ComponentRegistry cr, String cacheName) {
    InternalCacheRegistry icr =
        cr.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class);
    if (!icr.isInternalCache(cacheName)) {
      Configuration cfg = cr.getComponent(Configuration.class);
      boolean isIndexed = cfg.indexing().index().isEnabled();
      boolean isCompatMode = cfg.compatibility().enabled();
      if (isIndexed && !isCompatMode) {
        if (!verifyChainContainsRemoteValueWrapperInterceptor(cr)) {
          throw new IllegalStateException(
              "It was expected to find the RemoteValueWrapperInterceptor registered in the InterceptorChain but it wasn't found");
        }
      } else if (verifyChainContainsRemoteValueWrapperInterceptor(cr)) {
        throw new IllegalStateException(
            "It was NOT expected to find the RemoteValueWrapperInterceptor registered in the InterceptorChain as indexing was disabled, but it was found");
      }

      ProtobufMetadataManagerImpl protobufMetadataManager =
          (ProtobufMetadataManagerImpl)
              cr.getGlobalComponentRegistry().getComponent(ProtobufMetadataManager.class);
      SerializationContext serCtx = protobufMetadataManager.getSerializationContext();
      cr.registerComponent(new ProtobufMatcher(serCtx), ProtobufMatcher.class);

      if (isCompatMode) {
        SearchIntegrator searchFactory = cr.getComponent(SearchIntegrator.class);
        CompatibilityReflectionMatcher compatibilityReflectionMatcher;
        if (searchFactory == null) {
          compatibilityReflectionMatcher = new CompatibilityReflectionMatcher(serCtx);
        } else {
          compatibilityReflectionMatcher =
              new CompatibilityReflectionMatcher(serCtx, searchFactory);
        }
        cr.registerComponent(compatibilityReflectionMatcher, CompatibilityReflectionMatcher.class);
      }

      AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
      RemoteQueryEngine remoteQueryEngine =
          new RemoteQueryEngine(cache, isIndexed, isCompatMode, serCtx);
      cr.registerComponent(remoteQueryEngine, RemoteQueryEngine.class);
    }
  }
 /** Registers the remote value wrapper interceptor in the cache before it gets started. */
 @Override
 public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) {
   InternalCacheRegistry icr =
       cr.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class);
   if (!icr.isInternalCache(cacheName)) {
     boolean isIndexed = cfg.indexing().index().isEnabled();
     boolean isCompatMode = cfg.compatibility().enabled();
     if (isIndexed && !isCompatMode) {
       log.infof("Registering RemoteValueWrapperInterceptor for cache %s", cacheName);
       createRemoteValueWrapperInterceptor(cr, cfg);
     }
   }
 }
  public static ControlledCommandFactory registerControlledCommandFactory(
      Cache cache, Class<? extends ReplicableCommand> toBlock) {
    ComponentRegistry componentRegistry = cache.getAdvancedCache().getComponentRegistry();
    final ControlledCommandFactory ccf =
        new ControlledCommandFactory(componentRegistry.getCommandsFactory(), toBlock);
    TestingUtil.replaceField(ccf, "commandsFactory", componentRegistry, ComponentRegistry.class);
    componentRegistry.registerComponent(ccf, CommandsFactory.class);

    // hack: re-add the component registry to the GlobalComponentRegistry's "namedComponents" (CHM)
    // in order to correctly publish it for
    // when it will be read by the InboundInvocationHandlder. InboundInvocationHandlder reads the
    // value from the GlobalComponentRegistry.namedComponents before using it
    componentRegistry
        .getGlobalComponentRegistry()
        .registerNamedComponentRegistry(componentRegistry, EmbeddedCacheManager.DEFAULT_CACHE_NAME);
    return ccf;
  }
  @Start(priority = 11) // after Transport
  public void start() {
    SecurityActions.addCacheManagerListener(cache.getCacheManager(), new RankCalculator());

    isClustered =
        SecurityActions.getCacheConfiguration(cache.getAdvancedCache())
            .clustering()
            .cacheMode()
            .isClustered();

    if (isClustered) {
      // Use component registry to avoid keeping an instance ref simply used on start
      ComponentRegistry componentRegistry =
          SecurityActions.getCacheComponentRegistry(cache.getAdvancedCache());
      Transport transport =
          componentRegistry.getGlobalComponentRegistry().getComponent(Transport.class);
      calculateRank(transport.getAddress(), transport.getMembers(), transport.getViewId());
    }
  }
 @Override
 public void executeRuntimeStep(OperationContext context, ModelNode operation)
     throws OperationFailedException {
   final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
   final String cacheContainerName = address.getElement(address.size() - 2).getValue();
   final String cacheName = address.getElement(address.size() - 1).getValue();
   final ServiceController<?> controller =
       context
           .getServiceRegistry(false)
           .getService(CacheServiceName.CACHE.getServiceName(cacheContainerName, cacheName));
   if (controller != null) {
     Cache<?, ?> cache = (Cache<?, ?>) controller.getValue();
     if (cache != null) {
       ComponentRegistry registry = SecurityActions.getComponentRegistry(cache.getAdvancedCache());
       LocalTopologyManagerImpl localTopologyManager =
           (LocalTopologyManagerImpl)
               registry.getGlobalComponentRegistry().getComponent(LocalTopologyManager.class);
       if (localTopologyManager != null) {
         try {
           if (operation.hasDefined(VALUE)) {
             ModelNode newValue = operation.get(VALUE);
             localTopologyManager.setCacheAvailability(
                 cacheName, AvailabilityMode.valueOf(newValue.asString()));
           } else {
             context
                 .getResult()
                 .set(
                     new ModelNode()
                         .set(localTopologyManager.getCacheAvailability(cacheName).toString()));
           }
         } catch (Exception e) {
           throw new OperationFailedException(
               new ModelNode().set(MESSAGES.failedToInvokeOperation(e.getLocalizedMessage())));
         }
       }
     }
   }
   context.stepCompleted();
 }
  private void registerQueryMBeans(AdvancedCache cache, ComponentRegistry cr, String cacheName) {
    Configuration cfg = cache.getCacheConfiguration();
    SearchFactoryIntegrator sf = getSearchFactory(cfg.indexing().properties(), cr);

    // Resolve MBean server instance
    GlobalConfiguration globalCfg = cr.getGlobalComponentRegistry().getGlobalConfiguration();
    mbeanServer = JmxUtil.lookupMBeanServer(globalCfg);

    // Resolve jmx domain to use for query mbeans
    String queryGroupName = getQueryGroupName(cacheName);
    jmxDomain = JmxUtil.buildJmxDomain(globalCfg, mbeanServer, queryGroupName);

    // Register statistics MBean, but only enable if Infinispan config says so
    Statistics stats = sf.getStatistics();
    stats.setStatisticsEnabled(cfg.jmxStatistics().enabled());
    try {
      ObjectName statsObjName =
          new ObjectName(jmxDomain + ":" + queryGroupName + ",component=Statistics");
      JmxUtil.registerMBean(new StatisticsInfo(stats), statsObjName, mbeanServer);
    } catch (Exception e) {
      throw new CacheException("Unable to register query module statistics mbean", e);
    }

    // Register mass indexer MBean, picking metadata from repo
    ManageableComponentMetadata metadata =
        metadataRepo.findComponentMetadata(MassIndexer.class).toManageableComponentMetadata();
    try {
      // TODO: MassIndexer should be some kind of query cache component?
      MapReduceMassIndexer maxIndexer = new MapReduceMassIndexer(cache, sf);
      ResourceDMBean mbean = new ResourceDMBean(maxIndexer, metadata);
      ObjectName massIndexerObjName =
          new ObjectName(
              jmxDomain + ":" + queryGroupName + ",component=" + metadata.getJmxObjectName());
      JmxUtil.registerMBean(mbean, massIndexerObjName, mbeanServer);
    } catch (Exception e) {
      throw new CacheException("Unable to create ", e);
    }
  }
 private SearchFactoryIntegrator getSearchFactory(
     Properties indexingProperties, ComponentRegistry cr) {
   Object component = cr.getComponent(SearchFactoryIntegrator.class);
   SearchFactoryIntegrator searchFactory = null;
   if (component
       instanceof
       SearchFactoryIntegrator) { // could be the placeholder Object REMOVED_REGISTRY_COMPONENT
     searchFactory = (SearchFactoryIntegrator) component;
   }
   // defend against multiple initialization:
   if (searchFactory == null) {
     GlobalComponentRegistry globalComponentRegistry = cr.getGlobalComponentRegistry();
     EmbeddedCacheManager uninitializedCacheManager =
         globalComponentRegistry.getComponent(EmbeddedCacheManager.class);
     indexingProperties = addProgrammaticMappings(indexingProperties, cr);
     // Set up the search factory for Hibernate Search first.
     SearchConfiguration config =
         new SearchableCacheConfiguration(
             new Class[0], indexingProperties, uninitializedCacheManager, cr);
     searchFactory = new SearchFactoryBuilder().configuration(config).buildSearchFactory();
     cr.registerComponent(searchFactory, SearchFactoryIntegrator.class);
   }
   return searchFactory;
 }