/*
 * JBoss, Home of Professional Open Source
 * Copyright ${year}, Red Hat Middleware LLC, and individual contributors
 * by the @authors tag. See the copyright.txt 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.cache.search;

import org.jboss.cache.Cache;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;
import java.util.ArrayList;

/**
 * Class that is used to load objects from a list of CacheEntityId ids.
 * <p/>
 * @author Navin Surtani (<a href="mailto:nsurtani@redhat.com">nsurtani@redhat.com</a>)
 */
public class CacheEntityLoader
{
   Cache cache;
   private static final Log log = LogFactory.getLog(CacheEntityLoader.class);

   public CacheEntityLoader(Cache cache)
   {
      this.cache = cache;
   }

   /**
    * Takes a list of entity ids and gets them from the cache.
    * @param ids list of cache entity IDs.  Cannot be null.
    * @return List of objects loaded from the cache.  The list returned will be exactly the same size as the ids list passed in.
    * @throws NullPointerException if ids is null.
    */
   public List<Object> load(List<CacheEntityId> ids)
   {
      if (ids == null) throw new NullPointerException("ids are null");
      List<Object> retVal = new ArrayList<Object>(ids.size());

      for (CacheEntityId id: ids)
      {
         retVal.add( cache.get(id.getFqn(), id.getKey()) );
         if(log.isTraceEnabled()) log.trace("Created list of return values. Size is  " + retVal.size() );         
      }
      return retVal;
   }

   /**
    * Takes a list of entity ids and gets them from the cache.
    * @param id cache entity id to look up in the cache.
    * @return the object from the cache, or null if one cannot be found.
    * @throws NullPointerException if ids is null.
    */
   public Object load(CacheEntityId id)
   {
      if (id == null) throw new NullPointerException("id is null");
      return cache.get(id.getFqn(), id.getKey());
   }


}
