001 package org.shiftone.jrat.inject; 002 003 004 import org.shiftone.jrat.core.JRatException; 005 import org.shiftone.jrat.core.ServiceFactory; 006 import org.shiftone.jrat.core.criteria.MethodCriteria; 007 import org.shiftone.jrat.inject.bytecode.Transformer; 008 import org.shiftone.jrat.inject.process.CompositeFileProcessor; 009 import org.shiftone.jrat.inject.process.FileProcessor; 010 import org.shiftone.jrat.util.Assert; 011 import org.shiftone.jrat.util.io.IOUtil; 012 import org.shiftone.jrat.util.log.Logger; 013 014 import java.io.File; 015 016 017 /** 018 * @author jeff@shiftone.org (Jeff Drost) 019 */ 020 public class Injector { 021 022 private static final Logger LOG = Logger.getLogger(Injector.class); 023 public static final String WORK_FILE_END = "-JRatWorkFile"; 024 private FileProcessor fileProcessor = new CompositeFileProcessor(); 025 private InjectorOptions options = new InjectorOptions(); 026 private ServiceFactory serviceFactory = ServiceFactory.getInstance(); 027 private Transformer transformer = serviceFactory.getTransformer(); 028 029 public void inject(File sourceFile, File targetFile) throws InjectionException { 030 031 String sourceExt = IOUtil.getExtention(sourceFile); 032 String targetExt = IOUtil.getExtention(targetFile); 033 File targetDir = targetFile.getParentFile(); 034 035 Assert.assertSame("file extentions", sourceExt, targetExt); 036 037 // thanks Ilja Pavkovic for finding this bug 038 if (targetDir != null) { 039 040 // if the parent directory doesn't exist, then it must be created 041 // first. 042 if (!targetDir.exists() && !targetDir.mkdirs()) { 043 throw new InjectionException("error creating parent directory of target file : " + targetDir); 044 } 045 } 046 047 fileProcessor.process(transformer, options, sourceFile, targetFile); 048 } 049 050 051 public void inject(String source, String target) throws InjectionException { 052 inject(new File(source), new File(target)); 053 } 054 055 056 public void inject(File file) throws InjectionException { 057 058 if (file.getName().endsWith(Injector.WORK_FILE_END)) { 059 try { 060 IOUtil.delete(file); 061 } 062 catch (JRatException e) { 063 LOG.warn("unable to delete : " + file); 064 } 065 } else { 066 inject(file, file); 067 } 068 } 069 070 071 public void inject(String fileName) throws InjectionException { 072 inject(new File(fileName)); 073 } 074 075 076 // ------------------------------------------------------------------------------ 077 public MethodCriteria getMethodCriteria() { 078 return options.getCriteria(); 079 } 080 081 082 public void setMethodCriteria(MethodCriteria criteria) { 083 options.setCriteria(criteria); 084 } 085 }