Package org.jboss.ha.ispn

Source Code of org.jboss.ha.ispn.DefaultCacheContainerRegistry$CacheContainerRegistryEntry

/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.ha.ispn;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;

import org.infinispan.config.GlobalConfiguration;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStarted;
import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStopped;
import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent;
import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent;
import org.jboss.ha.ispn.config.CacheContainerRegistryConfiguration;
import org.jboss.ha.ispn.config.CacheContainerRegistryConfigurationEntry;
import org.jboss.ha.ispn.config.CacheContainerRegistryConfigurationSource;
import org.jboss.logging.Logger;
import org.jboss.util.naming.NonSerializableFactory;

/**
* Cache container registry that populates itself using a specified factory from configuration from a specified source.
* All cache containers in the registry are bound to jndi.
* @author Paul Ferraro
*/
public class DefaultCacheContainerRegistry implements CacheContainerRegistry
{
   public static final String DEFAULT_CACHE_MANAGER_NAME = new GlobalConfiguration().getCacheManagerName();
  
   static Logger logger = Logger.getLogger(DefaultCacheContainerRegistry.class);
  
   private static final AtomicReference<CacheContainerRegistry> singleton = new AtomicReference<CacheContainerRegistry>();
   public static CacheContainerRegistry getInstance()
   {
      return singleton.get();
   }
  
   private final CacheContainerFactory factory;
   private final CacheContainerRegistryConfigurationSource source;
   private final ConcurrentMap<String, String> aliases = new ConcurrentHashMap<String, String>();
   private final ConcurrentMap<String, CacheContainerRegistryEntry> containers = new ConcurrentHashMap<String, CacheContainerRegistryEntry>();
  
   private volatile String jndiNamePrefix = null;
  
   private volatile EmbeddedCacheManager defaultContainer;
  
   /**
    * Creates a new cache container registry using the specified factory and source.
    * @param factory used to create cache container instances from configuration
    * @param source source of cache container configurations.
    */
   public DefaultCacheContainerRegistry(CacheContainerFactory factory, CacheContainerRegistryConfigurationSource source)
   {
      this.factory = factory;
      this.source = source;
   }
  
   public String getJndiNamePrefix()
   {
      return this.jndiNamePrefix;
   }
  
   public void setJndiNamePrefix(String jndiNamePrefix)
   {
      this.jndiNamePrefix = jndiNamePrefix;
   }
  
   public void start() throws Exception
   {
      CacheContainerRegistryConfiguration registry = this.source.getRegistryConfiguration();
     
      for (CacheContainerRegistryConfigurationEntry entry: registry.getEntries())
      {
         this.add(entry);
      }

      CacheContainerRegistryConfigurationEntry defaultEntry = registry.getDefaultEntry();
     
      if (defaultEntry == null)
      {
         defaultEntry = registry.getEntries().get(0);
      }
     
      this.defaultContainer = this.containers.get(defaultEntry.getId()).getContainer();
     
      singleton.compareAndSet(null, this);
   }
  
   public void stop() throws Exception
   {
      singleton.set(null);
     
      for (CacheContainerRegistryEntry entry: this.containers.values())
      {
         this.stop(entry);
      }
     
      this.aliases.clear();
      this.containers.clear();
      this.defaultContainer = null;
   }

   /**
    * {@inheritDoc}
    * @see org.jboss.ha.ispn.CacheContainerRegistry#getCacheContainers()
    */
   @Override
   public Set<String> getCacheContainers()
   {
      return Collections.unmodifiableSet(this.containers.keySet());
   }

   /**
    * {@inheritDoc}
    * @see org.jboss.ha.ispn.CacheContainerRegistry#getCacheContainer()
    */
   @Override
   public EmbeddedCacheManager getCacheContainer()
   {
      return this.defaultContainer;
   }

   /**
    * {@inheritDoc}
    * @see org.jboss.ha.ispn.CacheContainerRegistry#getCacheContainer(java.lang.String)
    */
   @Override
   public EmbeddedCacheManager getCacheContainer(String alias)
   {
      CacheContainerRegistryEntry entry = null;
     
      if (alias != null)
      {
         // Resolve alias, if possible
         String id = this.aliases.get(alias);
        
         entry = this.containers.get((id != null) ? id : alias);
      }
     
      // Return default cache manager, if name was not found or if it was null
      return (entry != null) ? entry.getContainer() : this.defaultContainer;
   }
  
