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 org.apache.commons.lang.StringEscapeUtils;
6   import org.slf4j.Logger;
7   import org.slf4j.LoggerFactory;
8   
9   import java.io.IOException;
10  import java.io.StringWriter;
11  import java.io.Writer;
12  import java.util.Map;
13  
14  /**
15   * This class is used for web panel declaration that do not have a custom
16   * <code>class</code> attribute in their descriptor, nor a <code>location</code>
17   * attribute in their resource child element.
18   * <p>
19   * This class reads the web panel's content from the resource element's
20   * content.
21   *
22   * @see com.atlassian.plugin.web.descriptors.DefaultWebPanelModuleDescriptor
23   * @since   2.5.0
24   */
25  public class EmbeddedTemplateWebPanel extends AbstractWebPanel
26  {
27      private String templateBody;
28      private static final Logger logger = LoggerFactory.getLogger(EmbeddedTemplateWebPanel.class.getName());
29  
30      public EmbeddedTemplateWebPanel(PluginAccessor pluginAccessor)
31      {
32          super(pluginAccessor);
33      }
34  
35      /**
36       * @param templateBody  the body of the web panel (may contain any content type such as velocity or just static
37       *  HTML) that was inlined in <code>atlassian-plugin.xml</code>
38       */
39      public void setTemplateBody(String templateBody)
40      {
41          this.templateBody = templateBody;
42      }
43  
44      public void writeHtml(Writer writer, Map<String, Object> context) throws IOException
45      {
46          try
47          {
48              getRenderer().renderFragment(writer, templateBody, plugin, context);
49          }
50          catch (RendererException e)
51          {
52              final String message = String.format("Error rendering WebPanel: %s\n" +
53                      "Template contents: %s", e.getMessage(), templateBody);
54              logger.warn(message, e);
55              writer.write(StringEscapeUtils.escapeHtml(message));
56          }
57      }
58  
59      public String getHtml(final Map<String, Object> context)
60      {
61          try
62          {
63              StringWriter out = new StringWriter();
64              writeHtml(out, context);
65              return out.toString();
66          }
67          catch (IOException e)
68          {
69              // Something went very wrong: we failed to write to a StringWriter
70              throw new RuntimeException(e);
71          }
72      }
73  }