001 /**
002 * www.jcoverage.com
003 * Copyright (C)2003 jcoverage ltd.
004 *
005 * This file is part of jcoverage.
006 *
007 * jcoverage is free software; you can redistribute it and/or modify
008 * it under the terms of the GNU General Public License as published
009 * by the Free Software Foundation; either version 2 of the License,
010 * or (at your option) any later version.
011 *
012 * jcoverage is distributed in the hope that it will be useful, but
013 * WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * General Public License for more details.
016 *
017 * You should have received a copy of the GNU General Public License
018 * along with jcoverage; if not, write to the Free Software
019 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
020 * USA
021 *
022 */
023 package com.jcoverage.coverage;
024
025 import java.io.File;
026 import java.io.FileInputStream;
027 import java.io.FileNotFoundException;
028 import java.util.Map;
029 import java.util.Timer;
030
031 import org.apache.log4j.Logger;
032
033
034 public class InstrumentationFactory extends InstrumentationPersistence implements Runnable,HasBeenInstrumented {
035
036 static final Logger logger=Logger.getLogger(InstrumentationFactory.class);
037 static final InstrumentationFactory instrumentationFactory=new InstrumentationFactory();
038
039 Timer timer=new Timer(true);
040
041 private InstrumentationFactory() {
042 merge(loadInstrumentation());
043
044 if(logger.isInfoEnabled()) {
045 logger.info("loaded: "+keySet().size()+" items.");
046 }
047
048 if(getInstrumentationInterval()>0) {
049 timer.schedule(new SaveInstrumentationTask(this),getInstrumentationInterval(),getInstrumentationInterval());
050 }
051
052 Runtime.getRuntime().addShutdownHook(new Thread(this));
053 }
054
055 int getInstrumentationInterval() {
056 return Integer.getInteger("com.jcoverage.instrumentation.interval",0).intValue()*1000;
057 }
058
059 public void run() {
060 if(logger.isInfoEnabled()) {
061 logger.info("shutdown hook started");
062 }
063
064 saveInstrumentation();
065
066 if(logger.isInfoEnabled()) {
067 logger.info("saved: "+keySet().size()+" items.");
068 }
069
070 if(logger.isInfoEnabled()) {
071 logger.info("shutdown hook has finished");
072 }
073 }
074
075 public static InstrumentationFactory getInstance() {
076 return instrumentationFactory;
077 }
078
079 public Instrumentation newInstrumentation(Class cl) {
080 if(logger.isDebugEnabled()) {
081 logger.debug("cl: "+cl.getName());
082 }
083
084 return newInstrumentation(cl.getName());
085 }
086
087 public Instrumentation newInstrumentation(String className) {
088 if(logger.isDebugEnabled()) {
089 logger.debug("className: "+className);
090 }
091
092 if(!instrumentation.containsKey(className)) {
093 instrumentation.put(className,new InstrumentationImpl());
094 }
095 return (Instrumentation)instrumentation.get(className);
096 }
097 }