Update of /cvsroot/mockobjects/mockobjects-java/doc/com/mockobjects/doc
In directory usw-pr-cvs1:/tmp/cvs-serv9735/doc/com/mockobjects/doc
Added Files:
SiteTemplate.java
Log Message:
Added SiteTemplate ant task as alternative to
SiteHack
--- NEW FILE: SiteTemplate.java ---
package com.mockobjects.doc;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;
import java.io.*;
import java.text.MessageFormat;
public class SiteTemplate extends MatchingTask {
private File dir;
private File todir;
private File templatefile;
public void setTemplatefile(File aTemplatefile) {
templatefile = aTemplatefile;
}
public void setTodir(File aTodir) {
todir = aTodir;
}
public void setDir(File aDir) {
dir = aDir;
}
/**
* @see org.apache.tools.ant.Task#execute()
*/
public void execute() throws BuildException {
validateAttributes();
log("Template file: " + templatefile.getPath(), Project.MSG_INFO);
createOutputDirectory();
try {
MessageFormat template = new MessageFormat(readFileContent(templatefile));
DirectoryScanner scanner = getDirectoryScanner(dir);
String[] filenames = scanner.getIncludedFiles();
for (int i = 0; i < filenames.length; ++i) {
String filename = filenames[i];
writeToFile(filename, formattedContents(template, filename));
}
} catch (IOException e) {
log("IO Failure " + e.getMessage(), Project.MSG_ERR);
}
}
private String formattedContents(MessageFormat template, String filename) throws IOException {
return template.format(
new Object[] {
readFileContent(new File(dir, filename))});
}
private void createOutputDirectory() {
if (!todir.exists()) {
todir.mkdirs();
}
}
private void validateFile(File file, String propertyName) {
if (file == null) {
throw new BuildException("Missing " + propertyName, location);
}
if (!file.exists()) {
throw new BuildException("Cannot find " + file.getPath(), location);
}
}
private void validateAttributes() throws BuildException {
validateFile(templatefile, "templatefile");
validateFile(dir, "dir");
validateFile(todir, "todir");
}
private final String readFileContent(File inputFile) throws IOException {
FileReader rd = new FileReader(inputFile);
try {
BufferedReader reader = new BufferedReader(rd);
StringBuffer fileContents = new StringBuffer();
String line = reader.readLine();
while (line != null) {
fileContents.append(line);
fileContents.append("\r\n");
line = reader.readLine();
}
return fileContents.toString();
} finally {
rd.close();
}
}
private final void writeToFile(String fileName, String content) throws IOException {
File outputFile = new File(todir, fileName);
log("Writing to " + outputFile.getPath(), Project.MSG_INFO);
FileWriter writer = new FileWriter(outputFile);
try {
writer.write(content);
writer.flush();
} finally {
writer.close();
}
}
}
|