View Javadoc
1   package com.atlassian.plugin.web.model;
2   
3   import com.atlassian.plugin.PluginAccessor;
4   import com.atlassian.plugin.web.renderer.RendererException;
5   import com.google.common.base.Preconditions;
6   import org.apache.commons.lang3.StringEscapeUtils;
7   import org.slf4j.Logger;
8   import org.slf4j.LoggerFactory;
9   
10  import java.io.IOException;
11  import java.io.StringWriter;
12  import java.io.Writer;
13  import java.util.Map;
14  
15  /**
16   * This class is used for web panel declaration that do not have a custom
17   * <code>class</code> attribute in their descriptor, but do have a
18   * <code>location</code> attribute in their resource child element, which
19   * points to a template file on the (plugin's) classpath.
20   *
21   * @see com.atlassian.plugin.web.descriptors.DefaultWebPanelModuleDescriptor
22   * @since 2.5.0
23   */
24  public class ResourceTemplateWebPanel extends AbstractWebPanel {
25      private static final Logger logger = LoggerFactory.getLogger(ResourceTemplateWebPanel.class.getName());
26      private String resourceFilename;
27  
28      public ResourceTemplateWebPanel(PluginAccessor pluginAccessor) {
29          super(pluginAccessor);
30      }
31  
32      /**
33       * Specifies the name of the template file that is to be rendered.
34       * This file will be loaded from the (plugin's) classpath.
35       *
36       * @param resourceFilename the name of the template file that is to be rendered.
37       *                         May not be null.
38       */
39      public void setResourceFilename(String resourceFilename) {
40          this.resourceFilename = Preconditions.checkNotNull(resourceFilename, "resourceFilename");
41      }
42  
43      public void writeHtml(Writer writer, Map<String, Object> context) throws IOException {
44          try {
45              getRenderer().render(resourceFilename, plugin, context, writer);
46          } catch (RendererException e) {
47              final String message = String.format("Error rendering WebPanel (%s): %s", resourceFilename, e.getMessage());
48              logger.warn(message, e);
49              writer.write(StringEscapeUtils.escapeHtml4(message));
50          }
51      }
52  
53      public String getHtml(final Map<String, Object> context) {
54          try {
55              final StringWriter sink = new StringWriter();
56              writeHtml(sink, context);
57              return sink.toString();
58          } catch (IOException e) {
59              // Something went very wrong: we couldn't write to a StringWriter!
60              throw new RuntimeException(e);
61          }
62      }
63  }