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

Last change on this file since 13193 was 12620, checked in by Don-vip, 7 years ago

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

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