1 package net.simya.ldap.servlet; 2 3 import javax.servlet.http.*; 4 import javax.servlet.*; 5 import java.util.Hashtable ; 6 import java.util.Random ; 7 import java.util.Enumeration ; 8 9 public 10 class LdapGlobalCache 11 extends HttpServlet 12 implements Runnable 13 { 14 private static Hashtable objects = new Hashtable (); 15 16 private boolean isActive = true; 17 18 public void init() 19 { 20 new Thread ( this ).start(); 21 } 22 23 public void doGet( HttpServletRequest req, HttpServletResponse res ) 24 { 25 String id = req.getParameter( "id" ); 26 if ( id == null ) 27 return; 28 if ( id.equals( "MANAGER" ) ) 29 { 30 try 31 { 32 java.io.PrintWriter out = res.getWriter(); 33 out.println( "<html><head><title>LDAP Taglib Info</title></head>" ); 34 out.println( "<body><b>Total object(s) waiting in cache buffer : </b>" ); 35 out.println( objects.size() ); 36 out.println( "</body></html>" ); 37 } catch ( java.io.IOException ex ) 38 { 39 } 40 return; 41 } 42 43 CacheObject cached = (CacheObject) objects.get( id ); 44 45 try 46 { 47 ServletOutputStream out = res.getOutputStream(); 48 res.setContentType( cached.mimeType ); 49 out.write( (byte[]) cached.object ); 50 } catch (java.io.IOException ex) 51 { 52 } 53 finally 54 { 55 synchronized( objects ) 56 { 57 objects.remove( id ); 58 } 59 } 60 } 61 62 public static String addCache( Object object, String mimeType ) 63 { 64 String id = null; 65 do 66 { 67 id = generateRndId(); 68 } 69 while( objects.containsKey( id ) ); 70 synchronized( objects ) 71 { 72 objects.put( id, new CacheObject(object, mimeType) ); 73 } 74 return id; 75 } 76 77 public static String generateRndId() 78 { 79 byte[] b = new byte[ 20 ]; 80 char[] c = new char[ 20 ]; 81 Random r = new Random (); 82 r.nextBytes( b ); 83 for ( int i = 0; i < b.length; i++ ) 84 { 85 c[ i ] = (char) ((b[ i ] & 0xff) % 123); 86 if ( c[ i ] < 65 ) 87 c[ i ] = (char) (c[ i ] % 10 + 48) ; 88 if ( c[ i ] < 97 && c[ i ] > 90 ) 89 c[ i ] = 95; 90 if ( c[ 0 ] < 65 ) 91 c[ 0 ] += 18; 92 } 93 return new String ( c ); 94 } 95 96 public void destroy() 97 { 98 isActive = false; 99 } 100 101 public void run() 102 { 103 long SEEK_PERIOD = 30000; 104 105 while ( isActive ) 106 { 107 try 108 { 109 Thread.sleep( SEEK_PERIOD ); 110 } catch ( InterruptedException ex ) {} 111 synchronized( objects ) 112 { 113 for ( Enumeration e = objects.keys(); e.hasMoreElements(); ) 114 { 115 Object key = e.nextElement(); 116 CacheObject o = (CacheObject) objects.get( key ); 117 if ( o.isExpired() ) 118 objects.remove( key ); 119 } 120 } 121 } 122 } 123 124 } 125 126 class CacheObject 127 { 128 private static final long DELAY = 180000; Object object; 130 String mimeType; 131 long timeStamp = System.currentTimeMillis(); 132 133 CacheObject( Object _object, String _mimeType ) 134 { 135 this.object = _object; 136 this.mimeType = _mimeType; 137 } 138 139 boolean isExpired() 140 { 141 return (System.currentTimeMillis() - timeStamp) > DELAY; 142 } 143 } 144 | Popular Tags |