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 Iterable<CRaSHPlugin<?>> getPlugins() {
121        return manager.getPlugins();
122      }
123    
124      public final String getVersion() {
125        return version;
126      }
127    
128      /**
129       * Returns the list of properties.
130       *
131       * @return the properties
132       */
133      public final Collection<Property<?>> getFoo()
134      {
135        return properties.values();
136      }
137    
138      /**
139       * Returns a context property or null if it cannot be found.
140       *
141       * @param desc the property descriptor
142       * @param <T> the property parameter type
143       * @return the property value
144       * @throws NullPointerException if the descriptor argument is null
145       */
146      public final <T> T getProperty(PropertyDescriptor<T> desc) throws NullPointerException {
147        if (desc == null) {
148          throw new NullPointerException();
149        }
150        Property<T> property = (Property<T>)properties.get(desc);
151        return property != null ? property.getValue() : desc.defaultValue;
152      }
153    
154      /**
155       * Returns a context property or null if it cannot be found.
156       *
157       * @param propertyName the name of the property
158       * @param type the property type
159       * @param <T> the property parameter type
160       * @return the property value
161       * @throws NullPointerException if the descriptor argument is null
162       */
163      public final <T> T getProperty(String propertyName, Class<T> type) throws NullPointerException {
164        if (propertyName == null) {
165          throw new NullPointerException("No null property name accepted");
166        }
167        if (type == null) {
168          throw new NullPointerException("No null property type accepted");
169        }
170        for (PropertyDescriptor<?> pd : properties.keySet())
171        {
172          if (pd.name.equals(propertyName) && type.isAssignableFrom(pd.type))
173          {
174            return type.cast(getProperty(pd));
175          }
176        }
177        return null;
178      }
179    
180      /**
181       * Set a context property to a new value. If the provided value is null, then the property is removed.
182       *
183       * @param desc the property descriptor
184       * @param value the property value
185       * @param <T> the property parameter type
186       * @throws NullPointerException if the descriptor argument is null
187       */
188      public final <T> void setProperty(PropertyDescriptor<T> desc, T value) throws NullPointerException {
189        if (desc == null) {
190          throw new NullPointerException();
191        }
192        if (value == null) {
193          log.debug("Removing property " + desc.name);
194          properties.remove(desc);
195        } else {
196          Property<T> property = new Property<T>(desc, value);
197          log.debug("Setting property " + desc.name + " to value " + property.getValue());
198          properties.put(desc, property);
199        }
200      }
201    
202      /**
203       * Set a context property to a new value. If the provided value is null, then the property is removed.
204       *
205       * @param desc the property descriptor
206       * @param value the property value
207       * @param <T> the property parameter type
208       * @throws NullPointerException if the descriptor argument is null
209       * @throws IllegalArgumentException if the string value cannot be converted to the property type
210       */
211      public final <T> void setProperty(PropertyDescriptor<T> desc, String value) throws NullPointerException, IllegalArgumentException {
212        if (desc == null) {
213          throw new NullPointerException();
214        }
215        if (value == null) {
216          log.debug("Removing property " + desc.name);
217          properties.remove(desc);
218        } else {
219          Property<T> property = desc.toProperty(value);
220          log.debug("Setting property " + desc.name + " to value " + property.getValue());
221          properties.put(desc, property);
222        }
223      }
224    
225      public final Resource loadResource(String resourceId, ResourceKind resourceKind) {
226        Resource res = null;
227        try {
228    
229          //
230          switch (resourceKind) {
231            case LIFECYCLE:
232              if ("login".equals(resourceId) || "logout".equals(resourceId)) {
233                StringBuilder sb = new StringBuilder();
234                long timestamp = Long.MIN_VALUE;
235                for (File path : dirs) {
236                  File f = path.child(resourceId + ".groovy", false);
237                  if (f != null) {
238                    Resource sub = f.getResource();
239                    if (sub != null) {
240                      sb.append(sub.getContent() + "\n");
241                      timestamp = Math.max(timestamp, sub.getTimestamp());
242                    }
243                  }
244                }
245                return new Resource(sb.toString(), timestamp);
246              }
247              break;
248            case SCRIPT:
249              // Find the resource first, we find for the first found
250              for (File path : dirs) {
251                File f = path.child(resourceId + ".groovy", false);
252                if (f != null) {
253                  res = f.getResource();
254                }
255              }
256              break;
257            case CONFIG:
258              if ("telnet.properties".equals(resourceId)) {
259                File telnet = vfs.get(Path.get("/telnet/telnet.properties"));
260                if (telnet != null) {
261                  res = telnet.getResource();
262                }
263              }
264              if ("crash.properties".equals(resourceId)) {
265                File props = vfs.get(Path.get("/crash.properties"));
266                if (props != null) {
267                  res = props.getResource();
268                }
269              }
270              break;
271            case KEY:
272              if ("hostkey.pem".equals(resourceId)) {
273                File key = vfs.get((Path.get("/ssh/hostkey.pem")));
274                if (key != null) {
275                  res = key.getResource();
276                }
277              }
278              break;
279          }
280        } catch (IOException e) {
281          log.warn("Could not obtain resource " + resourceId, e);
282        }
283        return res;
284      }
285    
286      public final List<String> listResourceId(ResourceKind kind) {
287        switch (kind) {
288          case SCRIPT:
289            SortedSet<String> all = new TreeSet<String>();
290            try {
291              for (File path : dirs) {
292                for (File file : path.children()) {
293                  String name = file.getName();
294                  Matcher matcher = p.matcher(name);
295                  if (matcher.matches()) {
296                    all.add(matcher.group(1));
297                  }
298                }
299              }
300            }
301            catch (IOException e) {
302              e.printStackTrace();
303            }
304            all.remove("login");
305            all.remove("logout");
306            return new ArrayList<String>(all);
307          default:
308            return Collections.emptyList();
309        }
310      }
311    
312      public final ClassLoader getLoader() {
313        return loader;
314      }
315    
316      /**
317       * Refresh the fs system view. This is normally triggered by the periodic job but it can be manually
318       * invoked to trigger explicit refreshes.
319       */
320      public final void refresh() {
321        try {
322          File commands = vfs.get(Path.get("/commands/"));
323          List<File> newDirs = new ArrayList<File>();
324          newDirs.add(commands);
325          for (File path : commands.children()) {
326            if (path.isDir()) {
327              newDirs.add(path);
328            }
329          }
330          dirs = newDirs;
331        }
332        catch (IOException e) {
333          e.printStackTrace();
334        }
335      }
336    
337      public final synchronized  void start() {
338        if (!started) {
339    
340          // Start refresh
341          Integer refreshRate = getProperty(PropertyDescriptor.VFS_REFRESH_PERIOD);
342          TimeUnit timeUnit = getProperty(PropertyDescriptor.VFS_REFRESH_UNIT);
343          if (refreshRate != null && refreshRate > 0) {
344            TimeUnit tu = timeUnit != null ? timeUnit : TimeUnit.SECONDS;
345            executor =  new ScheduledThreadPoolExecutor(1);
346            executor.scheduleWithFixedDelay(new Runnable() {
347              int count = 0;
348              public void run() {
349                refresh();
350              }
351            }, 0, refreshRate, tu);
352          }
353    
354          // Init plugins
355          manager.getPlugins(Object.class);
356    
357          //
358          started = true;
359        } else {
360          log.warn("Attempt to double start");
361        }
362      }
363    
364      public final synchronized void stop() {
365    
366        //
367        if (started) {
368    
369          // Shutdown manager
370          manager.shutdown();
371    
372          //
373          if (executor != null) {
374            ScheduledExecutorService tmp = executor;
375            executor = null;
376            tmp.shutdown();
377          }
378        } else {
379          log.warn("Attempt to stop when stopped");
380        }
381      }
382    
383      public <T> Iterable<T> getPlugins(Class<T> pluginType) {
384        return manager.getPlugins(pluginType);
385      }
386    }