View Javadoc
1   /*
2    * Copyright (c) 2002-2022, City of Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.portal.service.plugin;
35  
36  import java.io.File;
37  import java.io.FileInputStream;
38  import java.io.FilenameFilter;
39  import java.util.ArrayList;
40  import java.util.Collection;
41  import java.util.HashMap;
42  import java.util.List;
43  import java.util.Map;
44  import java.util.Properties;
45  import java.util.TreeSet;
46  
47  import fr.paris.lutece.portal.service.database.AppConnectionService;
48  import fr.paris.lutece.portal.service.datastore.DatastoreService;
49  import fr.paris.lutece.portal.service.init.LuteceInitException;
50  import fr.paris.lutece.portal.service.util.AppLogService;
51  import fr.paris.lutece.portal.service.util.AppPathService;
52  import fr.paris.lutece.util.filesystem.FileListFilter;
53  
54  /**
55   * This class provides services and utilities for plugins management
56   */
57  public final class PluginService
58  {
59      // Constantes
60      private static final String PATH_CONF = "path.conf";
61      private static final String CORE_XML = "core.xml";
62      private static final String CORE = "core";
63      private static Plugin _pluginCore;
64      private static final String PATH_PLUGIN = "path.plugins";
65      private static final String FILE_PLUGINS_STATUS = "plugins.dat";
66      private static final String EXTENSION_FILE = "xml";
67      private static final String PROPERTY_IS_INSTALLED = ".installed";
68      private static final String PROPERTY_DB_POOL_NAME = ".pool";
69      private static final String KEY_PLUGINS_STATUS = "core.plugins.status.";
70  
71      // Variables
72      private static Map<String, Plugin> _mapPlugins = new HashMap<>( );
73      private static List<PluginEventListener> _listPluginEventListeners = new ArrayList<>( );
74  
75      /**
76       * Creates a new PluginService object.
77       */
78      private PluginService( )
79      {
80      }
81  
82      /**
83       * Initialize the service
84       * 
85       * @throws LuteceInitException
86       *             If an error occured
87       */
88      public static void init( ) throws LuteceInitException
89      {
90          loadPluginsStatus( );
91          _mapPlugins.clear( );
92          loadCoreComponents( );
93          loadPlugins( );
94      }
95  
96      /**
97       * Returns the plugins file list
98       *
99       * @return the plugins file list as a File[]
100      */
101     public static Collection<Plugin> getPluginList( )
102     {
103         return new TreeSet<>( _mapPlugins.values( ) );
104     }
105 
106     /**
107      * Returns a Plugin object from its name
108      *
109      * @param strPluginName
110      *            The name of the plugin
111      * @return The Plugin object corresponding to the name
112      */
113     public static Plugin getPlugin( String strPluginName )
114     {
115         return _mapPlugins.get( strPluginName );
116     }
117 
118     /**
119      * Load components of the core.
120      * 
121      * @throws LuteceInitException
122      *             If an error occured
123      */
124     private static void loadCoreComponents( ) throws LuteceInitException
125     {
126         File file = new File( AppPathService.getPath( PATH_CONF, CORE_XML ) );
127 
128         if ( file.exists( ) )
129         {
130             loadPluginFromFile( file, false );
131         }
132     }
133 
134     /**
135      * Load all plugins installed on the system.
136      * 
137      * @throws LuteceInitException
138      *             If an error occured
139      */
140     private static void loadPlugins( ) throws LuteceInitException
141     {
142         File dirPlugin = new File( AppPathService.getPath( PATH_PLUGIN ) );
143 
144         if ( dirPlugin.exists( ) )
145         {
146             FilenameFilter select = new FileListFilter( "", EXTENSION_FILE );
147             File [ ] listFile = dirPlugin.listFiles( select );
148 
149             for ( File file : listFile )
150             {
151                 loadPluginFromFile( file, true );
152             }
153         }
154     }
155 
156     /**
157      * Load a plugin from a file definition
158      * 
159      * @param file
160      *            The plugin file
161      * @param bRegisterAsPlugin
162      *            Register it as a plugin : true for plugins, false for core components file
163      * @throws LuteceInitException
164      *             If an error occured
165      */
166     private static void loadPluginFromFile( File file, boolean bRegisterAsPlugin ) throws LuteceInitException
167     {
168         PluginFile/plugin/PluginFile.html#PluginFile">PluginFile pluginFile = new PluginFile( );
169         pluginFile.load( file.getAbsolutePath( ) );
170 
171         String strPluginClass = pluginFile.getPluginClass( );
172 
173         if ( strPluginClass != null )
174         {
175             try
176             {
177                 Plugin../../../../../../fr/paris/lutece/portal/service/plugin/Plugin.html#Plugin">Plugin plugin = (Plugin) Class.forName( strPluginClass ).newInstance( );
178                 plugin.load( pluginFile );
179 
180                 if ( bRegisterAsPlugin )
181                 {
182                     plugin.setStatus( getPluginStatus( plugin ) );
183                     registerPlugin( plugin );
184                 }
185                 else
186                 {
187                     plugin.setStatus( true );
188                     registerCore( plugin );
189                 }
190 
191                 // If the plugin requires a database connection pool then
192                 // get the pool name and initialize its ConnectionService
193                 if ( plugin.isDbPoolRequired( ) )
194                 {
195                     String strPoolName = getPluginPoolName( plugin );
196                     plugin.setPoolName( strPoolName );
197                     plugin.initConnectionService( strPoolName );
198                 }
199 
200                 plugin.init( );
201 
202                 // plugin installed event
203                 PluginEventvice/plugin/PluginEvent.html#PluginEvent">PluginEvent event = new PluginEvent( plugin, PluginEvent.PLUGIN_INSTALLED );
204                 notifyListeners( event );
205             }
206             catch( Exception e )
207             {
208                 throw new LuteceInitException( "Error instantiating plugin defined in file : " + file.getAbsolutePath( ), e );
209             }
210         }
211         else
212         {
213             AppLogService.error( "No plugin class defined in file : {}", file.getAbsolutePath( ) );
214         }
215     }
216 
217     /**
218      * Register the plugin as a plugin loaded in the system
219      *
220      * @param plugin
221      *            The plugin object
222      */
223     private static void registerPlugin( Plugin plugin )
224     {
225         _mapPlugins.put( plugin.getName( ), plugin );
226 
227         String strStatusWarning = ( plugin.isInstalled( ) ) ? "" : " *** Warning : current status is 'disabled' ***";
228         AppLogService.info( "New Plugin registered : {} {}", plugin.getName( ), strStatusWarning );
229     }
230 
231     /**
232      * Gets the core plugin
233      * 
234      * @param plugin
235      *            the plugin
236      */
237     private static synchronized void registerCore( Plugin plugin )
238     {
239         _pluginCore = plugin;
240     }
241 
242     /**
243      * Gets the core.
244      *
245      * @return the core
246      */
247     public static Plugin getCore( )
248     {
249         return _pluginCore;
250     }
251 
252     /**
253      * Update plugins data.
254      *
255      * @param plugin
256      *            The plugin object
257      */
258     public static void updatePluginData( Plugin plugin )
259     {
260         String strKey = getInstalledKey( plugin.getName( ) );
261         String strValue = plugin.isInstalled( ) ? DatastoreService.VALUE_TRUE : DatastoreService.VALUE_FALSE;
262         DatastoreService.setInstanceDataValue( strKey, strValue );
263 
264         if ( plugin.isDbPoolRequired( ) )
265         {
266             DatastoreService.setInstanceDataValue( getPoolNameKey( plugin.getName( ) ), plugin.getDbPoolName( ) );
267         }
268     }
269 
270     /**
271      * Build the datastore key for a given plugin
272      * 
273      * @param strPluginName
274      *            The plugin name
275      * @return The key
276      */
277     private static String getInstalledKey( String strPluginName )
278     {
279         return KEY_PLUGINS_STATUS + strPluginName + PROPERTY_IS_INSTALLED;
280     }
281 
282     /**
283      * Build the datastore key for a given plugin
284      * 
285      * @param strPluginName
286      *            The plugin name
287      * @return The key
288      */
289     private static String getPoolNameKey( String strPluginName )
290     {
291         return KEY_PLUGINS_STATUS + strPluginName + PROPERTY_DB_POOL_NAME;
292     }
293 
294     /**
295      * Load plugins status
296      */
297     private static void loadPluginsStatus( )
298     {
299         // Load default values from the plugins.dat file
300         String strPluginStatusFile = AppPathService.getPath( PATH_PLUGIN, FILE_PLUGINS_STATUS );
301         File file = new File( strPluginStatusFile );
302         Properties props = new Properties( );
303 
304         try ( FileInputStream fis = new FileInputStream( file ) )
305         {
306             props.load( fis );
307         }
308         catch( Exception e )
309         {
310             AppLogService.error( "Error loading plugin defined in file : {}", file.getAbsolutePath( ), e );
311         }
312 
313         // If the keys aren't found in the datastore then create a key in it
314         for ( String strKey : props.stringPropertyNames( ) )
315         {
316             // Initialize plugins status into Datastore
317             int nPos = strKey.indexOf( PROPERTY_IS_INSTALLED );
318 
319             if ( nPos > 0 )
320             {
321                 String strPluginName = strKey.substring( 0, nPos );
322                 String strDSKey = getInstalledKey( strPluginName );
323 
324                 if ( !DatastoreService.existsInstanceKey( strDSKey ) )
325                 {
326                     String strValue = String.valueOf( props.getProperty( strKey ).equals( "1" ) );
327                     DatastoreService.setInstanceDataValue( strDSKey, strValue );
328                 }
329             }
330 
331             // Initialize plugins connection pool into Datastore
332             nPos = strKey.indexOf( PROPERTY_DB_POOL_NAME );
333 
334             if ( nPos > 0 )
335             {
336                 String strPluginName = strKey.substring( 0, nPos );
337                 String strDSKey = getPoolNameKey( strPluginName );
338 
339                 if ( !DatastoreService.existsInstanceKey( strDSKey ) )
340                 {
341                     String strValue = props.getProperty( strKey );
342                     DatastoreService.setInstanceDataValue( strDSKey, strValue );
343                 }
344             }
345         }
346     }
347 
348     /**
349      * Gets the plugin status
350      *
351      * @param plugin
352      *            The plugin object
353      * @return true if installed, otherwise false
354      */
355     private static boolean getPluginStatus( Plugin plugin )
356     {
357         String strValue = DatastoreService.getInstanceDataValue( getInstalledKey( plugin.getName( ) ), DatastoreService.VALUE_FALSE );
358 
359         return strValue.equals( DatastoreService.VALUE_TRUE );
360     }
361 
362     /**
363      * Gets the pool that should be used by the plugin
364      *
365      * @param plugin
366      *            The plugin Object
367      * @return the pool name
368      */
369     private static String getPluginPoolName( Plugin plugin )
370     {
371         String strPoolname = DatastoreService.getInstanceDataValue( getPoolNameKey( plugin.getName( ) ), AppConnectionService.NO_POOL_DEFINED );
372 
373         if ( strPoolname.equals( AppConnectionService.NO_POOL_DEFINED ) && plugin.isDbPoolRequired( ) && !plugin.getName( ).equals( CORE ) )
374         {
375             AppLogService.info( " *** WARNING *** - The plugin '{}' has no pool defined in db.properties or datastore. Using the default pool '{}' instead.",
376                     plugin, AppConnectionService.DEFAULT_POOL_NAME );
377             strPoolname = AppConnectionService.DEFAULT_POOL_NAME;
378         }
379 
380         return strPoolname;
381     }
382 
383     /**
384      * Gets the plugin status enable / disable
385      * 
386      * @param strPluginName
387      *            The plugin name
388      * @return True if the plugin is enable, otherwise false
389      */
390     public static boolean isPluginEnable( String strPluginName )
391     {
392         if ( strPluginName.equals( CORE ) )
393         {
394             return true;
395         }
396 
397         Plugin plugin = getPlugin( strPluginName );
398 
399         return ( ( plugin != null ) && ( plugin.isInstalled( ) ) );
400     }
401 
402     /**
403      * Register a Plugin Event Listener
404      * 
405      * @param listener
406      *            The listener
407      */
408     public static void registerPluginEventListener( PluginEventListener listener )
409     {
410         _listPluginEventListeners.add( listener );
411     }
412 
413     /**
414      * Notify an event to all Plugin Event Listeners
415      * 
416      * @param event
417      *            The event
418      */
419     public static void notifyListeners( PluginEvent event )
420     {
421         for ( PluginEventListener listener : _listPluginEventListeners )
422         {
423             listener.processPluginEvent( event );
424         }
425     }
426 }