View Javadoc

1   package com.atlassian.plugin.webresource.transformer;
2   
3   import static com.atlassian.plugin.webresource.transformer.TransformerUtils.UTF8;
4   import static com.atlassian.plugin.webresource.transformer.TransformerUtils.transformAndStreamResource;
5   
6   import com.atlassian.plugin.servlet.DownloadException;
7   import com.atlassian.plugin.servlet.DownloadableResource;
8   
9   import com.google.common.base.Function;
10  
11  import java.io.OutputStream;
12  import java.nio.charset.Charset;
13  
14  /**
15   * Abstract class that makes it easy to create transforms that go from string to string.  Override
16   * {@link #getEncoding()} to customize the character encoding of the underlying content and transformed content.
17   * <p>
18   * For example, here is a minimal transformer that prepends text to the underlying resource:
19   * <pre>
20   * public class PrefixTransformer implements WebResourceTransformer
21   *   {
22   *       public DownloadableResource transform(Element configElement, ResourceLocation location, String filePath, DownloadableResource nextResource)
23   *       {
24   *           return new CharSequenceDownloadableResource(nextResource)
25   *           {
26   *               protected CharSequence transform(CharSequence originalContent)
27   *               {
28   *                   return "Prefix: "  + originalContent;
29   *               }
30   *           };
31   *       }
32   *    }
33   * </pre>
34   *
35   * @since 2.9.0
36   */
37  public abstract class CharSequenceDownloadableResource extends AbstractTransformedDownloadableResource
38  {
39      protected CharSequenceDownloadableResource(final DownloadableResource originalResource)
40      {
41          super(originalResource);
42      }
43  
44      public void streamResource(final OutputStream out) throws DownloadException
45      {
46          transformAndStreamResource(getOriginalResource(), UTF8, out, new Function<CharSequence, CharSequence>()
47          {
48              public CharSequence apply(final CharSequence originalContent)
49              {
50                  return transform(originalContent);
51              }
52          });
53      }
54  
55      protected Charset encoding()
56      {
57          return UTF8;
58      }
59  
60      /**
61       * Override this method to transform the original content into a new format.
62       *
63       * @param original The content from the original resource.
64       * @return transformed content
65       */
66      protected abstract CharSequence transform(CharSequence original);
67  }