Skip to content

Instantly share code, notes, and snippets.

@bodewig
Created February 12, 2015 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bodewig/7909d63fc887b908a56a to your computer and use it in GitHub Desktop.
Save bodewig/7909d63fc887b908a56a to your computer and use it in GitHub Desktop.
simple Ant ProjectHelper that reads "buildfile from File"
Created in response to a question on the Ant user list "[Ant]Read buid.xml file in memory" - http://marc.info/?t=142367261300007&r=1&w=2
Run with something like
ANT_OPTS='-Dorg.apache.tools.ant.ProjectHelper=org.example.InMemoryProjectHelper' ant -lib . -f "arbitrary file"
this isn't anything I'd use myself, just proving how it can be done.
package org.example;
import java.io.File;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.net.URL;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.helper.AntXMLContext;
import org.apache.tools.ant.helper.ProjectHelper2;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.JAXPUtils;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
public class InMemoryProjectHelper extends ProjectHelper2 {
@Override
public void parse(Project project, Object source, RootHandler handler) throws BuildException {
if (!(source instanceof File)) {
// invoked to parse Ant's internal antlibs
super.parse(project, source, handler);
} else {
// source is the "real" build file that would need to be decrypted or whatever
// the code below just shows how to use a different stream
InputStream inputStream = null;
try {
inputStream = new StringBufferInputStream("<project><echo>Called!</echo></project>");
InputSource inputSource = new InputSource(inputStream);
XMLReader parser = JAXPUtils.getNamespaceXMLReader();
// this is required for the ProjectHelper2 machinery to work
AntXMLContext context = (AntXMLContext) project.getReference("ant.parsing.context");
context.setBuildFile((File) source);
parser.setContentHandler(handler);
parser.setEntityResolver(handler);
parser.setErrorHandler(handler);
parser.setDTDHandler(handler);
parser.parse(inputSource);
} catch (Exception ex) {
throw new BuildException(ex);
} finally {
FileUtils.close(inputStream);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment