Created
February 12, 2015 05:41
-
-
Save bodewig/7909d63fc887b908a56a to your computer and use it in GitHub Desktop.
simple Ant ProjectHelper that reads "buildfile from File"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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