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 AbstractStringTransformedDownloadableResource(nextResource)
25 * {
26 * protected String transform(String originalContent)
27 * {
28 * return "Prefix: " + originalContent;
29 * }
30 * };
31 * }
32 * }
33 * </pre>
34 *
35 * @since 2.5.0
36 * @deprecated since 2.9.0 use {@link CharSequenceDownloadableResource} instead
37 */
38 @Deprecated
39 public abstract class AbstractStringTransformedDownloadableResource extends AbstractTransformedDownloadableResource
40 {
41 private final Function<CharSequence, CharSequence> transformer = new Function<CharSequence, CharSequence>()
42 {
43 public CharSequence apply(final CharSequence originalContent)
44 {
45 return transform(originalContent.toString());
46 }
47 };
48
49 public AbstractStringTransformedDownloadableResource(final DownloadableResource originalResource)
50 {
51 super(originalResource);
52 }
53
54 public void streamResource(final OutputStream out) throws DownloadException
55 {
56 transformAndStreamResource(getOriginalResource(), Charset.forName(getEncoding()), out, transformer);
57 }
58
59 /**
60 * @return the encoding used to read the original resource and encode the transformed string
61 */
62 protected String getEncoding()
63 {
64 return UTF8.name();
65 }
66
67 /**
68 * Override this method to transform the original content into a new format.
69 *
70 * @param originalContent The original content from the original downloadable resource.
71 * @return The transformed content you want returned
72 */
73 protected abstract String transform(String originalContent);
74 }