@Test
 public void testBuildDiffCacheNameTimestampsRegion() {
   final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
   Properties p = createProperties();
   p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "unrecommended-timestamps");
   InfinispanRegionFactory factory = createRegionFactory(p);
   try {
     EmbeddedCacheManager manager = factory.getCacheManager();
     assertFalse(factory.getDefinedConfigurations().contains("timestamp"));
     assertTrue(factory.getDefinedConfigurations().contains("unrecommended-timestamps"));
     assertTrue(
         factory
             .getTypeOverrides()
             .get("timestamps")
             .getCacheName()
             .equals("unrecommended-timestamps"));
     ConfigurationBuilder builder = new ConfigurationBuilder();
     builder.clustering().stateTransfer().fetchInMemoryState(true);
     builder.clustering().cacheMode(CacheMode.REPL_SYNC);
     manager.defineConfiguration("unrecommended-timestamps", builder.build());
     TimestampsRegionImpl region =
         (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p);
     AdvancedCache cache = region.getCache();
     Configuration cacheCfg = cache.getCacheConfiguration();
     assertEquals(EvictionStrategy.NONE, cacheCfg.eviction().strategy());
     assertEquals(CacheMode.REPL_SYNC, cacheCfg.clustering().cacheMode());
     assertFalse(cacheCfg.storeAsBinary().enabled());
     assertFalse(cacheCfg.jmxStatistics().enabled());
   } finally {
     factory.stop();
   }
 }
Beispiel #2
0
  @Override
  public byte[] query(AdvancedCache<byte[], byte[]> cache, byte[] query) {
    try {
      SerializationContext serCtx =
          ProtobufMetadataManagerImpl.getSerializationContextInternal(cache.getCacheManager());
      QueryRequest request =
          ProtobufUtil.fromByteArray(serCtx, query, 0, query.length, QueryRequest.class);

      Configuration cacheConfiguration = SecurityActions.getCacheConfiguration(cache);
      boolean isIndexed = cacheConfiguration.indexing().index().isEnabled();
      boolean isCompatMode = cacheConfiguration.compatibility().enabled();
      SearchManager searchManager =
          isIndexed ? Search.getSearchManager(cache) : null; // this also checks access permissions
      RemoteQueryEngine queryEngine =
          new RemoteQueryEngine(cache, searchManager, isCompatMode, serCtx);

      long startOffset = request.getStartOffset() == null ? -1 : request.getStartOffset();
      int maxResults = request.getMaxResults() == null ? -1 : request.getMaxResults();
      Map<String, Object> namedParameters = getNamedParameters(request);
      Query q =
          queryEngine.buildQuery(
              null, request.getJpqlString(), namedParameters, startOffset, maxResults);

      QueryResponse response = makeResponse(q);
      return ProtobufUtil.toByteArray(serCtx, response);
    } catch (IOException e) {
      throw log.errorExecutingQuery(e);
    }
  }
  public void cleanupTimedOutTransactions() {
    if (trace)
      log.tracef(
          "About to cleanup remote transactions older than %d ms",
          configuration.transaction().completedTxTimeout());
    long beginning = timeService.time();
    long cutoffCreationTime =
        beginning - TimeUnit.MILLISECONDS.toNanos(configuration.transaction().completedTxTimeout());
    List<GlobalTransaction> toKill = new ArrayList<>();

    // Check remote transactions.
    for (Map.Entry<GlobalTransaction, RemoteTransaction> e : remoteTransactions.entrySet()) {
      GlobalTransaction gtx = e.getKey();
      RemoteTransaction remoteTx = e.getValue();
      if (remoteTx != null) {
        if (trace) log.tracef("Checking transaction %s", gtx);
        // Check the time.
        if (remoteTx.getCreationTime() - cutoffCreationTime < 0) {
          long duration =
              timeService.timeDuration(
                  remoteTx.getCreationTime(), beginning, TimeUnit.MILLISECONDS);
          log.remoteTransactionTimeout(gtx, duration);
          toKill.add(gtx);
        }
      }
    }

    // Rollback the orphaned transactions and release any held locks.
    for (GlobalTransaction gtx : toKill) {
      killTransaction(gtx);
    }
  }
  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());
    }
  }
  @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);
  }
 public static void verifyConfiguredAsClustered(final Cache<?, ?> cache) {
   verifyConfiguredAsClustered(cache.getCacheManager());
   final Configuration cacheConfiguration = cache.getCacheConfiguration();
   Assert.assertTrue(
       "This Cache is managed by a clustered CacheManager, but the Cache is having clustering disabled!",
       cacheConfiguration.clustering().cacheMode().isClustered());
 }
