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.lang.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  {
26      private static final Logger logger = LoggerFactory.getLogger(ResourceTemplateWebPanel.class.getName());
27      private String resourceFilename;
28  
29      public ResourceTemplateWebPanel(PluginAccessor pluginAccessor)
30      {
31          super(pluginAccessor);
32      }
33  
34      /**
35       * Specifies the name of the template file that is to be rendered.
36       * This file will be loaded from the (plugin's) classpath.
37       *
38       * @param resourceFilename  the name of the template file that is to be rendered.
39       *  May not be null.
40       */
41      public void setResourceFilename(String resourceFilename)
42      {
43          this.resourceFilename = Preconditions.checkNotNull(resourceFilename, "resourceFilename");
44      }
45  
46      public void writeHtml(Writer writer, Map<String, Object> context) throws IOException
47      {
48          try
49          {
50              getRenderer().render(resourceFilename, plugin, context, writer);
51          }
52          catch (RendererException e)
53          {
54              final String message = String.format("Error rendering WebPanel (%s): %s", resourceFilename, e.getMessage());
55              logger.warn(message, e);
56              writer.write(StringEscapeUtils.escapeHtml(message));
57          }
58      }
59  
60      public String getHtml(final Map<String, Object> context)
61      {
62          try
63          {
64              final StringWriter sink = new StringWriter();
65              writeHtml(sink, context);
66              return sink.toString();
67          }
68          catch (IOException e)
69          {
70              // Something went very wrong: we couldn't write to a StringWriter!
71              throw new RuntimeException(e);
72          }
73      }
74  }