×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Shamir Yona
Added: Sep 12, 2015 9:32 AM
Views: 1897
Tags: no tags
  1. /*
  2.  * An implementation of a Cache.
  3.  * First version -
  4.  * manage lines read from RandomAccessFile, which have key - values.
  5.  * Next changes:
  6.  * 1. Convert to Generics.
  7.  * 2. Use an interface instead ofRandomAccessFile.
  8.  */
  9. package prepare4interview.CacheTest;
  10.  
  11. import java.io.FileNotFoundException;
  12. import java.io.IOException;
  13. import java.io.RandomAccessFile;
  14. import java.util.HashMap;
  15. import java.util.LinkedList;
  16.  
  17. /**
  18.  *
  19.  * @author shay
  20.  */
  21. public class MyCache
  22. {
  23.    
  24.     /**************************************************************/
  25.     /* Constants:                                                 */
  26.     /**************************************************************/
  27.     public static final int DEF_CACHE_SIZE = 6;
  28.    
  29.     /**************************************************************/
  30.     /* Members:                                                   */
  31.     /**************************************************************/
  32.     RandomAccessFile inpFile;
  33.    
  34.     // Cache size:
  35.     int size;
  36.    
  37.     // The Cache's storage"
  38.     HashMap<String, String> cache;
  39.     // Defines the queue of values handled by the cache:
  40.     LinkedList<String> accessList;
  41.  
  42.     /**************************************************************/
  43.     /* Constructors:                                              */
  44.     /**************************************************************/
  45.  
  46.     /**
  47.      * Base Constructor - all parameters:
  48.      * @param inpFile
  49.      * @param size
  50.      */
  51.     public MyCache(RandomAccessFile inpFile, int size)
  52.     {
  53.         this.inpFile = inpFile;
  54.         this.size = size;
  55.        
  56.         this.cache = new HashMap<>(this.size);
  57.         this.accessList = new LinkedList<>();
  58.        
  59.     }
  60.    
  61.     /**
  62.      * OPtional Constructor - only Input File name:
  63.      * @param inpFile
  64.      */
  65.     public MyCache(RandomAccessFile inpFile)
  66.     {
  67.         this(inpFile, MyCache.DEF_CACHE_SIZE);
  68.     }
  69.  
  70.     /**************************************************************/
  71.     /* Class methods:                                             */
  72.     /**************************************************************/
  73.    
  74.     /**
  75.      * Get a value for the input key:
  76.      * @param keyStr
  77.      * @return
  78.      */
  79.     public String getValue(String keyStr)
  80.     {
  81.         String valStr = null;
  82.        
  83.         if (keyStr == null)
  84.             return(null);
  85.        
  86.         // in Cache?
  87.         int elemNr = this.accessList.size();
  88.         if (elemNr > 0 && (valStr = this.cache.get(keyStr)) != null)
  89.         {
  90.             System.out.println("key: " + keyStr + " Found value in cache: " + valStr);
  91.            
  92.             // Reloacte the key at the top of the Cache's Access list:
  93.             int keyIdx = this.accessList.indexOf(keyStr);
  94.             if (keyIdx > 1)
  95.             {
  96.                 this.accessList.remove(keyIdx);
  97.                 this.accessList.addFirst(keyStr);
  98.                 System.out.println("key: " + keyStr + " Moved key to top from: " + keyIdx);
  99.             }
  100.            
  101.            
  102.             return(valStr);
  103.         }
  104.        
  105.         // Not found - read it from file:
  106.         try {
  107.             valStr = getValueFromSrc(keyStr);
  108.         } catch (MyCacheException ex) {
  109.             System.err.println("Search for key: " + keyStr + " failed; exception: " + ex.getMessage());
  110.             return(null);
  111.         }
  112.        
  113.         // If key not in cache and the cache is full -
  114.         // remove the least recently accessed:
  115.         if (elemNr == this.size)
  116.         {
  117.             String firstKey = this.accessList.removeFirst();
  118.             this.cache.remove(firstKey);
  119.         }
  120.         // Add the missing key/value to the cache:
  121.         this.cache.put(keyStr, valStr);
  122.         this.accessList.addLast(keyStr);
  123.         System.out.println("key: " + keyStr + " Added value to cache: " + valStr);
  124.  
  125.         return(valStr);
  126.     }
  127.    
  128.    
  129.     /**************************************************************/
  130.     /* Class Methods, which might be moved to the interface       */
  131.     /**************************************************************/
  132.  
  133.     /**
  134.      * Search for the input key in the file and return its value
  135.      *
  136.      * @param keyStr
  137.      * @return
  138.      * @throws prepare4interview.CacheTest.MyCacheException
  139.      */
  140.     public String getValueFromSrc(String keyStr) throws MyCacheException
  141.     {
  142.         String valStr = null;
  143.         String inpLine;
  144.        
  145.         String keyStrLc = keyStr.toLowerCase();
  146.         try
  147.         {
  148.             inpFile.seek(0L);
  149.             // Scan for the input string - which is the first field
  150.             // in the input line:
  151.          
  152.             while ((inpLine = inpFile.readLine()) != null)
  153.             {
  154.                 if (inpLine.toLowerCase().startsWith(keyStrLc))
  155.                 {
  156.                     valStr = inpLine;
  157.                     System.out.println("getValueFromSrc() - Found value for the key:" + valStr);
  158.                     break;
  159.                 }
  160.             }
  161.            
  162.         } catch (IOException ex) {
  163.             throw new MyCacheException("getValueFromSrc()", ex);
  164.         }
  165.        
  166.         return(valStr);
  167.     }
  168.    
  169.     /***************************************************************/
  170.  
  171.     /**
  172.      *
  173.      * @param args
  174.      */
  175.     public static void main(String[] args)
  176.     {
  177.         RandomAccessFile inpFile = null;
  178.         String valStr;
  179.         if (args.length == 0)
  180.         {
  181.             System.err.println("Usage:" + MyCache.class.getName() + " <inpFileName>");
  182.             System.exit(1);
  183.         }
  184.         String inpFileName = args[0];
  185.         System.out.println("Starting");
  186.        
  187.         try {
  188.             inpFile = new RandomAccessFile(inpFileName, "r");
  189.         } catch (FileNotFoundException ex) {
  190.             System.err.println("Error: input file name: " +  inpFileName + " does not exist!");
  191.             System.exit(2);
  192.         }
  193.        
  194.         MyCache myCache = new MyCache(inpFile);
  195.         valStr = myCache.getValue("bbbb");
  196.         valStr = myCache.getValue("2222");
  197.         valStr = myCache.getValue("aaa");
  198.         valStr = myCache.getValue("bbbb");
  199.         valStr = myCache.getValue("GGGGG");
  200.         valStr = myCache.getValue("aaa");
  201.        
  202.         valStr = myCache.getValue("2222");
  203.         valStr = myCache.getValue("ccccc");
  204.         valStr = myCache.getValue("eeeee");
  205.     }
  206.    
  207. }
  208.