Beispiel #7
0
 private void writeTransaction(XMLExtendedStreamWriter writer, Configuration configuration)
     throws XMLStreamException {
   TransactionConfiguration transaction = configuration.transaction();
   AttributeSet attributes = transaction.attributes();
   if (attributes.isModified()) {
     writer.writeStartElement(Element.TRANSACTION);
     TransactionMode mode =
         TransactionMode.fromConfiguration(
             transaction.transactionMode(),
             !transaction.useSynchronization(),
             transaction.recovery().enabled(),
             configuration.invocationBatching().enabled());
     writer.writeAttribute(Attribute.MODE, mode.toString());
     attributes.write(writer);
     if (mode != TransactionMode.NONE) {
       attributes.write(writer, TransactionConfiguration.TRANSACTION_MANAGER_LOOKUP);
     }
     if (transaction.recovery().enabled())
       transaction
           .recovery()
           .attributes()
           .write(
               writer,
               RecoveryConfiguration.RECOVERY_INFO_CACHE_NAME,
               Attribute.RECOVERY_INFO_CACHE_NAME);
     writer.writeEndElement();
   }
 }
 @Test
 public void testBuildEntityRegionPersonPlusEntityOverridesWithoutCfg() {
   final String person = "com.acme.Person";
   Properties p = createProperties();
   // Third option, no cache defined for entity and overrides for generic entity data type and
   // entity itself.
   p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU");
   p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
   p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
   p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
   p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO");
   p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
   p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000");
   InfinispanRegionFactory factory = createRegionFactory(p);
   try {
     factory.getCacheManager();
     assertNotNull(factory.getTypeOverrides().get(person));
     assertFalse(factory.getDefinedConfigurations().contains(person));
     EntityRegionImpl region =
         (EntityRegionImpl) factory.buildEntityRegion(person, p, MUTABLE_NON_VERSIONED);
     assertNotNull(factory.getTypeOverrides().get(person));
     assertTrue(factory.getDefinedConfigurations().contains(person));
     AdvancedCache cache = region.getCache();
     Configuration cacheCfg = cache.getCacheConfiguration();
     assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
     assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
     assertEquals(10000, cacheCfg.eviction().maxEntries());
     assertEquals(60000, cacheCfg.expiration().lifespan());
     assertEquals(30000, cacheCfg.expiration().maxIdle());
   } finally {
     factory.stop();
   }
 }
  private void shutDownGracefully() {
    if (log.isDebugEnabled())
      log.debugf(
          "Wait for on-going transactions to finish for %s.",
          Util.prettyPrintTime(
              configuration.transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS));
    long failTime = currentMillisFromNanotime() + configuration.transaction().cacheStopTimeout();
    boolean txsOnGoing = areTxsOnGoing();
    while (txsOnGoing && currentMillisFromNanotime() < failTime) {
      try {
        Thread.sleep(30);
        txsOnGoing = areTxsOnGoing();
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        if (clustered) {
          log.debugf(
              "Interrupted waiting for on-going transactions to finish. %s local transactions and %s remote transactions",
              localTransactions.size(), remoteTransactions.size());
        } else {
          log.debugf(
              "Interrupted waiting for %s on-going transactions to finish.",
              localTransactions.size());
        }
      }
    }

    if (txsOnGoing) {
      log.unfinishedTransactionsRemain(
          localTransactions == null ? 0 : localTransactions.size(),
          remoteTransactions == null ? 0 : remoteTransactions.size());
    } else {
      log.debug("All transactions terminated");
    }
  }
 /** Registers the Search interceptor in the cache before it gets started */
 @Override
 public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) {
   if (cfg.indexing().enabled()) {
     log.registeringQueryInterceptor();
     SearchFactoryIntegrator searchFactory = getSearchFactory(cfg.indexing().properties(), cr);
     createQueryInterceptorIfNeeded(cr, cfg, searchFactory);
   }
 }
 /** Removes the {@link RemoteTransaction} corresponding to the given tx. */
 public void remoteTransactionCommitted(GlobalTransaction gtx, boolean onePc) {
   boolean optimisticWih1Pc =
       onePc && (configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC);
   if (Configurations.isSecondPhaseAsync(configuration)
       || configuration.transaction().transactionProtocol().isTotalOrder()
       || optimisticWih1Pc) {
     removeRemoteTransaction(gtx);
   }
 }
