View Javadoc

1   package com.atlassian.plugin.webresource.transformer;
2   
3   import com.atlassian.plugin.servlet.DownloadException;
4   import com.atlassian.plugin.servlet.DownloadableResource;
5   import com.google.common.base.Function;
6   import org.apache.commons.io.IOUtils;
7   import org.apache.commons.io.input.CharSequenceReader;
8   
9   import java.io.IOException;
10  import java.io.OutputStream;
11  import java.io.StringWriter;
12  import java.nio.charset.Charset;
13  
14  /**
15   * Utility class for transforming resources
16   */
17  public class TransformerUtils
18  {
19      public static final Charset UTF8 = Charset.forName("UTF-8");
20  
21      /**
22       * Write apply a given transform a resource and then write the transformed content
23       * to the supplied OutputStream.
24       * Note that the OutputStream will not be closed by this method.
25       * @param originalResource - the resource to transform
26       * @param encoding - the encoding to use for writing
27       * @param out - the output stream
28       * @param transform - a function for transforming the content
29       * @throws DownloadException - thrown if it is not possible to stream the output
30       * @since 2.9.0
31       */
32      public static void transformAndStreamResource(final DownloadableResource originalResource, final Charset encoding, final OutputStream out, final Function<CharSequence, CharSequence> transform) throws DownloadException
33      {
34          try
35          {
36              final StringWriter writer = new StringWriter();
37              final WriterOutputStream output = new WriterOutputStream(writer, encoding);
38              originalResource.streamResource(output);
39              output.flush();
40              IOUtils.copy(new CharSequenceReader(transform.apply(writer.getBuffer().toString())), out, encoding.name());
41          }
42          catch (final IOException e)
43          {
44              throw new DownloadException("Unable to stream to the output", e);
45          }
46      }
47  }