001 package com.croftsoft.core.util.cache; 002 003 import java.io.*; 004 import java.util.*; 005 006 import com.croftsoft.core.util.id.*; 007 008 /********************************************************************* 009 * A Cache implementation that is backed by a memory Map. 010 * 011 * <P> 012 * 013 * The InputStreams are read and stored to the Map as byte arrays. 014 * 015 * @see 016 * Cache 017 * @see 018 * java.util.WeakHashMap 019 * @see 020 * com.orbs.open.a.mpl.util.SoftHashMap 021 * 022 * @version 023 * 1999-04-24 024 * @author 025 * <a href="https://www.croftsoft.com/">David Wallace Croft</a> 026 *********************************************************************/ 027 028 public class MemoryMapCache implements Cache 029 ////////////////////////////////////////////////////////////////////// 030 ////////////////////////////////////////////////////////////////////// 031 { 032 033 private Map map; 034 035 ////////////////////////////////////////////////////////////////////// 036 // Constructor method 037 ////////////////////////////////////////////////////////////////////// 038 039 public MemoryMapCache ( Map map ) 040 ////////////////////////////////////////////////////////////////////// 041 { 042 if ( map == null ) 043 { 044 throw new IllegalArgumentException ( "null map" ); 045 } 046 047 this.map = map; 048 } 049 050 ////////////////////////////////////////////////////////////////////// 051 // Cache interface methods 052 ////////////////////////////////////////////////////////////////////// 053 054 public Id validate ( Id id, ContentAccessor contentAccessor ) 055 throws IOException 056 ////////////////////////////////////////////////////////////////////// 057 { 058 if ( isAvailable ( id ) ) return id; 059 060 InputStream inputStream = contentAccessor.getInputStream ( ); 061 062 if ( inputStream == null ) return null; 063 064 return store ( inputStream ); 065 } 066 067 public Id store ( InputStream in ) throws IOException 068 ////////////////////////////////////////////////////////////////////// 069 { 070 Id id = new IntId ( ); 071 072 map.put ( id, CacheLib.toByteArray ( in ) ); 073 074 return id; 075 } 076 077 public InputStream retrieve ( Id id ) throws IOException 078 ////////////////////////////////////////////////////////////////////// 079 { 080 byte [ ] content = ( byte [ ] ) map.get ( id ); 081 082 if ( content == null ) return null; 083 084 return new ByteArrayInputStream ( content ); 085 } 086 087 public boolean isAvailable ( Id id ) 088 ////////////////////////////////////////////////////////////////////// 089 { 090 return map.containsKey ( id ); 091 } 092 093 ////////////////////////////////////////////////////////////////////// 094 ////////////////////////////////////////////////////////////////////// 095 }