Replacing strings in a stream using Swizzle Stream

I tried the Swizzle Stream library to replace tokens in the 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. // ReplaceStringsInputStream 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 method" ...

  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?

+4
source share
1 answer

IOUtils.copy calls the read (byte []) method instead of read (), which is overridden by FixedTokenReplacementInputStream, a superclass of ReplaceStringInputStream. You must implement the copy yourself, for example, as follows:

 try { int b; while ((b = pomIS.read()) != -1) { os.write(b); }} finally { os.flush();os.close(); } 
+3
source

Source: https://habr.com/ru/post/1337496/


All Articles