001    /*
002     * Copyright (C) 2003-2009 eXo Platform SAS.
003     *
004     * This is free software; you can redistribute it and/or modify it
005     * under the terms of the GNU Lesser General Public License as
006     * published by the Free Software Foundation; either version 2.1 of
007     * the License, or (at your option) any later version.
008     *
009     * This software is distributed in the hope that it will be useful,
010     * but WITHOUT ANY WARRANTY; without even the implied warranty of
011     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012     * Lesser General Public License for more details.
013     *
014     * You should have received a copy of the GNU Lesser General Public
015     * License along with this software; if not, write to the Free
016     * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017     * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018     */
019    package org.crsh.plugin;
020    
021    import org.crsh.vfs.FS;
022    import org.crsh.vfs.File;
023    import org.crsh.vfs.Path;
024    import org.crsh.vfs.Resource;
025    import org.slf4j.Logger;
026    import org.slf4j.LoggerFactory;
027    
028    import java.io.IOException;
029    import java.io.InputStream;
030    import java.util.*;
031    import java.util.concurrent.ScheduledExecutorService;
032    import java.util.concurrent.ScheduledThreadPoolExecutor;
033    import java.util.concurrent.TimeUnit;
034    import java.util.regex.Matcher;
035    import java.util.regex.Pattern;
036    
037    /**
038     * The plugin context.
039     *
040     * @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a>
041     * @version $Revision$
042     */
043    public class PluginContext {
044    
045      /** . */
046      private static final Pattern p = Pattern.compile("(.+)\\.groovy");
047    
048      /** . */
049      private static final Logger log = LoggerFactory.getLogger(PluginContext.class);
050    
051      /** . */
052      final PluginManager manager;
053    
054      /** . */
055      private final ClassLoader loader;
056    
057      /** . */
058      private final String version;
059    
060      /** . */
061      private ScheduledExecutorService executor;
062    
063      /** . */
064      private volatile List<File> dirs;
065    
066      /** . */
067      private final Map<PropertyDescriptor<?>, Property<?>> properties;
068    
069      /** . */
070      private final FS vfs;
071    
072      /** . */
073      private boolean started;
074    
075      /**
076       * Create a new plugin context.
077       *
078       * @param discovery the plugin discovery
079       * @param fs the file system
080       * @param loader the loader
081       * @throws NullPointerException if any parameter argument is null
082       */
083      public PluginContext(PluginDiscovery discovery, FS fs, ClassLoader loader) throws NullPointerException {
084        if (fs == null) {
085          throw new NullPointerException();
086        }
087        if (loader == null) {
088          throw new NullPointerException();
089        }
090    
091        //
092        String version = null;
093        try {
094          Properties props = new Properties();
095          InputStream in = getClass().getClassLoader().getResourceAsStream("META-INF/maven/org.crsh/crsh.shell.core/pom.properties");
096          if (in != null) {
097            props.load(in);
098            version = props.getProperty("version");
099          }
100        } catch (Exception e) {
101          log.error("Could not load maven properties", e);
102        }
103    
104        //
105        if (version == null) {
106          log.warn("No version found will use unknown value instead");
107          version = "unknown";
108        }
109    
110        //
111        this.loader = loader;
112        this.version = version;
113        this.dirs = Collections.emptyList();
114        this.vfs = fs;
115        this.properties = new HashMap<PropertyDescriptor<?>, Property<?>>();
116        this.started = false;
117        this.manager = new PluginManager(this, discovery);
118      }
119    
120      public final String getVersion() {
121        return version;
122      }
123    
124      /**
125       * Returns a context property or null if it cannot be found.
126       *
127       * @param desc the property descriptor
128       * @param <T> the property parameter type
129       * @return the property value
130       * @throws NullPointerException if the descriptor argument is null
131       */
132      public final <T> T getProperty(PropertyDescriptor<T> desc) throws NullPointerException {
133        if (desc == null) {
134          throw new NullPointerException();
135        }
136        Property<T> property = (Property<T>)properties.get(desc);
137        return property != null ? property.getValue() : desc.defaultValue;
138      }
139    
140      /**
141       * Returns a context property or null if it cannot be found.
142       *
143       * @param propertyName the name of the property
144       * @param type the property type
145       * @param <T> the property parameter type
146       * @return the property value
147       * @throws NullPointerException if the descriptor argument is null
148       */
149      public final <T> T getProperty(String propertyName, Class<T> type) throws NullPointerException {
150        if (propertyName == null) {
151          throw new NullPointerException("No null property name accepted");
152        }
153        if (type == null) {
154          throw new NullPointerException("No null property type accepted");
155        }
156        for (PropertyDescriptor<?> pd : properties.keySet())
157        {
158          if (pd.name.equals(propertyName) && type.isAssignableFrom(pd.type))
159          {
160            return type.cast(getProperty(pd));
161          }
162        }
163        return null;
164      }
165    
166      /**
167       * Set a context property to a new value. If the provided value is null, then the property is removed.
168       *
169       * @param desc the property descriptor
170       * @param value the property value
171       * @param <T> the property parameter type
172       * @throws NullPointerException if the descriptor argument is null
173       */
174      public final <T> void setProperty(PropertyDescriptor<T> desc, T value) throws NullPointerException {
175        if (desc == null) {
176          throw new NullPointerException();
177        }
178        if (value == null) {
179          log.debug("Removing property " + desc.name);
180          properties.remove(desc);
181        } else {
182          Property<T> property = new Property<T>(desc, value);
183          log.debug("Setting property " + desc.name + " to value " + property.getValue());
184          properties.put(desc, property);
185        }
186      }
187    
188      /**
189       * Set a context property to a new value. If the provided value is null, then the property is removed.
190       *
191       * @param desc the property descriptor
192       * @param value the property value
193       * @param <T> the property parameter type
194       * @throws NullPointerException if the descriptor argument is null
195       * @throws IllegalArgumentException if the string value cannot be converted to the property type
196       */
197      public final <T> void setProperty(PropertyDescriptor<T> desc, String value) throws NullPointerException, IllegalArgumentException {
198        if (desc == null) {
199          throw new NullPointerException();
200        }
201        if (value == null) {
202          log.debug("Removing property " + desc.name);
203          properties.remove(desc);
204        } else {
205          Property<T> property = desc.toProperty(value);
206          log.debug("Setting property " + desc.name + " to value " + property.getValue());
207          properties.put(desc, property);
208        }
209      }
210    
211      public final Resource loadResource(String resourceId, ResourceKind resourceKind) {
212        Resource res = null;
213        try {
214    
215          //
216          switch (resourceKind) {
217            case LIFECYCLE:
218              if ("login".equals(resourceId) || "logout".equals(resourceId)) {
219                StringBuilder sb = new StringBuilder();
220                long timestamp = Long.MIN_VALUE;
221                for (File path : dirs) {
222                  File f = path.child(resourceId + ".groovy", false);
223                  if (f != null) {
224                    Resource sub = f.getResource();
225                    if (sub != null) {
226                      sb.append(sub.getContent() + "\n");
227                      timestamp = Math.max(timestamp, sub.getTimestamp());
228                    }
229                  }
230                }
231                return new Resource(sb.toString(), timestamp);
232              }
233              break;
234            case SCRIPT:
235              // Find the resource first, we find for the first found
236              for (File path : dirs) {
237                File f = path.child(resourceId + ".groovy", false);
238                if (f != null) {
239                  res = f.getResource();
240                }
241              }
242              break;
243            case CONFIG:
244              if ("telnet.properties".equals(resourceId)) {
245                File telnet = vfs.get(Path.get("/telnet/telnet.properties"));
246                if (telnet != null) {
247                  res = telnet.getResource();
248                }
249              }
250              if ("crash.properties".equals(resourceId)) {
251                File props = vfs.get(Path.get("/crash.properties"));
252                if (props != null) {
253                  res = props.getResource();
254                }
255              }
256              break;
257            case KEY:
258              if ("hostkey.pem".equals(resourceId)) {
259                File key = vfs.get((Path.get("/ssh/hostkey.pem")));
260                if (key != null) {
261                  res = key.getResource();
262                }
263              }
264              break;
265          }
266        } catch (IOException e) {
267          log.warn("Could not obtain resource " + resourceId, e);
268        }
269        return res;
270      }
271    
272      public final List<String> listResourceId(ResourceKind kind) {
273        switch (kind) {
274          case SCRIPT:
275            SortedSet<String> all = new TreeSet<String>();
276            try {
277              for (File path : dirs) {
278                for (File file : path.children()) {
279                  String name = file.getName();
280                  Matcher matcher = p.matcher(name);
281                  if (matcher.matches()) {
282                    all.add(matcher.group(1));
283                  }
284                }
285              }
286            }
287            catch (IOException e) {
288              e.printStackTrace();
289            }
290            all.remove("login");
291            all.remove("logout");
292            return new ArrayList<String>(all);
293          default:
294            return Collections.emptyList();
295        }
296      }
297    
298      public final ClassLoader getLoader() {
299        return loader;
300      }
301    
302      /**
303       * Refresh the fs system view. This is normally triggered by the periodic job but it can be manually
304       * invoked to trigger explicit refreshes.
305       */
306      public final void refresh() {
307        try {
308          File commands = vfs.get(Path.get("/commands/"));
309          List<File> newDirs = new ArrayList<File>();
310          newDirs.add(commands);
311          for (File path : commands.children()) {
312            if (path.isDir()) {
313              newDirs.add(path);
314            }
315          }
316          dirs = newDirs;
317        }
318        catch (IOException e) {
319          e.printStackTrace();
320        }
321      }
322    
323      public final synchronized  void start() {
324        if (!started) {
325    
326          // Start refresh
327          Integer refreshRate = getProperty(PropertyDescriptor.VFS_REFRESH_PERIOD);
328          TimeUnit timeUnit = getProperty(PropertyDescriptor.VFS_REFRESH_UNIT);
329          if (refreshRate != null && refreshRate > 0) {
330            TimeUnit tu = timeUnit != null ? timeUnit : TimeUnit.SECONDS;
331            executor =  new ScheduledThreadPoolExecutor(1);
332            executor.scheduleWithFixedDelay(new Runnable() {
333              int count = 0;
334              public void run() {
335                refresh();
336              }
337            }, 0, refreshRate, tu);
338          }
339    
340          // Init services
341          manager.getPlugins(Service.class);
342    
343          //
344          started = true;
345        } else {
346          log.warn("Attempt to double start");
347        }
348      }
349    
350      public final synchronized void stop() {
351    
352        //
353        if (started) {
354    
355          // Shutdown manager
356          manager.shutdown();
357    
358          //
359          if (executor != null) {
360            ScheduledExecutorService tmp = executor;
361            executor = null;
362            tmp.shutdown();
363          }
364        } else {
365          log.warn("Attempt to stop when stopped");
366        }
367      }
368    
369      public <T> Iterable<T> getPlugins(Class<T> pluginType) {
370        return manager.getPlugins(pluginType);
371      }
372    }