I've tried the Swizzle Stream library to replace tokens in an input stream.
String RESOURCE_PATH = "FakePom.xml";
InputStream pomIS = JarFinderServlet.class.getClassLoader().getResourceAsStream( RESOURCE_PATH );
if( null == pomIS )
throw new MavenhoeException("Can't read fake pom template - getResourceAsStream( RESOURCE_PATH ) == null");
Map map = ArrayUtils.toMap( new String[][]{
{"@GRP@", artifactInfo.getGroup() },
{"@ART@", artifactInfo.getName() },
{"@VER@", artifactInfo.getVersion() },
{"@PACK@", artifactInfo.getPackaging() },
{"@NAME@", artifactInfo.getFileName() },
{"@DESC@", req.getQueryString() },
} );
// This does not replace anything, no idea why. //
ReplaceStringsInp开发者_StackOverflow社区utStream replacingIS = new ReplaceStringsInputStream(pomIS, map);
ReplaceStringInputStream replacingIS2 = new ReplaceStringInputStream(pomIS, "@VER@", "0.0-AAAAA");
ReplaceStringInputStream replacingIS3 = new ReplaceStringInputStream(pomIS, "@", "#");
ServletOutputStream os = resp.getOutputStream();
IOUtils.copy( replacingIS, os );
replacingIS.close();
This did not work. It just does not replace. So I resorted to the "PHP way"...
String pomTemplate = IOUtils.toString(pomIS)
.replace("@GRP@", artifactInfo.getGroup() )
.replace("@ART@", artifactInfo.getName() )
.replace("@VER@", artifactInfo.getVersion() )
.replace("@PACK@", artifactInfo.getPackaging() )
.replace("@NAME@", artifactInfo.getFileName() )
.replace("@DESC@", req.getQueryString() );
ServletOutputStream os = resp.getOutputStream();
IOUtils.copy( new StringInputStream(pomTemplate), os );
os.close();
Works.
What's wrong?
IOUtils.copy calls read(byte[]) method instead of read(), which is overridden by FixedTokenReplacementInputStream, a superclass of ReplaceStringInputStream. You should implement copying on your own, for example, as follows:
try {
int b;
while ((b = pomIS.read()) != -1) {
os.write(b);
}} finally { os.flush();os.close(); }
精彩评论