Beispiel #12
0
  ServiceController<?> installCacheConfigurationService(
      ServiceTarget target,
      String containerName,
      String cacheName,
      String defaultCache,
      ModuleIdentifier moduleId,
      ConfigurationBuilder builder,
      Configuration config,
      List<Dependency<?>> dependencies,
      ServiceVerificationHandler verificationHandler) {

    final InjectedValue<EmbeddedCacheManager> container = new InjectedValue<EmbeddedCacheManager>();
    final CacheConfigurationDependencies cacheConfigurationDependencies =
        new CacheConfigurationDependencies(container);
    final Service<Configuration> service =
        new CacheConfigurationService(cacheName, builder, moduleId, cacheConfigurationDependencies);
    final ServiceBuilder<?> configBuilder =
        target
            .addService(CacheConfigurationService.getServiceName(containerName, cacheName), service)
            .addDependency(
                EmbeddedCacheManagerService.getServiceName(containerName),
                EmbeddedCacheManager.class,
                container)
            .addDependency(
                Services.JBOSS_SERVICE_MODULE_LOADER,
                ModuleLoader.class,
                cacheConfigurationDependencies.getModuleLoaderInjector())
            .setInitialMode(ServiceController.Mode.PASSIVE);
    if (config.invocationBatching().enabled()) {
      cacheConfigurationDependencies
          .getTransactionManagerInjector()
          .inject(BatchModeTransactionManager.getInstance());
    } else if (config.transaction().transactionMode()
        == org.infinispan.transaction.TransactionMode.TRANSACTIONAL) {
      configBuilder.addDependency(
          TxnServices.JBOSS_TXN_TRANSACTION_MANAGER,
          TransactionManager.class,
          cacheConfigurationDependencies.getTransactionManagerInjector());
      if (config.transaction().useSynchronization()) {
        configBuilder.addDependency(
            TxnServices.JBOSS_TXN_SYNCHRONIZATION_REGISTRY,
            TransactionSynchronizationRegistry.class,
            cacheConfigurationDependencies.getTransactionSynchronizationRegistryInjector());
      }
    }

    // add in any additional dependencies resulting from ModelNode parsing
    for (Dependency<?> dependency : dependencies) {
      this.addDependency(configBuilder, dependency);
    }
    // add an alias for the default cache
    if (cacheName.equals(defaultCache)) {
      configBuilder.addAliases(CacheConfigurationService.getServiceName(containerName, null));
    }
    return configBuilder.install();
  }
Beispiel #13
0
 private void writeLocalCache(
     XMLExtendedStreamWriter writer, String name, Configuration configuration)
     throws XMLStreamException {
   writer.writeStartElement(Element.LOCAL_CACHE);
   if (configuration.simpleCache()) {
     configuration.attributes().write(writer, Configuration.SIMPLE_CACHE, Attribute.SIMPLE_CACHE);
   }
   writeCommonCacheAttributesElements(writer, name, configuration);
   writer.writeEndElement();
 }
 private ThreadPoolExecutor createExecutorService() {
   return new ThreadPoolExecutor(
       configuration.conditionalExecutorService().corePoolSize(),
       configuration.conditionalExecutorService().maxPoolSize(),
       configuration.conditionalExecutorService().keepAliveTime(),
       TimeUnit.MILLISECONDS,
       new SynchronousQueue<Runnable>(),
       createThreadFactory(),
       new ThreadPoolExecutor.CallerRunsPolicy());
 }
Beispiel #15
0
 private void writeCacheContainer(XMLExtendedStreamWriter writer, ConfigurationHolder holder)
     throws XMLStreamException {
   writer.writeStartElement(Element.CACHE_CONTAINER);
   GlobalConfiguration globalConfiguration = holder.getGlobalConfiguration();
   writer.writeAttribute(
       Attribute.NAME, globalConfiguration.globalJmxStatistics().cacheManagerName());
   if (globalConfiguration.shutdown().hookBehavior() != ShutdownHookBehavior.DEFAULT) {
     writer.writeAttribute(
         Attribute.SHUTDOWN_HOOK, globalConfiguration.shutdown().hookBehavior().name());
   }
   globalConfiguration
       .globalJmxStatistics()
       .attributes()
       .write(writer, GlobalJmxStatisticsConfiguration.ENABLED, Attribute.STATISTICS);
   if (globalConfiguration.asyncThreadPool().threadPoolFactory() != null) {
     writer.writeAttribute(Attribute.ASYNC_EXECUTOR, "async-pool");
   }
   if (globalConfiguration.expirationThreadPool().threadPoolFactory() != null) {
     writer.writeAttribute(Attribute.EXPIRATION_EXECUTOR, "expiration-pool");
   }
   if (globalConfiguration.listenerThreadPool().threadPoolFactory() != null) {
     writer.writeAttribute(Attribute.LISTENER_EXECUTOR, "listener-pool");
   }
   if (globalConfiguration.persistenceThreadPool().threadPoolFactory() != null) {
     writer.writeAttribute(Attribute.PERSISTENCE_EXECUTOR, "persistence-pool");
   }
   if (globalConfiguration.stateTransferThreadPool().threadPoolFactory() != null) {
     writer.writeAttribute(Attribute.STATE_TRANSFER_EXECUTOR, "state-transfer-pool");
   }
   writeTransport(writer, globalConfiguration);
   writeSerialization(writer, globalConfiguration);
   writeJMX(writer, globalConfiguration);
   for (Entry<String, Configuration> configuration : holder.getConfigurations().entrySet()) {
     Configuration config = configuration.getValue();
     switch (config.clustering().cacheMode()) {
       case LOCAL:
         writeLocalCache(writer, configuration.getKey(), config);
         break;
       case DIST_ASYNC:
       case DIST_SYNC:
         writeDistributedCache(writer, configuration.getKey(), config);
         break;
       case INVALIDATION_ASYNC:
       case INVALIDATION_SYNC:
         writeInvalidationCache(writer, configuration.getKey(), config);
         break;
       case REPL_ASYNC:
       case REPL_SYNC:
         writeReplicatedCache(writer, configuration.getKey(), config);
         break;
       default:
         break;
     }
   }
 }
 @Test
 public void testClearStores() {
   Configuration c =
       new ConfigurationBuilder()
           .persistence()
           .addStore(DummyInMemoryStoreConfigurationBuilder.class)
           .persistence()
           .clearStores()
           .build();
   assertEquals(c.persistence().stores().size(), 0);
 }
 public void testNoRecovery() {
   Configuration noRecovery = cacheManager.getCache("noRecovery").getCacheConfiguration();
   assertFalse(
       noRecovery.transaction().recovery().enabled(), "Recovery is supposed to be disabled");
   assertNull(
       rm(cacheManager.getCache("noRecovery")),
       "RecoveryManager should be null when recovery is disabled");
   assertEquals(
       noRecovery.transaction().recovery().recoveryInfoCacheName(),
       "someName",
       "Wrong recovery cache name.");
 }
 @Test
 public void testDistSyncAutoCommit() {
   Configuration configuration =
       new ConfigurationBuilder()
           .clustering()
           .cacheMode(CacheMode.DIST_SYNC)
           .transaction()
           .autoCommit(true)
           .build();
   Assert.assertTrue(configuration.transaction().autoCommit());
   Assert.assertEquals(configuration.clustering().cacheMode(), CacheMode.DIST_SYNC);
 }
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void numVirtualNodes() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.clustering().cacheMode(CacheMode.DIST_SYNC);
    cb.clustering().hash().numSegments(5);

    Configuration c = cb.build();
    Assert.assertEquals(5, c.clustering().hash().numSegments());

    // negative test
    cb.clustering().hash().numSegments(0);
  }
  private void removeRemoteIndexingInterceptorFromConfig(Configuration cfg) {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    CustomInterceptorsConfigurationBuilder customInterceptorsBuilder = builder.customInterceptors();

    for (InterceptorConfiguration interceptorConfig : cfg.customInterceptors().interceptors()) {
      if (!(interceptorConfig.asyncInterceptor() instanceof RemoteValueWrapperInterceptor)) {
        customInterceptorsBuilder.addInterceptor().read(interceptorConfig);
      }
    }

    cfg.customInterceptors().interceptors(builder.build().customInterceptors().interceptors());
  }
 /** 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);
     }
   }
 }
  private void removeQueryInterceptorFromConfiguration(Configuration cfg) {

    ConfigurationBuilder builder = new ConfigurationBuilder();
    CustomInterceptorsConfigurationBuilder customInterceptorsBuilder = builder.customInterceptors();

    for (InterceptorConfiguration interceptorConfig : cfg.customInterceptors().interceptors()) {
      if (!(interceptorConfig.interceptor() instanceof QueryInterceptor)) {
        customInterceptorsBuilder.addInterceptor().read(interceptorConfig);
      }
    }

    cfg.customInterceptors().interceptors(builder.build().customInterceptors().interceptors());
  }
 @Test
 public void testReplAsyncWithQueue() {
   Configuration configuration =
       new ConfigurationBuilder()
           .clustering()
           .cacheMode(CacheMode.REPL_ASYNC)
           .async()
           .useReplQueue(true)
           .replQueueInterval(1222)
           .build();
   Assert.assertTrue(configuration.clustering().async().useReplQueue());
   Assert.assertEquals(configuration.clustering().async().replQueueInterval(), 1222);
 }
  public void testNoSchemaWithStuff() throws IOException {
    String config =
        INFINISPAN_START_TAG_NO_SCHEMA
            + "    <default>\n"
            + "        <locking concurrencyLevel=\"10000\" isolationLevel=\"REPEATABLE_READ\" />\n"
            + "    </default>\n"
            + INFINISPAN_END_TAG;

    InputStream is = new ByteArrayInputStream(config.getBytes());
    EmbeddedCacheManager cm = TestCacheManagerFactory.fromStream(is);

    Configuration cfg = cm.getDefaultCacheConfiguration();
    assert cfg.locking().concurrencyLevel() == 10000;
    assert cfg.locking().isolationLevel() == IsolationLevel.REPEATABLE_READ;
  }
  @Inject
  public void initialize(
      RpcManager rpcManager,
      Configuration configuration,
      InvocationContextFactory icf,
      InterceptorChain invoker,
      CacheNotifier notifier,
      TransactionFactory gtf,
      TransactionCoordinator txCoordinator,
      TransactionSynchronizationRegistry transactionSynchronizationRegistry,
      CommandsFactory commandsFactory,
      ClusteringDependentLogic clusteringDependentLogic,
      Cache cache,
      TimeService timeService,
      CacheManagerNotifier cacheManagerNotifier,
      PartitionHandlingManager partitionHandlingManager) {
    this.rpcManager = rpcManager;
    this.configuration = configuration;
    this.icf = icf;
    this.invoker = invoker;
    this.notifier = notifier;
    this.txFactory = gtf;
    this.txCoordinator = txCoordinator;
    this.transactionSynchronizationRegistry = transactionSynchronizationRegistry;
    this.commandsFactory = commandsFactory;
    this.clusteringLogic = clusteringDependentLogic;
    this.cacheManagerNotifier = cacheManagerNotifier;
    this.cacheName = cache.getName();
    this.timeService = timeService;
    this.partitionHandlingManager = partitionHandlingManager;

    this.clustered = configuration.clustering().cacheMode().isClustered();
  }
  public void cleanupCompletedTransactions() {
    if (!completedTransactions.isEmpty()) {
      try {
        log.tracef(
            "About to cleanup completed transaction. Initial size is %d",
            completedTransactions.size());
        // this iterator is weekly consistent and will never throw ConcurrentModificationException
        Iterator<Map.Entry<GlobalTransaction, Long>> iterator =
            completedTransactions.entrySet().iterator();
        long timeout = configuration.transaction().completedTxTimeout();

        int removedEntries = 0;
        long beginning = timeService.time();
        while (iterator.hasNext()) {
          Map.Entry<GlobalTransaction, Long> e = iterator.next();
          long ageMillis = timeService.timeDuration(e.getValue(), TimeUnit.MILLISECONDS);
          if (ageMillis >= timeout) {
            iterator.remove();
            removedEntries++;
          }
        }
        long duration = timeService.timeDuration(beginning, TimeUnit.MILLISECONDS);

        log.tracef(
            "Finished cleaning up completed transactions. %d transactions were removed, total duration was %d millis, "
                + "current number of completed transactions is %d",
            removedEntries, duration, completedTransactions.size());
      } catch (Exception e) {
        log.errorf(e, "Failed to cleanup completed transactions: %s", e.getMessage());
      }
    }
  }
  @Start(priority = 9) // Start before cache loader manager
  @SuppressWarnings("unused")
  private void start() {
    final int concurrencyLevel = configuration.locking().concurrencyLevel();
    localTransactions =
        CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel);
    globalToLocalTransactions =
        CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel);
    if (configuration.clustering().cacheMode().isClustered()) {
      minTopologyRecalculationLock = new ReentrantLock();
      // Only initialize this if we are clustered.
      remoteTransactions =
          CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel);
      notifier.addListener(this);
      clustered = true;
    }

    totalOrder = configuration.transaction().transactionProtocol().isTotalOrder();
    if (!totalOrder) {
      // Periodically run a task to cleanup the transaction table from completed transactions.
      ThreadFactory tf =
          new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
              String address =
                  rpcManager != null ? rpcManager.getTransport().getAddress().toString() : "local";
              Thread th = new Thread(r, "TxCleanupService," + cacheName + "," + address);
              th.setDaemon(true);
              return th;
            }
          };

      executorService = Executors.newSingleThreadScheduledExecutor(tf);

      long interval = configuration.transaction().reaperWakeUpInterval();
      executorService.scheduleAtFixedRate(
          new Runnable() {
            @Override
            public void run() {
              cleanupCompletedTransactions();
            }
          },
          interval,
          interval,
          TimeUnit.MILLISECONDS);
    }
  }
  @Inject
  public void init(
      StateTransferLock stateTransferLock,
      Configuration configuration,
      CommandsFactory commandFactory,
      StateTransferManager stateTransferManager) {
    this.stateTransferLock = stateTransferLock;
    this.commandFactory = commandFactory;
    this.stateTransferManager = stateTransferManager;

    useVersioning =
        configuration.transaction().transactionMode().isTransactional()
            && configuration.locking().writeSkewCheck()
            && configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC
            && configuration.versioning().enabled();
    transactionDataTimeout = configuration.clustering().sync().replTimeout();
  }
 private QueryInterceptor buildQueryInterceptor(
     Configuration cfg, SearchFactoryIntegrator searchFactory) {
   if (cfg.indexing().indexLocalOnly()) {
     return new LocalQueryInterceptor(searchFactory);
   } else {
     return new QueryInterceptor(searchFactory);
   }
 }
 @Test
 public void testBuildQueryRegion() {
   final String query = "org.hibernate.cache.internal.StandardQueryCache";
   Properties p = createProperties();
   InfinispanRegionFactory factory = createRegionFactory(p);
   try {
     assertTrue(factory.getDefinedConfigurations().contains("local-query"));
     QueryResultsRegionImpl region =
         (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p);
     AdvancedCache cache = region.getCache();
     Configuration cacheCfg = cache.getCacheConfiguration();
     assertEquals(CacheMode.LOCAL, cacheCfg.clustering().cacheMode());
     assertFalse(cacheCfg.jmxStatistics().enabled());
   } finally {
     factory.stop();
   }
 }