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