⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pluginmanager.java

📁 jspwiki source code,jspwiki source code
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/*    JSPWiki - a JSP-based WikiWiki clone.    Licensed to the Apache Software Foundation (ASF) under one    or more contributor license agreements.  See the NOTICE file    distributed with this work for additional information    regarding copyright ownership.  The ASF licenses this file    to you under the Apache License, Version 2.0 (the    "License"); you may not use this file except in compliance    with the License.  You may obtain a copy of the License at       http://www.apache.org/licenses/LICENSE-2.0    Unless required by applicable law or agreed to in writing,    software distributed under the License is distributed on an    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY    KIND, either express or implied.  See the License for the    specific language governing permissions and limitations    under the License.   */package com.ecyrd.jspwiki.plugin;import java.io.*;import java.net.URL;import java.text.MessageFormat;import java.util.*;import org.apache.commons.lang.ClassUtils;import org.apache.ecs.xhtml.*;import org.apache.log4j.Logger;import org.apache.oro.text.regex.*;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.input.SAXBuilder;import org.jdom.xpath.XPath;import com.ecyrd.jspwiki.*;import com.ecyrd.jspwiki.modules.ModuleManager;import com.ecyrd.jspwiki.modules.WikiModuleInfo;import com.ecyrd.jspwiki.parser.PluginContent;import com.ecyrd.jspwiki.util.ClassUtil;/** *  Manages plugin classes.  There exists a single instance of PluginManager *  per each instance of WikiEngine, that is, each JSPWiki instance. *  <P> *  A plugin is defined to have three parts: *  <OL> *    <li>The plugin class *    <li>The plugin parameters *    <li>The plugin body *  </ol> * *  For example, in the following line of code: *  <pre> *  [{INSERT com.ecyrd.jspwiki.plugin.FunnyPlugin  foo='bar' *  blob='goo' * *  abcdefghijklmnopqrstuvw *  01234567890}] *  </pre> * *  The plugin class is "com.ecyrd.jspwiki.plugin.FunnyPlugin", the *  parameters are "foo" and "blob" (having values "bar" and "goo", *  respectively), and the plugin body is then *  "abcdefghijklmnopqrstuvw\n01234567890".   The plugin body is *  accessible via a special parameter called "_body". *  <p> *  If the parameter "debug" is set to "true" for the plugin, *  JSPWiki will output debugging information directly to the page if there *  is an exception. *  <P> *  The class name can be shortened, and marked without the package. *  For example, "FunnyPlugin" would be expanded to *  "com.ecyrd.jspwiki.plugin.FunnyPlugin" automatically.  It is also *  possible to define other packages, by setting the *  "jspwiki.plugin.searchPath" property.  See the included *  jspwiki.properties file for examples. *  <P> *  Even though the nominal way of writing the plugin is *  <pre> *  [{INSERT pluginclass WHERE param1=value1...}], *  </pre> *  it is possible to shorten this quite a lot, by skipping the *  INSERT, and WHERE words, and dropping the package name.  For *  example: * *  <pre> *  [{INSERT com.ecyrd.jspwiki.plugin.Counter WHERE name='foo'}] *  </pre> * *  is the same as *  <pre> *  [{Counter name='foo'}] *  </pre> *  <h3>Plugin property files</h3> *  <p> *  Since 2.3.25 you can also define a generic plugin XML properties file per *  each JAR file. *  <pre> *  <modules> *   <plugin class="com.ecyrd.jspwiki.foo.TestPlugin"> *       <author>Janne Jalkanen</author> *       <script>foo.js</script> *       <stylesheet>foo.css</stylesheet> *       <alias>code</alias> *   </plugin> *   <plugin class="com.ecyrd.jspwiki.foo.TestPlugin2"> *       <author>Janne Jalkanen</author> *   </plugin> *   </modules> *  </pre> *  <h3>Plugin lifecycle</h3> * *  <p>Plugin can implement multiple interfaces to let JSPWiki know at which stages they should *  be invoked: *  <ul> *  <li>InitializablePlugin: If your plugin implements this interface, the initialize()-method is *      called once for this class *      before any actual execute() methods are called.  You should use the initialize() for e.g. *      precalculating things.  But notice that this method is really called only once during the *      entire WikiEngine lifetime.  The InitializablePlugin is available from 2.5.30 onwards.</li> *  <li>ParserStagePlugin: If you implement this interface, the executeParse() method is called *      when JSPWiki is forming the DOM tree.  You will receive an incomplete DOM tree, as well *      as the regular parameters.  However, since JSPWiki caches the DOM tree to speed up later *      places, which means that whatever this method returns would be irrelevant.  You can do some DOM *      tree manipulation, though.  The ParserStagePlugin is available from 2.5.30 onwards.</li> *  <li>WikiPlugin: The regular kind of plugin which is executed at every rendering stage.  Each *      new page load is guaranteed to invoke the plugin, unlike with the ParserStagePlugins.</li> *  </ul> * *  @since 1.6.1 */public class PluginManager extends ModuleManager{    private static final String PLUGIN_INSERT_PATTERN = "\\{?(INSERT)?\\s*([\\w\\._]+)[ \\t]*(WHERE)?[ \\t]*";    private static Logger log = Logger.getLogger( PluginManager.class );    /**     *  This is the default package to try in case the instantiation     *  fails.     */    public static final String DEFAULT_PACKAGE = "com.ecyrd.jspwiki.plugin";    private static final String DEFAULT_FORMS_PACKAGE = "com.ecyrd.jspwiki.forms";    /**     *  The property name defining which packages will be searched for properties.     */    public static final String PROP_SEARCHPATH = "jspwiki.plugin.searchPath";    /**     *  The name of the body content.  Current value is "_body".     */    public static final String PARAM_BODY      = "_body";    /**     *  The name of the command line content parameter. The value is "_cmdline".     */    public static final String PARAM_CMDLINE   = "_cmdline";    /**     *  The name of the parameter containing the start and end positions in the     *  read stream of the plugin text (stored as a two-element int[], start     *  and end resp.).     */    public static final String PARAM_BOUNDS    = "_bounds";    /**     *  A special name to be used in case you want to see debug output     */    public static final String PARAM_DEBUG     = "debug";    private ArrayList<String>  m_searchPath = new ArrayList<String>();    private Pattern m_pluginPattern;    private boolean m_pluginsEnabled = true;    /**     *  Keeps a list of all known plugin classes.     */    private Map<String, WikiPluginInfo> m_pluginClassMap = new HashMap<String, WikiPluginInfo>();    /**     *  Create a new PluginManager.     *     *  @param engine WikiEngine which owns this manager.     *  @param props Contents of a "jspwiki.properties" file.     */    public PluginManager( WikiEngine engine, Properties props )    {        super(engine);        String packageNames = props.getProperty( PROP_SEARCHPATH );        if( packageNames != null )        {            StringTokenizer tok = new StringTokenizer( packageNames, "," );            while( tok.hasMoreTokens() )            {                m_searchPath.add( tok.nextToken().trim() );            }        }        registerPlugins();        //        //  The default packages are always added.        //        m_searchPath.add( DEFAULT_PACKAGE );        m_searchPath.add( DEFAULT_FORMS_PACKAGE );        PatternCompiler compiler = new Perl5Compiler();        try        {            m_pluginPattern = compiler.compile( PLUGIN_INSERT_PATTERN );        }        catch( MalformedPatternException e )        {            log.fatal("Internal error: someone messed with pluginmanager patterns.", e );            throw new InternalWikiException( "PluginManager patterns are broken" );        }    }    /**     * Enables or disables plugin execution.     *      * @param enabled True, if plugins should be globally enabled; false, if disabled.     */    public void enablePlugins( boolean enabled )    {        m_pluginsEnabled = enabled;    }    /**     * Returns plugin execution status. If false, plugins are not     * executed when they are encountered on a WikiPage, and an     * empty string is returned in their place.     *      * @return True, if plugins are enabled; false otherwise.     */    public boolean pluginsEnabled()    {        return m_pluginsEnabled;    }    /**     *  Returns true if the link is really command to insert     *  a plugin.     *  <P>     *  Currently we just check if the link starts with "{INSERT",     *  or just plain "{" but not "{$".     *     *  @param link Link text, i.e. the contents of text between [].     *  @return True, if this link seems to be a command to insert a plugin here.     */    public static boolean isPluginLink( String link )    {        return link.startsWith("{INSERT") ||               (link.startsWith("{") && !link.startsWith("{$"));    }    /**     *  Attempts to locate a plugin class from the class path     *  set in the property file.     *     *  @param classname Either a fully fledged class name, or just     *  the name of the file (that is,     *  "com.ecyrd.jspwiki.plugin.Counter" or just plain "Counter").     *     *  @return A found class.     *     *  @throws ClassNotFoundException if no such class exists.     */    private Class findPluginClass( String classname )        throws ClassNotFoundException    {        return ClassUtil.findClass( m_searchPath, classname );    }    /**     *  Outputs a HTML-formatted version of a stack trace.     */    private String stackTrace( Map params, Throwable t )    {        div d = new div();        d.setClass("debug");        d.addElement("Plugin execution failed, stack trace follows:");        StringWriter out = new StringWriter();        t.printStackTrace( new PrintWriter(out) );        d.addElement( new pre( out.toString() ) );        d.addElement( new b( "Parameters to the plugin" ) );        ul list = new ul();        for( Iterator i = params.entrySet().iterator(); i.hasNext(); )        {            Map.Entry e = (Map.Entry) i.next();            String key = (String)e.getKey();            list.addElement(new li( key+"'='"+e.getValue() ) );        }        d.addElement( list );        return d.toString();    }    /**     *  Executes a plugin class in the given context.     *  <P>Used to be private, but is public since 1.9.21.     *     *  @param context The current WikiContext.     *  @param classname The name of the class.  Can also be a     *  shortened version without the package name, since the class name is searched from the     *  package search path.     *     *  @param params A parsed map of key-value pairs.     *     *  @return Whatever the plugin returns.     *     *  @throws PluginException If the plugin execution failed for     *  some reason.     *     *  @since 2.0     */    public String execute( WikiContext context,                           String classname,                           Map params )        throws PluginException    {        if( !m_pluginsEnabled )            return "";        ResourceBundle rb = context.getBundle(WikiPlugin.CORE_PLUGINS_RESOURCEBUNDLE);        Object[] args = { classname };        try        {            WikiPlugin plugin;            boolean debug = TextUtil.isPositive( (String) params.get( PARAM_DEBUG ) );            WikiPluginInfo pluginInfo = m_pluginClassMap.get(classname);            if(pluginInfo == null)            {                pluginInfo = WikiPluginInfo.newInstance(findPluginClass( classname ));                registerPlugin(pluginInfo);            }            if( !checkCompatibility(pluginInfo) )            {                String msg = "Plugin '"+pluginInfo.getName()+"' not compatible with this version of JSPWiki";                log.info(msg);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -