@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);
  }
 private void replaceLockManager(ComponentRegistry componentRegistry) {
   LockManager oldLockManager = componentRegistry.getComponent(LockManager.class);
   LockManager newLockManager =
       new ExtendedStatisticLockManager(oldLockManager, cacheStatisticManager, timeService);
   log.replaceComponent("LockManager", oldLockManager, newLockManager);
   componentRegistry.registerComponent(newLockManager, LockManager.class);
 }
  private void createRemoteValueWrapperInterceptor(ComponentRegistry cr, Configuration cfg) {
    RemoteValueWrapperInterceptor wrapperInterceptor =
        cr.getComponent(RemoteValueWrapperInterceptor.class);
    if (wrapperInterceptor == null) {
      wrapperInterceptor = new RemoteValueWrapperInterceptor();

      // Interceptor registration not needed, core configuration handling
      // already does it for all custom interceptors - UNLESS the InterceptorChain already exists in
      // the component registry!
      AsyncInterceptorChain ic = cr.getComponent(AsyncInterceptorChain.class);

      ConfigurationBuilder builder = new ConfigurationBuilder().read(cfg);
      InterceptorConfigurationBuilder interceptorBuilder =
          builder.customInterceptors().addInterceptor();
      interceptorBuilder.interceptor(wrapperInterceptor);

      if (cfg.invocationBatching().enabled()) {
        if (ic != null) ic.addInterceptorAfter(wrapperInterceptor, BatchingInterceptor.class);
        interceptorBuilder.after(BatchingInterceptor.class);
      } else {
        if (ic != null)
          ic.addInterceptorAfter(wrapperInterceptor, InvocationContextInterceptor.class);
        interceptorBuilder.after(InvocationContextInterceptor.class);
      }
      if (ic != null) {
        cr.registerComponent(wrapperInterceptor, RemoteValueWrapperInterceptor.class);
      }
      cfg.customInterceptors().interceptors(builder.build().customInterceptors().interceptors());
    }
  }
 /**
  * Replaces a component in a running cache
  *
  * @param cache cache in which to replace component
  * @param componentType component type of which to replace
  * @param replacementComponent new instance
  * @param rewire if true, ComponentRegistry.rewire() is called after replacing.
  * @return the original component that was replaced
  */
 public static <T> T replaceComponent(
     Cache<?, ?> cache, Class<T> componentType, T replacementComponent, boolean rewire) {
   ComponentRegistry cr = extractComponentRegistry(cache);
   T old = cr.getComponent(componentType);
   cr.registerComponent(replacementComponent, componentType);
   if (rewire) cr.rewire();
   return old;
 }
  @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);
    }
  }
 private void replaceRpcManager(ComponentRegistry componentRegistry) {
   RpcManager oldRpcManager = componentRegistry.getComponent(RpcManager.class);
   if (oldRpcManager == null) {
     // local mode
     return;
   }
   RpcManager newRpcManager =
       new ExtendedStatisticRpcManager(oldRpcManager, cacheStatisticManager, timeService);
   log.replaceComponent("RpcManager", oldRpcManager, newRpcManager);
   componentRegistry.registerComponent(newRpcManager, RpcManager.class);
   this.rpcManager = newRpcManager;
 }
  @Override
  protected void start() {
    super.start();
    log.startStreamSummaryInterceptor();
    streamSummaryContainer = StreamSummaryContainer.getOrCreateStreamLibContainer(cache);
    streamSummaryContainer.setEnabled(true);
    distributionManager = cache.getAdvancedCache().getDistributionManager();

    ComponentRegistry componentRegistry = cache.getAdvancedCache().getComponentRegistry();
    LockManager oldLockManager = componentRegistry.getComponent(LockManager.class);
    LockManager newLockManager = new TopKeyLockManager(oldLockManager, streamSummaryContainer);
    log.replaceComponent("LockManager", oldLockManager, newLockManager);
    componentRegistry.registerComponent(newLockManager, LockManager.class);
    componentRegistry.rewire();
  }
  private void createQueryInterceptorIfNeeded(
      ComponentRegistry cr, Configuration cfg, SearchFactoryIntegrator searchFactory) {
    QueryInterceptor queryInterceptor = cr.getComponent(QueryInterceptor.class);
    if (queryInterceptor == null) {
      queryInterceptor = buildQueryInterceptor(cfg, searchFactory);

      // Interceptor registration not needed, core configuration handling
      // already does it for all custom interceptors - UNLESS the InterceptorChain already exists in
      // the component registry!
      InterceptorChain ic = cr.getComponent(InterceptorChain.class);

      ConfigurationBuilder builder = new ConfigurationBuilder().read(cfg);
      InterceptorConfigurationBuilder interceptorBuilder =
          builder.customInterceptors().addInterceptor();
      interceptorBuilder.interceptor(queryInterceptor);

      if (!cfg.transaction().transactionMode().isTransactional()) {
        if (ic != null)
          ic.addInterceptorAfter(queryInterceptor, NonTransactionalLockingInterceptor.class);
        interceptorBuilder.after(NonTransactionalLockingInterceptor.class);
      } else if (cfg.transaction().lockingMode() == LockingMode.OPTIMISTIC) {
        if (ic != null)
          ic.addInterceptorAfter(queryInterceptor, OptimisticLockingInterceptor.class);
        interceptorBuilder.after(OptimisticLockingInterceptor.class);
      } else {
        if (ic != null)
          ic.addInterceptorAfter(queryInterceptor, PessimisticLockingInterceptor.class);
        interceptorBuilder.after(PessimisticLockingInterceptor.class);
      }
      if (ic != null) {
        cr.registerComponent(queryInterceptor, QueryInterceptor.class);
        cr.registerComponent(queryInterceptor, queryInterceptor.getClass().getName(), true);
      }
      cfg.customInterceptors().interceptors(builder.build().customInterceptors().interceptors());
    }
  }
  @Override
  public void cacheStopping(ComponentRegistry cr, String cacheName) {
    // TODO move this to cacheStopped event (won't work right now as the ComponentRegistry is half
    // empty at that point: ISPN-1006)
    Object searchFactoryIntegrator = cr.getComponent(SearchFactoryIntegrator.class);
    if (searchFactoryIntegrator != null && searchFactoryIntegrator != REMOVED_REGISTRY_COMPONENT) {
      searchFactoriesToShutdown.put(cacheName, (SearchFactoryIntegrator) searchFactoryIntegrator);
      // free some memory by de-registering the SearchFactory
      cr.registerComponent(REMOVED_REGISTRY_COMPONENT, SearchFactoryIntegrator.class);
    }

    // Unregister MBeans
    if (mbeanServer != null) {
      String queryMBeanFilter = jmxDomain + ":" + getQueryGroupName(cacheName) + ",*";
      JmxUtil.unregisterMBeans(queryMBeanFilter, mbeanServer);
    }
  }
  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;
  }
 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;
 }