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

Last change on this file since 14379 was 14378, checked in by Don-vip, 6 years ago

fix #16907 - fix plugin manifest property name mismatch: use Plugin-Minimum-Java-Version

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