source: josm/trunk/src/org/openstreetmap/josm/plugins/PluginInformation.java@ 6920

Last change on this file since 6920 was 6890, checked in by Don-vip, 10 years ago

fix some Sonar issues (Constructor Calls Overridable Method)

  • Property svn:eol-style set to native
File size: 20.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.plugins;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Image;
7import java.awt.image.BufferedImage;
8import java.io.File;
9import java.io.FileInputStream;
10import java.io.IOException;
11import java.io.InputStream;
12import java.lang.reflect.Constructor;
13import java.lang.reflect.InvocationTargetException;
14import java.net.MalformedURLException;
15import java.net.URL;
16import java.text.MessageFormat;
17import java.util.ArrayList;
18import java.util.Collection;
19import java.util.LinkedList;
20import java.util.List;
21import java.util.Map;
22import java.util.TreeMap;
23import java.util.jar.Attributes;
24import java.util.jar.JarInputStream;
25import java.util.jar.Manifest;
26
27import javax.swing.ImageIcon;
28
29import org.openstreetmap.josm.Main;
30import org.openstreetmap.josm.data.Version;
31import org.openstreetmap.josm.tools.ImageProvider;
32import org.openstreetmap.josm.tools.LanguageInfo;
33import org.openstreetmap.josm.tools.Utils;
34
35/**
36 * Encapsulate general information about a plugin. This information is available
37 * without the need of loading any class from the plugin jar file.
38 *
39 * @author imi
40 */
41public class PluginInformation {
42
43 /** The plugin jar file. */
44 public File file = null;
45 /** The plugin name. */
46 public String name = null;
47 /** The lowest JOSM version required by this plugin (from plugin list). **/
48 public int mainversion = 0;
49 /** The lowest JOSM version required by this plugin (from locally available jar). **/
50 public int localmainversion = 0;
51 /** The plugin class name. */
52 public String className = null;
53 public boolean oldmode = false;
54 /** The list of required plugins, separated by ';' (from plugin list). */
55 public String requires = null;
56 /** The list of required plugins, separated by ';' (from locally available jar). */
57 public String localrequires = null;
58 /** The plugin link (for documentation). */
59 public String link = null;
60 /** The plugin description. */
61 public String description = null;
62 /** Determines if the plugin must be loaded early or not. */
63 public boolean early = false;
64 /** The plugin author. */
65 public String author = null;
66 /** The plugin stage, determining the loading sequence order of plugins. */
67 public int stage = 50;
68 /** The plugin version (from plugin list). **/
69 public String version = null;
70 /** The plugin version (from locally available jar). **/
71 public String localversion = null;
72 /** The plugin download link. */
73 public String downloadlink = null;
74 public String iconPath;
75 /** The plugin icon. */
76 public ImageIcon icon;
77 public List<URL> libraries = new LinkedList<URL>();
78 public final Map<String, String> attr = new TreeMap<String, String>();
79
80 private static final ImageIcon emptyIcon = new ImageIcon(new BufferedImage(24, 24, BufferedImage.TYPE_INT_ARGB));
81
82 /**
83 * Creates a plugin information object by reading the plugin information from
84 * the manifest in the plugin jar.
85 *
86 * The plugin name is derived from the file name.
87 *
88 * @param file the plugin jar file
89 * @throws PluginException if reading the manifest fails
90 */
91 public PluginInformation(File file) throws PluginException{
92 this(file, file.getName().substring(0, file.getName().length()-4));
93 }
94
95 /**
96 * Creates a plugin information object for the plugin with name {@code name}.
97 * Information about the plugin is extracted from the manifest file in the plugin jar
98 * {@code file}.
99 * @param file the plugin jar
100 * @param name the plugin name
101 * @throws PluginException thrown if reading the manifest file fails
102 */
103 public PluginInformation(File file, String name) throws PluginException {
104 if (!PluginHandler.isValidJar(file)) {
105 throw new PluginException(name, tr("Invalid jar file ''{0}''", file));
106 }
107 this.name = name;
108 this.file = file;
109 FileInputStream fis = null;
110 JarInputStream jar = null;
111 try {
112 fis = new FileInputStream(file);
113 jar = new JarInputStream(fis);
114 Manifest manifest = jar.getManifest();
115 if (manifest == null)
116 throw new PluginException(name, tr("The plugin file ''{0}'' does not include a Manifest.", file.toString()));
117 scanManifest(manifest, false);
118 libraries.add(0, Utils.fileToURL(file));
119 } catch (IOException e) {
120 throw new PluginException(name, e);
121 } finally {
122 Utils.close(jar);
123 Utils.close(fis);
124 }
125 }
126
127 /**
128 * Creates a plugin information object by reading plugin information in Manifest format
129 * from the input stream {@code manifestStream}.
130 *
131 * @param manifestStream the stream to read the manifest from
132 * @param name the plugin name
133 * @param url the download URL for the plugin
134 * @throws PluginException thrown if the plugin information can't be read from the input stream
135 */
136 public PluginInformation(InputStream manifestStream, String name, String url) throws PluginException {
137 this.name = name;
138 try {
139 Manifest manifest = new Manifest();
140 manifest.read(manifestStream);
141 if(url != null) {
142 downloadlink = url;
143 }
144 scanManifest(manifest, url != null);
145 } catch (IOException e) {
146 throw new PluginException(name, e);
147 }
148 }
149
150 /**
151 * Updates the plugin information of this plugin information object with the
152 * plugin information in a plugin information object retrieved from a plugin
153 * update site.
154 *
155 * @param other the plugin information object retrieved from the update site
156 */
157 public void updateFromPluginSite(PluginInformation other) {
158 this.mainversion = other.mainversion;
159 this.className = other.className;
160 this.requires = other.requires;
161 this.link = other.link;
162 this.description = other.description;
163 this.early = other.early;
164 this.author = other.author;
165 this.stage = other.stage;
166 this.version = other.version;
167 this.downloadlink = other.downloadlink;
168 this.icon = other.icon;
169 this.iconPath = other.iconPath;
170 this.libraries = other.libraries;
171 this.attr.clear();
172 this.attr.putAll(other.attr);
173 }
174
175 /**
176 * Updates the plugin information of this plugin information object with the
177 * plugin information in a plugin information object retrieved from a plugin
178 * jar.
179 *
180 * @param other the plugin information object retrieved from the jar file
181 * @since 5601
182 */
183 public void updateFromJar(PluginInformation other) {
184 updateLocalInfo(other);
185 if (other.icon != null) {
186 this.icon = other.icon;
187 }
188 this.early = other.early;
189 this.className = other.className;
190 this.libraries = other.libraries;
191 this.stage = other.stage;
192 }
193
194 private final void scanManifest(Manifest manifest, boolean oldcheck) {
195 String lang = LanguageInfo.getLanguageCodeManifest();
196 Attributes attr = manifest.getMainAttributes();
197 className = attr.getValue("Plugin-Class");
198 String s = attr.getValue(lang+"Plugin-Link");
199 if (s == null) {
200 s = attr.getValue("Plugin-Link");
201 }
202 if (s != null) {
203 try {
204 new URL(s);
205 } catch (MalformedURLException e) {
206 Main.info(tr("Invalid URL ''{0}'' in plugin {1}", s, name));
207 s = null;
208 }
209 }
210 link = s;
211 requires = attr.getValue("Plugin-Requires");
212 s = attr.getValue(lang+"Plugin-Description");
213 if (s == null) {
214 s = attr.getValue("Plugin-Description");
215 if (s != null) {
216 try {
217 s = tr(s);
218 } catch (IllegalArgumentException e) {
219 Main.info(tr("Invalid plugin description ''{0}'' in plugin {1}", s, name));
220 }
221 }
222 } else {
223 s = MessageFormat.format(s, (Object[]) null);
224 }
225 description = s;
226 early = Boolean.parseBoolean(attr.getValue("Plugin-Early"));
227 String stageStr = attr.getValue("Plugin-Stage");
228 stage = stageStr == null ? 50 : Integer.parseInt(stageStr);
229 version = attr.getValue("Plugin-Version");
230 s = attr.getValue("Plugin-Mainversion");
231 if (s != null) {
232 try {
233 mainversion = Integer.parseInt(s);
234 } catch(NumberFormatException e) {
235 Main.warn(tr("Invalid plugin main version ''{0}'' in plugin {1}", s, name));
236 }
237 } else {
238 Main.warn(tr("Missing plugin main version in plugin {0}", name));
239 }
240 author = attr.getValue("Author");
241 iconPath = attr.getValue("Plugin-Icon");
242 if (iconPath != null && file != null) {
243 // extract icon from the plugin jar file
244 icon = new ImageProvider(iconPath).setArchive(file).setMaxWidth(24).setMaxHeight(24).setOptional(true).get();
245 }
246 if (oldcheck && mainversion > Version.getInstance().getVersion()) {
247 int myv = Version.getInstance().getVersion();
248 for (Map.Entry<Object, Object> entry : attr.entrySet()) {
249 try {
250 String key = ((Attributes.Name)entry.getKey()).toString();
251 if (key.endsWith("_Plugin-Url")) {
252 int mv = Integer.parseInt(key.substring(0,key.length()-11));
253 if (mv <= myv && (mv > mainversion || mainversion > myv)) {
254 String v = (String)entry.getValue();
255 int i = v.indexOf(';');
256 if (i > 0) {
257 downloadlink = v.substring(i+1);
258 mainversion = mv;
259 version = v.substring(0,i);
260 oldmode = true;
261 }
262 }
263 }
264 }
265 catch(Exception e) {
266 Main.error(e);
267 }
268 }
269 }
270
271 String classPath = attr.getValue(Attributes.Name.CLASS_PATH);
272 if (classPath != null) {
273 for (String entry : classPath.split(" ")) {
274 File entryFile;
275 if (new File(entry).isAbsolute() || file == null) {
276 entryFile = new File(entry);
277 } else {
278 entryFile = new File(file.getParent(), entry);
279 }
280
281 libraries.add(Utils.fileToURL(entryFile));
282 }
283 }
284 for (Object o : attr.keySet()) {
285 this.attr.put(o.toString(), attr.getValue(o.toString()));
286 }
287 }
288
289 /**
290 * Replies the description as HTML document, including a link to a web page with
291 * more information, provided such a link is available.
292 *
293 * @return the description as HTML document
294 */
295 public String getDescriptionAsHtml() {
296 StringBuilder sb = new StringBuilder();
297 sb.append("<html><body>");
298 sb.append(description == null ? tr("no description available") : description);
299 if (link != null) {
300 sb.append(" <a href=\"").append(link).append("\">").append(tr("More info...")).append("</a>");
301 }
302 if (downloadlink != null && !downloadlink.startsWith("http://svn.openstreetmap.org/applications/editors/josm/dist/")
303 && !downloadlink.startsWith("http://trac.openstreetmap.org/browser/applications/editors/josm/dist/")) {
304 sb.append("<p>&nbsp;</p><p>"+tr("<b>Plugin provided by an external source:</b> {0}", downloadlink)+"</p>");
305 }
306 sb.append("</body></html>");
307 return sb.toString();
308 }
309
310 /**
311 * Loads and instantiates the plugin.
312 *
313 * @param klass the plugin class
314 * @return the instantiated and initialized plugin
315 * @throws PluginException if the plugin cannot be loaded or instanciated
316 */
317 public PluginProxy load(Class<?> klass) throws PluginException {
318 try {
319 Constructor<?> c = klass.getConstructor(PluginInformation.class);
320 Object plugin = c.newInstance(this);
321 return new PluginProxy(plugin, this);
322 } catch(NoSuchMethodException e) {
323 throw new PluginException(name, e);
324 } catch(IllegalAccessException e) {
325 throw new PluginException(name, e);
326 } catch (InstantiationException e) {
327 throw new PluginException(name, e);
328 } catch(InvocationTargetException e) {
329 throw new PluginException(name, e);
330 }
331 }
332
333 /**
334 * Loads the class of the plugin.
335 *
336 * @param classLoader the class loader to use
337 * @return the loaded class
338 * @throws PluginException if the class cannot be loaded
339 */
340 public Class<?> loadClass(ClassLoader classLoader) throws PluginException {
341 if (className == null)
342 return null;
343 try {
344 return Class.forName(className, true, classLoader);
345 } catch (ClassNotFoundException e) {
346 throw new PluginException(name, e);
347 } catch (ClassCastException e) {
348 throw new PluginException(name, e);
349 }
350 }
351
352 /**
353 * Try to find a plugin after some criterias. Extract the plugin-information
354 * from the plugin and return it. The plugin is searched in the following way:
355 *<ol>
356 *<li>first look after an MANIFEST.MF in the package org.openstreetmap.josm.plugins.&lt;plugin name&gt;
357 * (After removing all fancy characters from the plugin name).
358 * If found, the plugin is loaded using the bootstrap classloader.</li>
359 *<li>If not found, look for a jar file in the user specific plugin directory
360 * (~/.josm/plugins/&lt;plugin name&gt;.jar)</li>
361 *<li>If not found and the environment variable JOSM_RESOURCES + "/plugins/" exist, look there.</li>
362 *<li>Try for the java property josm.resources + "/plugins/" (set via java -Djosm.plugins.path=...)</li>
363 *<li>If the environment variable ALLUSERSPROFILE and APPDATA exist, look in
364 * ALLUSERSPROFILE/&lt;the last stuff from APPDATA&gt;/JOSM/plugins.
365 * (*sic* There is no easy way under Windows to get the All User's application
366 * directory)</li>
367 *<li>Finally, look in some typical unix paths:<ul>
368 * <li>/usr/local/share/josm/plugins/</li>
369 * <li>/usr/local/lib/josm/plugins/</li>
370 * <li>/usr/share/josm/plugins/</li>
371 * <li>/usr/lib/josm/plugins/</li></ul></li>
372 *</ol>
373 * If a plugin class or jar file is found earlier in the list but seem not to
374 * be working, an PluginException is thrown rather than continuing the search.
375 * This is so JOSM can detect broken user-provided plugins and do not go silently
376 * ignore them.
377 *
378 * The plugin is not initialized. If the plugin is a .jar file, it is not loaded
379 * (only the manifest is extracted). In the classloader-case, the class is
380 * bootstraped (e.g. static {} - declarations will run. However, nothing else is done.
381 *
382 * @param pluginName The name of the plugin (in all lowercase). E.g. "lang-de"
383 * @return Information about the plugin or <code>null</code>, if the plugin
384 * was nowhere to be found.
385 * @throws PluginException In case of broken plugins.
386 */
387 public static PluginInformation findPlugin(String pluginName) throws PluginException {
388 String name = pluginName;
389 name = name.replaceAll("[-. ]", "");
390 InputStream manifestStream = PluginInformation.class.getResourceAsStream("/org/openstreetmap/josm/plugins/"+name+"/MANIFEST.MF");
391 if (manifestStream != null)
392 return new PluginInformation(manifestStream, pluginName, null);
393
394 Collection<String> locations = getPluginLocations();
395
396 for (String s : locations) {
397 File pluginFile = new File(s, pluginName + ".jar");
398 if (pluginFile.exists()) {
399 return new PluginInformation(pluginFile);
400 }
401 }
402 return null;
403 }
404
405 /**
406 * Returns all possible plugin locations.
407 * @return all possible plugin locations.
408 */
409 public static Collection<String> getPluginLocations() {
410 Collection<String> locations = Main.pref.getAllPossiblePreferenceDirs();
411 Collection<String> all = new ArrayList<String>(locations.size());
412 for (String s : locations) {
413 all.add(s+"plugins");
414 }
415 return all;
416 }
417
418 /**
419 * Replies true if the plugin with the given information is most likely outdated with
420 * respect to the referenceVersion.
421 *
422 * @param referenceVersion the reference version. Can be null if we don't know a
423 * reference version
424 *
425 * @return true, if the plugin needs to be updated; false, otherweise
426 */
427 public boolean isUpdateRequired(String referenceVersion) {
428 if (this.downloadlink == null) return false;
429 if (this.version == null && referenceVersion!= null)
430 return true;
431 if (this.version != null && !this.version.equals(referenceVersion))
432 return true;
433 return false;
434 }
435
436 /**
437 * Replies true if this this plugin should be updated/downloaded because either
438 * it is not available locally (its local version is null) or its local version is
439 * older than the available version on the server.
440 *
441 * @return true if the plugin should be updated
442 */
443 public boolean isUpdateRequired() {
444 if (this.downloadlink == null) return false;
445 if (this.localversion == null) return true;
446 return isUpdateRequired(this.localversion);
447 }
448
449 protected boolean matches(String filter, String value) {
450 if (filter == null) return true;
451 if (value == null) return false;
452 return value.toLowerCase().contains(filter.toLowerCase());
453 }
454
455 /**
456 * Replies true if either the name, the description, or the version match (case insensitive)
457 * one of the words in filter. Replies true if filter is null.
458 *
459 * @param filter the filter expression
460 * @return true if this plugin info matches with the filter
461 */
462 public boolean matches(String filter) {
463 if (filter == null) return true;
464 String[] words = filter.split("\\s+");
465 for (String word: words) {
466 if (matches(word, name)
467 || matches(word, description)
468 || matches(word, version)
469 || matches(word, localversion))
470 return true;
471 }
472 return false;
473 }
474
475 /**
476 * Replies the name of the plugin.
477 * @return The plugin name
478 */
479 public String getName() {
480 return name;
481 }
482
483 /**
484 * Sets the name
485 * @param name
486 */
487 public void setName(String name) {
488 this.name = name;
489 }
490
491 /**
492 * Replies the plugin icon, scaled to 24x24 pixels.
493 * @return the plugin icon, scaled to 24x24 pixels.
494 */
495 public ImageIcon getScaledIcon() {
496 if (icon == null)
497 return emptyIcon;
498 return new ImageIcon(icon.getImage().getScaledInstance(24, 24, Image.SCALE_SMOOTH));
499 }
500
501 @Override
502 public final String toString() {
503 return getName();
504 }
505
506 private static List<String> getRequiredPlugins(String pluginList) {
507 List<String> requiredPlugins = new ArrayList<String>();
508 if (pluginList != null) {
509 for (String s : pluginList.split(";")) {
510 String plugin = s.trim();
511 if (!plugin.isEmpty()) {
512 requiredPlugins.add(plugin);
513 }
514 }
515 }
516 return requiredPlugins;
517 }
518
519 /**
520 * Replies the list of plugins required by the up-to-date version of this plugin.
521 * @return List of plugins required. Empty if no plugin is required.
522 * @since 5601
523 */
524 public List<String> getRequiredPlugins() {
525 return getRequiredPlugins(requires);
526 }
527
528 /**
529 * Replies the list of plugins required by the local instance of this plugin.
530 * @return List of plugins required. Empty if no plugin is required.
531 * @since 5601
532 */
533 public List<String> getLocalRequiredPlugins() {
534 return getRequiredPlugins(localrequires);
535 }
536
537 /**
538 * Updates the local fields ({@link #localversion}, {@link #localmainversion}, {@link #localrequires})
539 * to values contained in the up-to-date fields ({@link #version}, {@link #mainversion}, {@link #requires})
540 * of the given PluginInformation.
541 * @param info The plugin information to get the data from.
542 * @since 5601
543 */
544 public void updateLocalInfo(PluginInformation info) {
545 if (info != null) {
546 this.localversion = info.version;
547 this.localmainversion = info.mainversion;
548 this.localrequires = info.requires;
549 }
550 }
551}
Note: See TracBrowser for help on using the repository browser.