001 package org.apache.torque.mojo; 002 003 import java.io.File; 004 import java.io.FileInputStream; 005 import java.io.FileOutputStream; 006 import java.io.IOException; 007 008 import org.apache.maven.plugin.MojoExecutionException; 009 import org.apache.torque.mojo.morph.MorphRequest; 010 import org.apache.torque.mojo.morph.Morpher; 011 import org.codehaus.plexus.util.FileUtils; 012 013 /** 014 * Common logic for morphing one file to another file 015 */ 016 public abstract class AbstractMorphSingleMojo extends BaseMojo { 017 018 /** 019 * The file that will contain the morphed contents 020 */ 021 private File newFile; 022 023 /** 024 * The file containing the contents to be morphed 025 */ 026 private File oldFile; 027 028 /** 029 * Add logic to the basic skip() method for skipping based on a morph being needed 030 */ 031 @Override 032 protected boolean skipMojo() { 033 // We may be skipping based on packaging of type 'pom' 034 if (super.skipMojo()) { 035 return true; 036 } 037 038 // If a morph is needed, we can't skip 039 boolean morphNeeded = isMorphNeeded(); 040 if (morphNeeded) { 041 return false; 042 } else { 043 getLog().info("Skipping morph. Nothing has changed"); 044 return true; 045 } 046 } 047 048 protected boolean isMorphNeeded() { 049 // The file they asked to morph does not exist 050 if (!getOldFile().exists()) { 051 getLog().debug("file:" + getOldFile().getAbsolutePath() + " does not exist"); 052 return false; 053 } 054 055 // The new file does not exist, we need to morph 056 if (!getNewFile().exists()) { 057 return true; 058 } 059 060 // Extract the last modified timestamps 061 long oldLastModified = getOldFile().lastModified(); 062 long newLastModified = getNewFile().lastModified(); 063 064 // If old file has been modified since the new file was last modified, 065 // we need to morph 066 return oldLastModified > newLastModified; 067 } 068 069 protected abstract Morpher getMorpher(MorphRequest request, String artifactId); 070 071 @Override 072 protected void executeMojo() throws MojoExecutionException { 073 try { 074 getLog().info("From: " + oldFile.getAbsolutePath()); 075 getLog().info(" To: " + newFile.getAbsolutePath()); 076 FileUtils.forceMkdir(new File(FileUtils.getPath(newFile.getAbsolutePath()))); 077 MorphRequest request = new MorphRequest(oldFile.getName(), new FileInputStream(oldFile), 078 new FileOutputStream(newFile)); 079 request.setEncoding(getEncoding()); 080 Morpher morpher = getMorpher(request, getProject().getArtifactId()); 081 morpher.executeMorph(); 082 } catch (IOException e) { 083 throw new MojoExecutionException("Unexpected error while attempting to morph " + oldFile.getAbsolutePath(), 084 e); 085 } 086 } 087 088 public File getNewFile() { 089 return newFile; 090 } 091 092 public void setNewFile(final File newFile) { 093 this.newFile = newFile; 094 } 095 096 public File getOldFile() { 097 return oldFile; 098 } 099 100 public void setOldFile(final File oldFile) { 101 this.oldFile = oldFile; 102 } 103 }