001 /* 002 @license.text@ 003 */ 004 package biz.hammurapi.metrics.persistent; 005 006 import java.sql.SQLException; 007 import java.util.Set; 008 009 import biz.hammurapi.cache.Cache; 010 import biz.hammurapi.cache.Entry; 011 import biz.hammurapi.cache.Producer; 012 import biz.hammurapi.config.ConfigurationException; 013 import biz.hammurapi.sql.SQLProcessor; 014 import biz.hammurapi.sql.SQLRuntimeException; 015 016 017 /** 018 * @author Pavel Vlasov 019 * @revision $Revision$ 020 */ 021 public class PeriodFactory { 022 023 private MetricsEngine engine; 024 private Cache cache; 025 026 public PeriodFactory(SQLProcessor processor) { 027 engine=new MetricsEngine(processor); 028 cache=createCache(); 029 } 030 031 MetricsEngine getEngine() { 032 return engine; 033 } 034 035 /** 036 * Override this method to create caching period factory 037 * @return 038 */ 039 protected Cache createCache() { 040 return null; 041 } 042 043 public Period getPeriod(int id, long from, long to, int slices, boolean shrink) throws SQLException { 044 if (cache==null) { 045 return new Period(this, id, from, to, slices, shrink); 046 } 047 048 return (Period) cache.get(new Period.Key(id, from, to, slices, shrink)); 049 } 050 051 public SyntheticPeriod getRootPeriod(long from, long to, int slices, boolean shrink) throws SQLException { 052 MetricLocator locator=new MetricLocator(engine); 053 return newSyntheticPeriod("Root categories", locator.findRoots(), from, to, slices, shrink); 054 } 055 056 /** 057 * Producer to be used by cache. 058 * @return 059 */ 060 protected Producer getProducer() { 061 return new Producer() { 062 063 public Entry get(Object key) { 064 try { 065 final Period period=new Period(PeriodFactory.this, (Period.Key) key); 066 067 return new Entry() { 068 069 public long getExpirationTime() { 070 return 0; 071 } 072 073 public long getTime() { 074 return 0; 075 } 076 077 public Object get() { 078 return period; 079 } 080 081 }; 082 } catch (SQLException e) { 083 throw new SQLRuntimeException(e); 084 } 085 } 086 087 public void addCache(Cache cache) { 088 // TODO Auto-generated method stub 089 090 } 091 092 public Set keySet() { 093 return null; 094 } 095 096 }; 097 } 098 099 void register(Period period) { 100 if (cache!=null) { 101 cache.put(period.toKey(), period, System.currentTimeMillis(), 0); 102 } 103 } 104 105 public SyntheticPeriod newSyntheticPeriod(String name, int[] ids, long from, long to, int slices, boolean shrink) throws SQLException { 106 return new SyntheticPeriod(this, name, ids, from, to, slices, shrink); 107 } 108 109 /** 110 * Shuts down cache, if any. 111 * 112 */ 113 public void stop() throws ConfigurationException { 114 if (cache!=null) { 115 cache.stop(); 116 } 117 } 118 }