001package org.javasimon.console; 002 003import java.util.ArrayList; 004import java.util.Collection; 005import java.util.Collections; 006import java.util.List; 007 008import org.javasimon.console.html.HtmlResource; 009import org.javasimon.console.html.HtmlResourceType; 010import org.javasimon.console.json.ObjectJS; 011import org.javasimon.console.text.Stringifier; 012import org.javasimon.console.text.StringifierFactory; 013 014/** 015 * Base class for plugins. 016 * 017 * @author gquintana 018 */ 019public abstract class SimonConsolePlugin { 020 021 /** Plugin Id. */ 022 private String id; 023 024 /** Label, title short description. */ 025 private String label; 026 027 /** JavaScript and CSS resources used by this plugin */ 028 private List<HtmlResource> resources = new ArrayList<>(); 029 030 /** Default constructor. */ 031 protected SimonConsolePlugin(String id, String label) { 032 this.id = id; 033 this.label = label; 034 } 035 036 public String getId() { 037 return id; 038 } 039 040 public String getLabel() { 041 return label; 042 } 043 044 public Collection<ActionBinding> getActionBindings() { 045 return Collections.emptyList(); 046 } 047 048 /** 049 * Add a resource to this plugin. 050 * 051 * @param path Resource path 052 * @param type Resource type 053 */ 054 public final void addResource(String path, HtmlResourceType type) { 055 resources.add(new HtmlResource(path, type)); 056 } 057 058 /** Get resources used by this plugin. */ 059 public final List<HtmlResource> getResources() { 060 return Collections.unmodifiableList(resources); 061 } 062 063 /** 064 * Gather resources used by all Detail plugins in the plugin manager 065 * 066 * @param context Context containing plugin manager 067 * @return Detail plugins resources. 068 */ 069 public static List<HtmlResource> getResources(ActionContext context, Class<? extends SimonConsolePlugin> pluginType) { 070 List<HtmlResource> resources = new ArrayList<>(); 071 for (SimonConsolePlugin plugin : context.getPluginManager().getPluginsByType(pluginType)) { 072 resources.addAll(plugin.getResources()); 073 } 074 return resources; 075 } 076 077 /** 078 * Serialize plugin data into a JSON object 079 * 080 * @param jsonStringifierFactory Stringifier factory 081 * @return JSON object representing plugin 082 */ 083 public final ObjectJS toJson(StringifierFactory jsonStringifierFactory) { 084 final ObjectJS pluginJS = new ObjectJS(); 085 final Stringifier<String> stringStringifier = jsonStringifierFactory.getStringifier(String.class); 086 pluginJS.setSimpleAttribute("id", getId(), stringStringifier); 087 pluginJS.setSimpleAttribute("label", getLabel(), stringStringifier); 088 pluginJS.setAttribute("resources", HtmlResource.toJson( 089 getResources(), 090 jsonStringifierFactory)); 091 return pluginJS; 092 } 093}