001/* 002 Licensed to the Apache Software Foundation (ASF) under one 003 or more contributor license agreements. See the NOTICE file 004 distributed with this work for additional information 005 regarding copyright ownership. The ASF licenses this file 006 to you under the Apache License, Version 2.0 (the 007 "License"); you may not use this file except in compliance 008 with the License. You may obtain a copy of the License at 009 010 http://www.apache.org/licenses/LICENSE-2.0 011 012 Unless required by applicable law or agreed to in writing, 013 software distributed under the License is distributed on an 014 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 KIND, either express or implied. See the License for the 016 specific language governing permissions and limitations 017 under the License. 018 */ 019 020package org.apache.wiki.plugin; 021 022import org.apache.commons.lang3.ClassUtils; 023import org.apache.commons.lang3.StringUtils; 024import org.apache.logging.log4j.LogManager; 025import org.apache.logging.log4j.Logger; 026import org.apache.oro.text.regex.MalformedPatternException; 027import org.apache.oro.text.regex.MatchResult; 028import org.apache.oro.text.regex.Pattern; 029import org.apache.oro.text.regex.PatternCompiler; 030import org.apache.oro.text.regex.PatternMatcher; 031import org.apache.oro.text.regex.Perl5Compiler; 032import org.apache.oro.text.regex.Perl5Matcher; 033import org.apache.wiki.InternalWikiException; 034import org.apache.wiki.ajax.WikiAjaxDispatcherServlet; 035import org.apache.wiki.ajax.WikiAjaxServlet; 036import org.apache.wiki.api.core.Context; 037import org.apache.wiki.api.core.Engine; 038import org.apache.wiki.api.exceptions.PluginException; 039import org.apache.wiki.api.plugin.InitializablePlugin; 040import org.apache.wiki.api.plugin.Plugin; 041import org.apache.wiki.modules.BaseModuleManager; 042import org.apache.wiki.modules.WikiModuleInfo; 043import org.apache.wiki.preferences.Preferences; 044import org.apache.wiki.util.ClassUtil; 045import org.apache.wiki.util.FileUtil; 046import org.apache.wiki.util.TextUtil; 047import org.apache.wiki.util.XHTML; 048import org.apache.wiki.util.XhtmlUtil; 049import org.apache.wiki.util.XmlUtil; 050import org.jdom2.Element; 051 052import jakarta.servlet.http.HttpServlet; 053import java.io.IOException; 054import java.io.PrintWriter; 055import java.io.StreamTokenizer; 056import java.io.StringReader; 057import java.io.StringWriter; 058import java.text.MessageFormat; 059import java.util.ArrayList; 060import java.util.Collection; 061import java.util.HashMap; 062import java.util.HashSet; 063import java.util.List; 064import java.util.Map; 065import java.util.NoSuchElementException; 066import java.util.Properties; 067import java.util.ResourceBundle; 068import java.util.Set; 069import java.util.StringTokenizer; 070 071/** 072 * Manages plugin classes. There exists a single instance of PluginManager 073 * per each instance of Engine, that is, each JSPWiki instance. 074 * <P> 075 * A plugin is defined to have three parts: 076 * <OL> 077 * <li>The plugin class 078 * <li>The plugin parameters 079 * <li>The plugin body 080 * </ol> 081 * 082 * For example, in the following line of code: 083 * <pre> 084 * [{INSERT org.apache.wiki.plugin.FunnyPlugin foo='bar' 085 * blob='goo' 086 * 087 * abcdefghijklmnopqrstuvw 088 * 01234567890}] 089 * </pre> 090 * 091 * The plugin class is "org.apache.wiki.plugin.FunnyPlugin", the 092 * parameters are "foo" and "blob" (having values "bar" and "goo", 093 * respectively), and the plugin body is then 094 * "abcdefghijklmnopqrstuvw\n01234567890". The plugin body is 095 * accessible via a special parameter called "_body". 096 * <p> 097 * If the parameter "debug" is set to "true" for the plugin, 098 * JSPWiki will output debugging information directly to the page if there 099 * is an exception. 100 * <P> 101 * The class name can be shortened, and marked without the package. 102 * For example, "FunnyPlugin" would be expanded to 103 * "org.apache.wiki.plugin.FunnyPlugin" automatically. It is also 104 * possible to define other packages, by setting the 105 * "jspwiki.plugin.searchPath" property. See the included 106 * jspwiki.properties file for examples. 107 * <P> 108 * Even though the nominal way of writing the plugin is 109 * <pre> 110 * [{INSERT pluginclass WHERE param1=value1...}], 111 * </pre> 112 * it is possible to shorten this quite a lot, by skipping the 113 * INSERT, and WHERE words, and dropping the package name. For 114 * example: 115 * 116 * <pre> 117 * [{INSERT org.apache.wiki.plugin.Counter WHERE name='foo'}] 118 * </pre> 119 * 120 * is the same as 121 * <pre> 122 * [{Counter name='foo'}] 123 * </pre> 124 * <h3>Plugin property files</h3> 125 * <p> 126 * Since 2.3.25 you can also define a generic plugin XML properties file per 127 * each JAR file. 128 * <pre> 129 * <modules> 130 * <plugin class="org.apache.wiki.foo.TestPlugin"> 131 * <author>Janne Jalkanen</author> 132 * <script>foo.js</script> 133 * <stylesheet>foo.css</stylesheet> 134 * <alias>code</alias> 135 * </plugin> 136 * <plugin class="org.apache.wiki.foo.TestPlugin2"> 137 * <author>Janne Jalkanen</author> 138 * </plugin> 139 * </modules> 140 * </pre> 141 * <h3>Plugin lifecycle</h3> 142 * 143 * <p>Plugin can implement multiple interfaces to let JSPWiki know at which stages they should 144 * be invoked: 145 * <ul> 146 * <li>InitializablePlugin: If your plugin implements this interface, the initialize()-method is 147 * called once for this class 148 * before any actual execute() methods are called. You should use the initialize() for e.g. 149 * precalculating things. But notice that this method is really called only once during the 150 * entire Engine lifetime. The InitializablePlugin is available from 2.5.30 onwards.</li> 151 * <li>ParserStagePlugin: If you implement this interface, the executeParse() method is called 152 * when JSPWiki is forming the DOM tree. You will receive an incomplete DOM tree, as well 153 * as the regular parameters. However, since JSPWiki caches the DOM tree to speed up later 154 * places, which means that whatever this method returns would be irrelevant. You can do some DOM 155 * tree manipulation, though. The ParserStagePlugin is available from 2.5.30 onwards.</li> 156 * <li>Plugin: The regular kind of plugin which is executed at every rendering stage. Each 157 * new page load is guaranteed to invoke the plugin, unlike with the ParserStagePlugins.</li> 158 * </ul> 159 * 160 * @since 1.6.1 161 */ 162public class DefaultPluginManager extends BaseModuleManager implements PluginManager { 163 164 private static final String PLUGIN_INSERT_PATTERN = "\\{?(INSERT)?\\s*([\\w\\._]+)[ \\t]*(WHERE)?[ \\t]*"; 165 private static final Logger LOG = LogManager.getLogger( DefaultPluginManager.class ); 166 private static final String DEFAULT_FORMS_PACKAGE = "org.apache.wiki.forms"; 167 168 private final ArrayList< String > m_searchPath = new ArrayList<>(); 169 private final ArrayList< String > m_externalJars = new ArrayList<>(); 170 private final Pattern m_pluginPattern; 171 private boolean m_pluginsEnabled = true; 172 173 /** Keeps a list of all known plugin classes. */ 174 private final Map< String, WikiPluginInfo > m_pluginClassMap = new HashMap<>(); 175 176 /** 177 * Create a new PluginManager. 178 * 179 * @param engine Engine which owns this manager. 180 * @param props Contents of a "jspwiki.properties" file. 181 */ 182 public DefaultPluginManager( final Engine engine, final Properties props ) { 183 super( engine ); 184 final String packageNames = props.getProperty( Engine.PROP_SEARCHPATH ); 185 if ( packageNames != null ) { 186 final StringTokenizer tok = new StringTokenizer( packageNames, "," ); 187 while( tok.hasMoreTokens() ) { 188 m_searchPath.add( tok.nextToken().trim() ); 189 } 190 } 191 192 final String externalJars = props.getProperty( PROP_EXTERNALJARS ); 193 if( externalJars != null ) { 194 final StringTokenizer tok = new StringTokenizer( externalJars, "," ); 195 while( tok.hasMoreTokens() ) { 196 m_externalJars.add( tok.nextToken().trim() ); 197 } 198 } 199 200 registerPlugins(); 201 202 // The default packages are always added. 203 m_searchPath.add( DEFAULT_PACKAGE ); 204 m_searchPath.add( DEFAULT_FORMS_PACKAGE ); 205 206 final PatternCompiler compiler = new Perl5Compiler(); 207 try { 208 m_pluginPattern = compiler.compile( PLUGIN_INSERT_PATTERN ); 209 } catch( final MalformedPatternException e ) { 210 LOG.fatal( "Internal error: someone messed with pluginmanager patterns.", e ); 211 throw new InternalWikiException( "PluginManager patterns are broken" , e ); 212 } 213 } 214 215 /** {@inheritDoc} */ 216 @Override 217 public void enablePlugins( final boolean enabled ) { 218 m_pluginsEnabled = enabled; 219 } 220 221 /** {@inheritDoc} */ 222 @Override 223 public boolean pluginsEnabled() { 224 return m_pluginsEnabled; 225 } 226 227 /** {@inheritDoc} */ 228 @Override 229 public Pattern getPluginPattern() { 230 return m_pluginPattern; 231 } 232 233 /** 234 * Attempts to locate a plugin class from the class path set in the property file. 235 * 236 * @param classname Either a fully fledged class name, or just the name of the file (that is, "org.apache.wiki.plugin.Counter" or just plain "Counter"). 237 * @return A found class. 238 * @throws ClassNotFoundException if no such class exists. 239 */ 240 private Class< ? > findPluginClass( final String classname ) throws ClassNotFoundException { 241 final Class< ? > clazz = ClassUtil.findClass( m_searchPath, m_externalJars, classname ); 242 if( !Plugin.class.isAssignableFrom( clazz ) || !isInSearchPath( clazz ) ) { 243 // Reject with the same error as an unknown class, so that page markup cannot be used to 244 // load or instantiate arbitrary classpath classes, nor to probe for their presence. 245 throw new ClassNotFoundException( "Class '" + classname + "' not found in search path!" ); 246 } 247 return clazz; 248 } 249 250 /** 251 * Checks whether the package of the given class is one of the packages on the plugin search path. 252 * 253 * @param clazz The class to check. 254 * @return true, if the class' package is on the plugin search path. 255 */ 256 private boolean isInSearchPath( final Class< ? > clazz ) { 257 final Package pkg = clazz.getPackage(); 258 return pkg != null && m_searchPath.contains( pkg.getName() ); 259 } 260 261 /** Outputs an HTML-formatted version of a stack trace. */ 262 private String stackTrace( final Map<String,String> params, final Throwable t ) { 263 final Element div = XhtmlUtil.element( XHTML.div, "Plugin execution failed, stack trace follows:" ); 264 div.setAttribute( XHTML.ATTR_class, "debug" ); 265 266 final StringWriter out = new StringWriter(); 267 t.printStackTrace( new PrintWriter( out ) ); 268 div.addContent( XhtmlUtil.element( XHTML.pre, out.toString() ) ); 269 div.addContent( XhtmlUtil.element( XHTML.b, "Parameters to the plugin" ) ); 270 271 final Element list = XhtmlUtil.element( XHTML.ul ); 272 for( final Map.Entry< String, String > e : params.entrySet() ) { 273 final String key = e.getKey(); 274 list.addContent( XhtmlUtil.element( XHTML.li, key + "'='" + e.getValue() ) ); 275 } 276 div.addContent( list ); 277 return XhtmlUtil.serialize( div ); 278 } 279 280 /** {@inheritDoc} */ 281 @Override 282 public String execute( final Context context, final String classname, final Map< String, String > params ) throws PluginException { 283 if( !m_pluginsEnabled ) { 284 return ""; 285 } 286 287 final ResourceBundle rb = Preferences.getBundle( context, Plugin.CORE_PLUGINS_RESOURCEBUNDLE ); 288 //see JSPWIKI-75 289 final boolean debug = TextUtil.isPositive( params.get( PARAM_DEBUG ) ) && context.hasAdminPermissions(); 290 291 try { 292 // Create... 293 final Plugin plugin = newWikiPlugin( classname, rb ); 294 if( plugin == null ) { 295 return "Plugin '" + classname + "' not compatible with this version of JSPWiki"; 296 } 297 298 // ...and launch. 299 try { 300 return plugin.execute( context, params ); 301 } catch( final PluginException e ) { 302 LOG.warn(e.getMessage(), e); 303 if( debug ) { 304 return stackTrace( params, e ); 305 } 306 307 // Just pass this exception onward. 308 throw ( PluginException )e.fillInStackTrace(); 309 } catch( final Throwable t ) { 310 311 // But all others get captured here. 312 LOG.warn( "Plugin failed while executing:", t ); 313 if( debug ) { 314 return stackTrace( params, t ); 315 } 316 317 throw new PluginException( rb.getString( "plugin.error.failed" ), t ); 318 } 319 320 } catch( final ClassCastException e ) { 321 throw new PluginException( MessageFormat.format( rb.getString( "plugin.error.notawikiplugin" ), classname ), e ); 322 } 323 } 324 325 /** {@inheritDoc} */ 326 @Override 327 public Map< String, String > parseArgs( final String argstring ) throws IOException { 328 final Map< String, String > arglist = new HashMap<>(); 329 // Protection against funny users. 330 if( argstring == null ) { 331 return arglist; 332 } 333 334 arglist.put( PARAM_CMDLINE, argstring ); 335 final StringReader in = new StringReader( argstring ); 336 final StreamTokenizer tok = new StreamTokenizer( in ); 337 tok.eolIsSignificant( true ); 338 339 String param = null; 340 String value; 341 boolean potentialEmptyLine = false; 342 boolean quit = false; 343 while( !quit ) { 344 final String s; 345 final int type = tok.nextToken(); 346 347 switch( type ) { 348 case StreamTokenizer.TT_EOF: 349 quit = true; 350 s = null; 351 break; 352 353 case StreamTokenizer.TT_WORD: 354 s = tok.sval; 355 potentialEmptyLine = false; 356 break; 357 358 case StreamTokenizer.TT_EOL: 359 quit = potentialEmptyLine; 360 potentialEmptyLine = true; 361 s = null; 362 break; 363 364 case StreamTokenizer.TT_NUMBER: 365 s = Integer.toString( ( int )tok.nval ); 366 potentialEmptyLine = false; 367 break; 368 369 case '\'': 370 s = tok.sval; 371 break; 372 373 default: 374 s = null; 375 } 376 377 // Assume that alternate words on the line are parameter and value, respectively. 378 if( s != null ) { 379 if( param == null ) { 380 param = s; 381 } else { 382 value = s; 383 arglist.put( param, value ); 384 param = null; 385 } 386 } 387 } 388 389 // Now, we'll check the body. 390 if( potentialEmptyLine ) { 391 final StringWriter out = new StringWriter(); 392 FileUtil.copyContents( in, out ); 393 final String bodyContent = out.toString(); 394 if( bodyContent != null ) { 395 arglist.put( PARAM_BODY, bodyContent ); 396 } 397 } 398 399 return arglist; 400 } 401 402 /** {@inheritDoc} */ 403 @Override 404 public String execute( final Context context, final String commandline ) throws PluginException { 405 if( !m_pluginsEnabled ) { 406 return ""; 407 } 408 409 final ResourceBundle rb = Preferences.getBundle( context, Plugin.CORE_PLUGINS_RESOURCEBUNDLE ); 410 final PatternMatcher matcher = new Perl5Matcher(); 411 412 try { 413 if( matcher.contains( commandline, m_pluginPattern ) ) { 414 final MatchResult res = matcher.getMatch(); 415 final String plugin = res.group( 2 ); 416 final int endIndex = commandline.length() - ( commandline.charAt( commandline.length() - 1 ) == '}' ? 1 : 0 ); 417 final String args = commandline.substring( res.endOffset( 0 ), endIndex ); 418 final Map< String, String > arglist = parseArgs( args ); 419 return execute( context, plugin, arglist ); 420 } 421 } catch( final NoSuchElementException e ) { 422 final String msg = "Missing parameter in plugin definition: " + commandline; 423 LOG.warn( msg, e ); 424 throw new PluginException( MessageFormat.format( rb.getString( "plugin.error.missingparameter" ), commandline ) ); 425 } catch( final IOException e ) { 426 final String msg = "Zyrf. Problems with parsing arguments: " + commandline; 427 LOG.warn( msg, e ); 428 throw new PluginException( MessageFormat.format( rb.getString( "plugin.error.parsingarguments" ), commandline ) ); 429 } 430 431 // FIXME: We could either return an empty string "", or the original line. If we want unsuccessful requests 432 // to be invisible, then we should return an empty string. 433 return commandline; 434 } 435 436 /** Register a plugin. */ 437 private void registerPlugin( final WikiPluginInfo pluginClass ) { 438 String name; 439 440 // Register the plugin with the className without the package-part 441 name = pluginClass.getName(); 442 if( name != null ) { 443 LOG.debug( "Registering plugin [name]: " + name ); 444 m_pluginClassMap.put( name, pluginClass ); 445 } 446 447 // Register the plugin with a short convenient name. 448 name = pluginClass.getAlias(); 449 if( name != null ) { 450 LOG.debug( "Registering plugin [shortName]: " + name ); 451 m_pluginClassMap.put( name, pluginClass ); 452 } 453 454 // Register the plugin with the className with the package-part 455 name = pluginClass.getClassName(); 456 if( name != null ) { 457 LOG.debug( "Registering plugin [className]: " + name ); 458 m_pluginClassMap.put( name, pluginClass ); 459 } 460 461 pluginClass.initializePlugin( pluginClass, m_engine, m_searchPath, m_externalJars ); 462 } 463 464 private void registerPlugins() { 465 // Register all plugins which have created a resource containing its properties. 466 LOG.info( "Registering plugins" ); 467 final List< Element > plugins = XmlUtil.parse( PLUGIN_RESOURCE_LOCATION, "/modules/plugin" ); 468 469 // Get all resources of all plugins. 470 for( final Element pluginEl : plugins ) { 471 final String className = pluginEl.getAttributeValue( "class" ); 472 final WikiPluginInfo pluginInfo = WikiPluginInfo.newInstance( className, pluginEl ,m_searchPath, m_externalJars ); 473 if( pluginInfo != null ) { 474 registerPlugin( pluginInfo ); 475 } 476 } 477 } 478 479 /** 480 * Contains information about a bunch of plugins. 481 */ 482 // FIXME: This class needs a better interface to return all sorts of possible information from the plugin XML. In fact, it probably 483 // should have some sort of a superclass system. 484 public static final class WikiPluginInfo extends WikiModuleInfo { 485 486 private String m_className; 487 private String m_alias; 488 private String m_ajaxAlias; 489 private Class< Plugin > m_clazz; 490 491 private boolean m_initialized; 492 493 /** 494 * Creates a new plugin info object which can be used to access a plugin. 495 * 496 * @param className Either a fully qualified class name, or a "short" name which is then checked against the internal list of plugin packages. 497 * @param el A JDOM Element containing the information about this class. 498 * @param searchPath A List of Strings, containing different package names. 499 * @param externalJars the list of external jars to search 500 * @return A WikiPluginInfo object. 501 */ 502 static WikiPluginInfo newInstance( final String className, final Element el, final List<String> searchPath, final List<String> externalJars ) { 503 if( className == null || className.isEmpty() ) { 504 return null; 505 } 506 507 final WikiPluginInfo info = new WikiPluginInfo( className ); 508 info.initializeFromXML( el ); 509 return info; 510 } 511 512 /** 513 * Initializes a plugin, if it has not yet been initialized. If the plugin extends {@link HttpServlet} it will automatically 514 * register it as AJAX using {@link WikiAjaxDispatcherServlet#registerServlet(String, WikiAjaxServlet)}. 515 * 516 * @param engine The Engine 517 * @param searchPath A List of Strings, containing different package names. 518 * @param externalJars the list of external jars to search 519 */ 520 void initializePlugin( final WikiPluginInfo info, final Engine engine , final List<String> searchPath, final List<String> externalJars) { 521 if( !m_initialized ) { 522 // This makes sure we only try once per class, even if init fails. 523 m_initialized = true; 524 525 try { 526 final Plugin p = newPluginInstance(searchPath, externalJars); 527 if( p instanceof InitializablePlugin ) { 528 ( ( InitializablePlugin )p ).initialize( engine ); 529 } 530 if( p instanceof WikiAjaxServlet ) { 531 WikiAjaxDispatcherServlet.registerServlet( (WikiAjaxServlet) p ); 532 final String ajaxAlias = info.getAjaxAlias(); 533 if (StringUtils.isNotBlank(ajaxAlias)) { 534 WikiAjaxDispatcherServlet.registerServlet( info.getAjaxAlias(), (WikiAjaxServlet) p ); 535 } 536 } 537 } catch( final Exception e ) { 538 LOG.info( "Cannot initialize plugin " + m_className, e ); 539 } 540 } 541 } 542 543 /** 544 * {@inheritDoc} 545 */ 546 @Override 547 protected void initializeFromXML( final Element el ) { 548 super.initializeFromXML( el ); 549 m_alias = el.getChildText( "alias" ); 550 m_ajaxAlias = el.getChildText( "ajaxAlias" ); 551 } 552 553 /** 554 * Create a new WikiPluginInfo based on the Class information. 555 * 556 * @param clazz The class to check 557 * @return A WikiPluginInfo instance 558 */ 559 static WikiPluginInfo newInstance( final Class< ? > clazz ) { 560 return new WikiPluginInfo( clazz.getName() ); 561 } 562 563 private WikiPluginInfo( final String className ) { 564 super( className ); 565 setClassName( className ); 566 } 567 568 private void setClassName( final String fullClassName ) { 569 m_name = ClassUtils.getShortClassName( fullClassName ); 570 m_className = fullClassName; 571 } 572 573 /** 574 * Returns the full class name of this object. 575 * @return The full class name of the object. 576 */ 577 public String getClassName() { 578 return m_className; 579 } 580 581 /** 582 * Returns the alias name for this object. 583 * @return An alias name for the plugin. 584 */ 585 public String getAlias() { 586 return m_alias; 587 } 588 589 /** 590 * Returns the ajax alias name for this object. 591 * @return An ajax alias name for the plugin. 592 */ 593 public String getAjaxAlias() { 594 return m_ajaxAlias; 595 } 596 597 /** 598 * Creates a new plugin instance. 599 * 600 * @param searchPath A List of Strings, containing different package names. 601 * @param externalJars the list of external jars to search 602 * @return A new plugin. 603 * @throws ClassNotFoundException If the class declared was not found. 604 * @throws InstantiationException If the class cannot be instantiated- 605 * @throws IllegalAccessException If the class cannot be accessed. 606 */ 607 608 public Plugin newPluginInstance( final List< String > searchPath, final List< String > externalJars) throws ReflectiveOperationException { 609 if( m_clazz == null ) { 610 m_clazz = ClassUtil.findClass( searchPath, externalJars ,m_className ); 611 } 612 613 return ClassUtil.buildInstance( m_clazz ); 614 } 615 616 /** 617 * Returns a text for IncludeResources. 618 * 619 * @param type Either "script" or "stylesheet" 620 * @return Text, or an empty string, if there is nothing to be included. 621 */ 622 public String getIncludeText( final String type ) { 623 try { 624 if( "script".equals( type ) ) { 625 return getScriptText(); 626 } else if( "stylesheet".equals( type ) ) { 627 return getStylesheetText(); 628 } 629 } catch( final Exception ex ) { 630 // We want to fail gracefully here 631 return ex.getMessage(); 632 } 633 634 return null; 635 } 636 637 private String getScriptText() throws IOException { 638 if( m_scriptText != null ) { 639 return m_scriptText; 640 } 641 642 if( m_scriptLocation == null ) { 643 return ""; 644 } 645 646 try { 647 m_scriptText = getTextResource(m_scriptLocation); 648 } catch( final IOException ex ) { 649 // Only throw this exception once! 650 m_scriptText = ""; 651 throw ex; 652 } 653 654 return m_scriptText; 655 } 656 657 private String getStylesheetText() throws IOException { 658 if( m_stylesheetText != null ) { 659 return m_stylesheetText; 660 } 661 662 if( m_stylesheetLocation == null ) { 663 return ""; 664 } 665 666 try { 667 m_stylesheetText = getTextResource(m_stylesheetLocation); 668 } catch( final IOException ex ) { 669 // Only throw this exception once! 670 m_stylesheetText = ""; 671 throw ex; 672 } 673 674 return m_stylesheetText; 675 } 676 677 /** 678 * Returns a string suitable for debugging. Don't assume that the format would stay the same. 679 * 680 * @return Something human-readable 681 */ 682 @Override 683 public String toString() { 684 return "Plugin :[name=" + m_name + "][className=" + m_className + "]"; 685 } 686 687 } // WikiPluginClass 688 689 /** 690 * {@inheritDoc} 691 */ 692 @Override 693 public Collection< WikiModuleInfo > modules() { 694 return modules( m_pluginClassMap.values().iterator() ); 695 } 696 697 /** 698 * {@inheritDoc} 699 */ 700 @Override 701 public WikiPluginInfo getModuleInfo( final String moduleName) { 702 return m_pluginClassMap.get(moduleName); 703 } 704 705 /** 706 * Creates a {@link Plugin}. 707 * 708 * @param pluginName plugin's classname 709 * @param rb {@link ResourceBundle} with i18ned text for exceptions. 710 * @return a {@link Plugin}. 711 * @throws PluginException if there is a problem building the {@link Plugin}. 712 */ 713 @Override 714 public Plugin newWikiPlugin( final String pluginName, final ResourceBundle rb ) throws PluginException { 715 Plugin plugin = null; 716 WikiPluginInfo pluginInfo = m_pluginClassMap.get( pluginName ); 717 try { 718 if( pluginInfo == null ) { 719 pluginInfo = WikiPluginInfo.newInstance( findPluginClass( pluginName ) ); 720 registerPlugin( pluginInfo ); 721 } 722 723 if( !checkCompatibility( pluginInfo ) ) { 724 final String msg = "Plugin '" + pluginInfo.getName() + "' not compatible with this version of JSPWiki"; 725 LOG.info( msg ); 726 } else { 727 plugin = pluginInfo.newPluginInstance(m_searchPath, m_externalJars); 728 } 729 } catch( final ClassNotFoundException e ) { 730 throw new PluginException( MessageFormat.format( rb.getString( "plugin.error.couldnotfind" ), pluginName ), e ); 731 } catch( final InstantiationException e ) { 732 throw new PluginException( MessageFormat.format( rb.getString( "plugin.error.cannotinstantiate" ), pluginName ), e ); 733 } catch( final IllegalAccessException e ) { 734 throw new PluginException( MessageFormat.format( rb.getString( "plugin.error.notallowed" ), pluginName ), e ); 735 } catch( final Exception e ) { 736 throw new PluginException( MessageFormat.format( rb.getString( "plugin.error.instantationfailed" ), pluginName ), e ); 737 } 738 return plugin; 739 } 740 741 @Override 742 public List<Plugin> getDiscoveredPlugins() { 743 Collection<WikiModuleInfo> pluginModules = modules(); 744 Set<Plugin> plugins = new HashSet<>(); 745 for(WikiModuleInfo plugin : pluginModules) { 746 try { 747 Plugin p = (Plugin) Class.forName(((WikiPluginInfo)plugin).getClassName()).getDeclaredConstructor().newInstance(); 748 plugins.add(p); 749 } catch (Throwable ex) { 750 LOG.error("failed to load class " + plugin.getName(), ex); 751 } 752 } 753 754 return new ArrayList<>(plugins); 755 } 756 757}