   public void add(CacheContainerRegistryConfigurationEntry configEntry) throws NamingException
   {
      String id = configEntry.getId();
      CacheContainerConfiguration config = configEntry.getConfiguration();
      GlobalConfiguration globalConfig = config.getGlobalConfiguration();
     
      // ISPN-754 As of 4.2.0.BETA1, Infinispan uses this to build its JMX object names
      if (globalConfig.getCacheManagerName() == DEFAULT_CACHE_MANAGER_NAME)
      {
         globalConfig.setCacheManagerName(id);
      }
     
      EmbeddedCacheManager container = this.factory.createCacheContainer(config);
      String jndiName = configEntry.getJndiName();
      List<String> aliases = configEntry.getAliases();
     
      String prefix = this.jndiNamePrefix;
      if ((prefix != null) && (jndiName == null))
      {
         jndiName = prefix + "/" + id;
      }
     
      CacheContainerRegistryEntry entry = new CacheContainerRegistryEntry(id, container, jndiName, aliases);
     
      // Store cache containers with jndi name, so they can be unbound during stop()
      CacheContainerRegistryEntry existingEntry = this.containers.putIfAbsent(id, entry);
     
      if (existingEntry != null)
      {
         throw new IllegalArgumentException(id + " cache container is already registered.");
      }
     
      for (String alias: aliases)
      {
         String existingAlias = this.aliases.putIfAbsent(alias, id);
        
         if (existingAlias != null)
         {
            logger.warn("Ignoring alias " + alias + " for " + id + " cache container because it is already assigned to " + existingAlias);
         }
      }
     
      this.start(entry);
   }
  
   public void remove(CacheContainerRegistryConfigurationEntry configEntry)
   {
      CacheContainerRegistryEntry entry = this.containers.remove(configEntry.getId());
     
      if (entry != null)
      {
         for (String alias: entry.getAliases())
         {
            this.aliases.remove(alias);
         }
        
         this.stop(entry);
      }
   }
  
   private void start(CacheContainerRegistryEntry entry)
   {
      EmbeddedCacheManager container = entry.getContainer();
      container.start();
      container.addListener(entry);
     
      String jndiName = entry.getJndiName();
     
      if (jndiName != null)
      {
         try
         {
            logger.info("Binding " + entry.getId() + " cache container to " + jndiName);
            this.bind(jndiName, container);
         }
         catch (NamingException e)
         {
            logger.warn(e.getMessage(), e);
         }
      }
   }
  
   private void stop(CacheContainerRegistryEntry entry)
   {
      String jndiName = entry.getJndiName();
     
      if (jndiName != null)
      {
         try
         {
            logger.info("Unbinding " + entry.getId() + " cache container from " + jndiName);
            this.unbind(jndiName);
         }
         catch (NamingException e)
         {
            logger.warn(e.getMessage(), e);
         }
      }
     
      EmbeddedCacheManager container = entry.getContainer();
      container.removeListener(entry);
      container.stop();
   }
  
   private void bind(String jndiName, Object value) throws NamingException
   {
      Context context = new InitialContext();
      Name name = context.getNameParser("").parse(jndiName);
      int end = name.size();
     
      for (int i = 1; i < end; ++i)
      {
         Name subcontextName = name.getPrefix(i);
        
         try
         {
            context.lookup(subcontextName);
         }
         catch (NameNotFoundException e)
         {
            logger.trace("Creating subcontext " + subcontextName);
            context.createSubcontext(subcontextName);
         }
      }
     
      NonSerializableFactory.rebind(context, jndiName, value);
   }
  
   private void unbind(String name) throws NamingException
   {
      new InitialContext().unbind(name);
      NonSerializableFactory.unbind(name);
   }
  
   @Listener
   public static class CacheContainerRegistryEntry
   {
      private final String id;
      private final List<String> aliases;
      private final String jndiName;
      private final EmbeddedCacheManager container;
     
      public CacheContainerRegistryEntry(String id, EmbeddedCacheManager container, String jndiName, List<String> aliases)
      {
         this.id = id;
         this.container = container;
         this.jndiName = jndiName;
         this.aliases = aliases;
      }
     
      public String getId()
      {
         return this.id;
      }
     
      public EmbeddedCacheManager getContainer()
      {
         return this.container;
      }
     
      public String getJndiName()
      {
         return this.jndiName;
      }
     
      public List<String> getAliases()
      {
         return this.aliases;
      }
     
      @CacheStarted
      public void cacheStarted(CacheStartedEvent event)
      {
         this.log("Started", event.getCacheName());
      }
     
      @CacheStopped
      public void cacheStopped(CacheStoppedEvent event)
      {
         this.log("Stopped", event.getCacheName());
      }
     
      private void log(String event, String cacheName)
      {
         logger.info(String.format("%s \"%s\" cache from \"%s\" container", event, cacheName, this.id));
      }
   }
}
TOP

Related Classes of org.jboss.ha.ispn.DefaultCacheContainerRegistry$CacheContainerRegistryEntry

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.