You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by tv...@apache.org on 2020/04/13 11:58:05 UTC

[commons-jcs] 04/06: Move from arrays to collections

This is an automated email from the ASF dual-hosted git repository.

tv pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-jcs.git

commit ff58598ebc8b5eb56e46409718d2e9dac7f4111c
Author: Thomas Vandahl <tv...@apache.org>
AuthorDate: Mon Apr 13 13:56:13 2020 +0200

    Move from arrays to collections
---
 .../org/apache/commons/jcs/admin/JCSAdminBean.java | 113 ++++++++-------------
 .../org/apache/commons/jcs/admin/JCSJMXBean.java   |  15 +--
 .../auxiliary/remote/server/RemoteCacheServer.java |   7 +-
 .../jcs/engine/control/CompositeCacheManager.java  |   9 +-
 .../commons/jcs/admin/AdminBeanUnitTest.java       |  32 +++---
 5 files changed, 74 insertions(+), 102 deletions(-)

diff --git a/commons-jcs-core/src/main/java/org/apache/commons/jcs/admin/JCSAdminBean.java b/commons-jcs-core/src/main/java/org/apache/commons/jcs/admin/JCSAdminBean.java
index 550fd74..42fa3b7 100644
--- a/commons-jcs-core/src/main/java/org/apache/commons/jcs/admin/JCSAdminBean.java
+++ b/commons-jcs-core/src/main/java/org/apache/commons/jcs/admin/JCSAdminBean.java
@@ -1,5 +1,18 @@
 package org.apache.commons.jcs.admin;
 
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.text.DateFormat;
+import java.util.Date;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+
 /*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
@@ -29,15 +42,6 @@ import org.apache.commons.jcs.engine.control.CompositeCache;
 import org.apache.commons.jcs.engine.control.CompositeCacheManager;
 import org.apache.commons.jcs.engine.memory.behavior.IMemoryCache;
 
-import java.io.IOException;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.text.DateFormat;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.LinkedList;
-import java.util.Set;
-
 /**
  * A servlet which provides HTTP access to JCS. Allows a summary of regions to be viewed, and
  * removeAll to be run on individual regions or all regions. Also provides the ability to remove
@@ -80,46 +84,34 @@ public class JCSAdminBean implements JCSJMXBean
      * Builds up info about each element in a region.
      * <p>
      * @param cacheName
-     * @return Array of CacheElementInfo objects
-     * @throws Exception
+     * @return List of CacheElementInfo objects
+     * @throws IOException
      */
     @Override
-    public CacheElementInfo[] buildElementInfo( String cacheName )
-        throws Exception
+    public List<CacheElementInfo> buildElementInfo( String cacheName )
+        throws IOException
     {
-        CompositeCache<Serializable, Serializable> cache = cacheHub.getCache( cacheName );
+        CompositeCache<Object, Object> cache = cacheHub.getCache( cacheName );
 
-        Serializable[] keys = cache.getMemoryCache().getKeySet().toArray(new Serializable[0]);
-
-        // Attempt to sort keys according to their natural ordering. If that
-        // fails, get the key array again and continue unsorted.
-        try
-        {
-            Arrays.sort( keys );
-        }
-        catch ( Exception e )
-        {
-            keys = cache.getMemoryCache().getKeySet().toArray(new Serializable[0]);
-        }
+        // Convert all keys to string, store in a sorted map
+        TreeMap<String, ?> keys = new TreeMap<>(cache.getMemoryCache().getKeySet()
+                .stream()
+                .collect(Collectors.toMap(k -> k.toString(), k -> k)));
 
         LinkedList<CacheElementInfo> records = new LinkedList<>();
 
-        ICacheElement<Serializable, Serializable> element;
-        IElementAttributes attributes;
-        CacheElementInfo elementInfo;
-
         DateFormat format = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT );
 
         long now = System.currentTimeMillis();
 
