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

Last change on this file since 17379 was 16874, checked in by stoecker, 4 years ago

deprecate OSM svn, see #19509

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