-        for (Serializable key : keys)
+        for (Map.Entry<String, ?> key : keys.entrySet())
         {
-            element = cache.getMemoryCache().getQuiet( key );
+            ICacheElement<?, ?> element = cache.getMemoryCache().getQuiet( key.getValue() );
 
-            attributes = element.getElementAttributes();
+            IElementAttributes attributes = element.getElementAttributes();
 
-            elementInfo = new CacheElementInfo(
-            		String.valueOf( key ),
+            CacheElementInfo elementInfo = new CacheElementInfo(
+            		key.getKey(),
             		attributes.getIsEternal(),
             		format.format(new Date(attributes.getCreateTime())),
             		attributes.getMaxLife(),
@@ -128,7 +120,7 @@ public class JCSAdminBean implements JCSJMXBean
             records.add( elementInfo );
         }
 
-        return records.toArray(new CacheElementInfo[0]);
+        return records;
     }
 
     /**
@@ -136,27 +128,20 @@ public class JCSAdminBean implements JCSJMXBean
      * <p>
      * TODO we need a most light weight method that does not count bytes. The byte counting can
      *       really swamp a server.
-     * @return list of CacheRegionInfo objects
-     * @throws Exception
+     * @return List of CacheRegionInfo objects
      */
     @Override
-    public CacheRegionInfo[] buildCacheInfo()
-        throws Exception
+    public List<CacheRegionInfo> buildCacheInfo()
     {
-        String[] cacheNames = cacheHub.getCacheNames();
-
-        Arrays.sort( cacheNames );
+        TreeSet<String> cacheNames = new TreeSet<>(cacheHub.getCacheNames());
 
         LinkedList<CacheRegionInfo> cacheInfo = new LinkedList<>();
 
-        CacheRegionInfo regionInfo;
-        CompositeCache<?, ?> cache;
-
-        for ( int i = 0; i < cacheNames.length; i++ )
+        for (String cacheName : cacheNames)
         {
-            cache = cacheHub.getCache( cacheNames[i] );
+            CompositeCache<?, ?> cache = cacheHub.getCache( cacheName );
 
-            regionInfo = new CacheRegionInfo(
+            CacheRegionInfo regionInfo = new CacheRegionInfo(
                     cache.getCacheName(),
                     cache.getSize(),
                     cache.getStatus().toString(),
@@ -170,7 +155,7 @@ public class JCSAdminBean implements JCSJMXBean
             cacheInfo.add( regionInfo );
         }
 
-        return cacheInfo.toArray(new CacheRegionInfo[0]);
+        return cacheInfo;
     }
 
 
@@ -269,37 +254,25 @@ public class JCSAdminBean implements JCSJMXBean
     @Override
     public void clearAllRegions() throws IOException
     {
-        if (RemoteCacheServerFactory.getRemoteCacheServer() == null)
+        RemoteCacheServer<?, ?> remoteCacheServer = RemoteCacheServerFactory.getRemoteCacheServer();
+
+        if (remoteCacheServer == null)
         {
             // Not running in a remote cache server.
             // Remove objects from the cache directly, as no need to broadcast removes to client machines...
-
-            String[] names = cacheHub.getCacheNames();
-
-            for (int i = 0; i < names.length; i++)
+            for (String name : cacheHub.getCacheNames())
             {
-                cacheHub.getCache(names[i]).removeAll();
+                cacheHub.getCache(name).removeAll();
             }
         }
         else
         {
             // Running in a remote cache server.
             // Remove objects via the RemoteCacheServer API, so that removes will be broadcast to client machines...
-            try
-            {
-                String[] cacheNames = cacheHub.getCacheNames();
-
-                // Call remoteCacheServer.removeAll(String) for each cacheName...
-                RemoteCacheServer<?, ?> remoteCacheServer = RemoteCacheServerFactory.getRemoteCacheServer();
-                for (int i = 0; i < cacheNames.length; i++)
-                {
-                    String cacheName = cacheNames[i];
-                    remoteCacheServer.removeAll(cacheName);
-                }
-            }
-            catch (IOException e)
+            // Call remoteCacheServer.removeAll(String) for each cacheName...
+            for (String name : cacheHub.getCacheNames())
             {
-                throw new IllegalStateException("Failed to remove all elements from all cache regions: " + e, e);
+                remoteCacheServer.removeAll(name);
             }
         }
     }
diff --git a/commons-jcs-core/src/main/java/org/apache/commons/jcs/admin/JCSJMXBean.java b/commons-jcs-core/src/main/java/org/apache/commons/jcs/admin/JCSJMXBean.java
index 1cf02d0..41b756a 100644
--- a/commons-jcs-core/src/main/java/org/apache/commons/jcs/admin/JCSJMXBean.java
+++ b/commons-jcs-core/src/main/java/org/apache/commons/jcs/admin/JCSJMXBean.java
@@ -1,5 +1,8 @@
 package org.apache.commons.jcs.admin;
 
+import java.io.IOException;
+import java.util.List;
+
 /*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
@@ -20,7 +23,6 @@ package org.apache.commons.jcs.admin;
  */
 
 import javax.management.MXBean;
-import java.io.IOException;
 
 /**
  * A MXBean to expose the JCS statistics to JMX
@@ -32,20 +34,19 @@ public interface JCSJMXBean
      * Builds up info about each element in a region.
      * <p>
      * @param cacheName
-     * @return Array of CacheElementInfo objects
-     * @throws Exception
+     * @return List of CacheElementInfo objects
+     * @throws IOException
      */
-    CacheElementInfo[] buildElementInfo( String cacheName ) throws Exception;
+    List<CacheElementInfo> buildElementInfo( String cacheName ) throws IOException;
 
     /**
      * Builds up data on every region.
      * <p>
      * TODO we need a most light weight method that does not count bytes. The byte counting can
      *       really swamp a server.
-     * @return Array of CacheRegionInfo objects
-     * @throws Exception
+     * @return List of CacheRegionInfo objects
      */
-    CacheRegionInfo[] buildCacheInfo() throws Exception;
+    List<CacheRegionInfo> buildCacheInfo();
 
     /**
      * Tries to estimate how much data is in a region. This is expensive. If there are any non serializable objects in
diff --git a/commons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/remote/server/RemoteCacheServer.java b/commons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/remote/server/RemoteCacheServer.java
index 4d5f3db..05d271b 100644
--- a/commons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/remote/server/RemoteCacheServer.java
+++ b/commons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/remote/server/RemoteCacheServer.java
@@ -164,13 +164,10 @@ public class RemoteCacheServer<K, V>
 
         // cacheManager would have created a number of ICache objects.
         // Use these objects to set up the cacheListenersMap.
-        String[] list = cacheManager.getCacheNames();
-        for ( int i = 0; i < list.length; i++ )
-        {
-            String name = list[i];
+        cacheManager.getCacheNames().forEach(name -> {
             CompositeCache<K, V> cache = cacheManager.getCache( name );
             cacheListenersMap.put( name, new CacheListeners<>( cache ) );
-        }
+        });
     }
 
     /**
diff --git a/commons-jcs-core/src/main/java/org/apache/commons/jcs/engine/control/CompositeCacheManager.java b/commons-jcs-core/src/main/java/org/apache/commons/jcs/engine/control/CompositeCacheManager.java
index d735a47..85712ff 100644
--- a/commons-jcs-core/src/main/java/org/apache/commons/jcs/engine/control/CompositeCacheManager.java
+++ b/commons-jcs-core/src/main/java/org/apache/commons/jcs/engine/control/CompositeCacheManager.java
@@ -26,6 +26,7 @@ import java.security.AccessControlException;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Properties;
+import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.Executors;
@@ -628,7 +629,7 @@ public class CompositeCacheManager
             }
 
             // do the traditional shutdown of the regions.
-            Arrays.stream(getCacheNames()).forEach(this::freeCache);
+            getCacheNames().forEach(this::freeCache);
 
             // shut down factories
             auxiliaryFactoryRegistry.values().forEach(AuxiliaryCacheFactory::dispose);
@@ -688,11 +689,11 @@ public class CompositeCacheManager
 
     /**
      * Returns a list of the current cache names.
-     * @return String[]
+     * @return Set<String>
      */
-    public String[] getCacheNames()
+    public Set<String> getCacheNames()
     {
-        return caches.keySet().toArray(new String[caches.size()]);
+        return caches.keySet();
     }
 
     /**
diff --git a/commons-jcs-core/src/test/java/org/apache/commons/jcs/admin/AdminBeanUnitTest.java b/commons-jcs-core/src/test/java/org/apache/commons/jcs/admin/AdminBeanUnitTest.java
index 7c84a23..38a75ff 100644
--- a/commons-jcs-core/src/test/java/org/apache/commons/jcs/admin/AdminBeanUnitTest.java
+++ b/commons-jcs-core/src/test/java/org/apache/commons/jcs/admin/AdminBeanUnitTest.java
@@ -1,5 +1,10 @@
 package org.apache.commons.jcs.admin;
 
+import java.util.List;
+
+import org.apache.commons.jcs.JCS;
+import org.apache.commons.jcs.access.CacheAccess;
+
 /*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
@@ -20,8 +25,6 @@ package org.apache.commons.jcs.admin;
  */
 
 import junit.framework.TestCase;
-import org.apache.commons.jcs.JCS;
-import org.apache.commons.jcs.access.CacheAccess;
 
 /**
  * Test the admin bean that is used by the JCSAdmin.jsp
@@ -49,7 +52,7 @@ public class AdminBeanUnitTest
 
         JCSAdminBean admin = new JCSAdminBean();
 
-        CacheRegionInfo[] regions = admin.buildCacheInfo();
+        List<CacheRegionInfo> regions = admin.buildCacheInfo();
 
         boolean foundRegion = false;
 
@@ -88,11 +91,10 @@ public class AdminBeanUnitTest
 
         JCSAdminBean admin = new JCSAdminBean();
 
-        CacheElementInfo[] elements = admin.buildElementInfo( regionName );
-
-        assertEquals( "Wrong number of elements in the region.", 1, elements.length );
+        List<CacheElementInfo> elements = admin.buildElementInfo( regionName );
+        assertEquals( "Wrong number of elements in the region.", 1, elements.size() );
 
-        CacheElementInfo elementInfo = elements[0];
+        CacheElementInfo elementInfo = elements.get(0);
         assertEquals( "Wrong key." + elementInfo, key, elementInfo.getKey() );
     }
 
@@ -116,18 +118,16 @@ public class AdminBeanUnitTest
         String key = "myKey";
         cache.put( key, "value" );
 
-        CacheElementInfo[] elements = admin.buildElementInfo( regionName );
-
-        assertEquals( "Wrong number of elements in the region.", 1, elements.length );
-
-        CacheElementInfo elementInfo = elements[0];
+        List<CacheElementInfo> elements = admin.buildElementInfo( regionName );
+        assertEquals( "Wrong number of elements in the region.", 1, elements.size() );
 
+        CacheElementInfo elementInfo = elements.get(0);
         assertEquals( "Wrong key.", key, elementInfo.getKey() );
 
         admin.removeItem( regionName, key );
 
-        CacheElementInfo[] elements2 = admin.buildElementInfo( regionName );
-        assertEquals( "Wrong number of elements in the region after remove.", 0, elements2.length );
+        List<CacheElementInfo> elements2 = admin.buildElementInfo( regionName );
+        assertEquals( "Wrong number of elements in the region after remove.", 0, elements2.size() );
     }
 
     /**
@@ -148,7 +148,7 @@ public class AdminBeanUnitTest
 
         admin.clearAllRegions();
 
-        CacheElementInfo[] elements2 = admin.buildElementInfo( regionName );
-        assertEquals( "Wrong number of elements in the region after remove.", 0, elements2.length );
+        List<CacheElementInfo> elements2 = admin.buildElementInfo( regionName );
+        assertEquals( "Wrong number of elements in the region after remove.", 0, elements2.size() );
     }
 }